<template>
  <el-dialog
    v-model="visible"
    :fullscreen="true"
    destroy-on-close
    :show-close="false"
    :close-on-click-modal="false"
    :append-to-body="false"
    class="custom-dialog"
    @closed="$emit('closed')"
  >
    <el-container direction="vertical" style="position: relative">
      <div style="flex-shrink: 0; box-sizing: border-box">
        <el-card style="position: relative">
          <div style="text-align: center; font-size: 22px; font-weight: 600">
            {{ title }}
          </div>

          <div
            style="
              position: absolute;
              right: 10px;
              top: 0;
              height: 100%;
              display: flex;
              align-items: center;
            "
          >
            <el-button type="primary" plain @click="save" >保存</el-button>
            <el-button type="info" plain @click="back">取消</el-button>
          </div>
        </el-card>
      </div>
      <el-main>
        <el-card style="margin-top: 15px">
          <sc-form
            ref="formref"
            :config="formConfig"
            v-model="form"
            :formMode="mode"
          >
          </sc-form>
        </el-card>

        <el-card style="margin-top: 15px">
          <div style="padding: 0px 10px 10px 0" >
            <el-button type="primary" plain @click="add_materials"
              >添加</el-button
            >
            <el-button type="info" plain @click="delete_materials"
              >删除</el-button
            >
          </div>
          <scTable
            ref="table"
            :data="listData"
            :column="column"
            hidePagination
            hideDo
            row-key=""
            @selection-change="selectionChange"
          >
            <el-table-column  type="selection" width="50"></el-table-column>

            <!-- 退货数量 -->
            <template #productionLength="scoped">
              <el-input-number
                v-model="scoped.row.productionLength"
                :step="1"
                :min="1"
                :precision="0"
                :controls="true"
              ></el-input-number>
              <!-- <div v-else> {{ scoped.row.returnQuantity }} </div> -->
            </template>

            <!-- 排产支数 -->
            <template #productionPieces="scoped">
              <el-input-number
                v-model="scoped.row.productionPieces"
                :step="1"
                :min="1"
                :max="Number(scoped.row.plannedPieces) - Number(scoped.row.productionedPieces)"
                :precision="0"
                :controls="true"
                
              ></el-input-number>
              <!-- <div v-else> {{ scoped.row.returnQuantity }} </div> -->
            </template>

            <!-- 锯切方式 -->
            <template #sawingMethod="scoped">
              <el-input
                v-model="scoped.row.sawingMethod"
              ></el-input>
              <!-- <div v-else> {{ scoped.row.sawingMethod }} </div> -->
            </template>
          </scTable>
        </el-card>
      </el-main>
      <!-- <select-page
        ref="selectPage"
        v-if="dialog.selectPage"
        @success="handleSuccess"
        @closed="dialog.selectPage = false"
      ></select-page> -->
        <materialsSelect
          v-if="dialog.product"
          ref="materialsSelect"
          @success="handleSuccess"
          @closed="dialog.product = false"
        ></materialsSelect>
    </el-container>
  </el-dialog>
</template>

<script>
import useTabs from "@/utils/useTabs";
import selectPage from "./selectPage";
import materialsSelect from "./materialsSelect";

import module from "./module";

export default {
  emits: ["success", "closed"],
  components: {
    selectPage,
    materialsSelect
  },
  data() {
    return {
      formConfig: module.pageForm.form,
      form: {},
      title: module.pageForm.title,
      column: module.pageForm.column,
      initComputed: module.pageForm.computed,
      listData: [],
      selection: [],
      dialog: {
        product: false,
      },
      supplier: {},
      path: this.$route.query.path,
      detailId: this.$route.query.id,
      mode: "add",
      dialog: {
        selectPage: false,
      },
      visible: false,
      orderInfo: {}
    };
  },
  watch: {
    "form.supplier": {
      handler(value, old) {
        const _this = this;
        for (let i = 0, len = this.formConfig.formItems.length; i < len; i++) {
          const item = this.formConfig.formItems[i];
          if (item.name == "supplier") {
            const items = item.options.items;
            if (!items) {
              break;
            }
            for (let j = 0, len1 = items.length; j < len1; j++) {
              if (items[j].value == value) {
                _this.supplier = items[j];
              }
            }
            break;
          }
        }
      },
    },
    listData: {
      handler(newVal) {
        if (!newVal) return;
        newVal.forEach((item) => {
          /* 支数 */
          item["pieces"] = parseFloat(
            Number(item["piecesBundle"]) * Number(item["returnQuantity"])
          );

          /* 排产理论重量 */
          item["productionWeight"] = parseFloat(
            (
              Number(item["weight"]) *
              Number(item["productionLength"]) *
              Number(item["productionPieces"])
            ).toFixed(2)
          );

          /* 理论重量 */
          item["theoreticalWeight"] = parseFloat(
            (
              Number(item["weight"]) *
              Number(item["defaultLength"]) *
              Number(item["returnQuantity"])
            ).toFixed(2)
          );

          // item["salespersonName"] = this.orderInfo.salespersonName;
          // item["salesOrderCode"] = this.orderInfo.documentNumber;
          item["undeliveredQuantity"] = item["orderTotalQuantity"] - item["producedPieces"]
        });
      },
      deep: true,
    },
  },
  created() {},
  mounted() {
    // this.loadDetail();
  },
  methods: {
    open(mode="add") {
      this.mode = mode;
      this.visible = true;
      return this;
    },
    setData(row) {
      this.loadDetail(row.scheduleNumber)
    },
    async loadDetail(scheduleNumber) {
      var res = await this.$API[module.name][module.detail].http({
        scheduleNumber: scheduleNumber,
      });

      if (res.code == 0) {
        this.form = res.data.orderInfo;
        this.listData = res.data.materials;

        this.$nextTick(function () {
          this.$forceUpdate();
        });
      }
    },
    selectionChange(selection) {
      this.selection = selection;
    },
    add_materials() {
      this.$refs.formref.validate(async (valid, obj) => {
        if (valid) {
          this.dialog.product = true;
          this.$nextTick(() => {
            this.$refs.materialsSelect.open().setData(this.listData);
          });
        }
      })
    },
    delete_materials() {
      this.listData = this.listData.filter(
        (item1) =>
          !this.selection.some(
            (item2) => item2.materialCode === item1.materialCode
          )
      );
      this.selection = [];
    },
    handleSuccess(data, orderInfo) {
      const _this = this;
      this.orderInfo = orderInfo;
      console.log("1", this, this.listData)
      data.forEach((item) => {
        for (let key in _this.initComputed) {
          if (!item[key]) {
            item[key] = _this.initComputed[key];
          }
        }
      });
      console.log("2", this, this.listData)
      this.listData = [...data];
    },
    async queryInventoryQuantity(row) {
      // 查看现有库存
      const res = await this.$API.currentInventory.queryInventory.http({
        materialCode: row.materialCode,
        supplier: this.orderInfo.supplier,
      })

      if (res.code == 0) {
        row.inventoryQuantity = res.data || 0;
      }
    },
    back() {
      // useTabs.closeNext((tags) => {
      //   //回调返回所有标签的数组，这里其实是需要判断是否含有'/usercenter'，含有再操作的，这里为了演示就直接打开了。
      //   console.log(tags);
      //   this.$router.push(this.path);
      //   this.$route.is = true;
      // });
      this.visible = false;
    },
    save() {
      this.$refs.formref.validate(async (valid, obj) => {
        if (valid) {
          // this.$message.success("操作成功");
          if (this.listData.length <= 0) {
            this.$alert("请选择物料", "提示", { type: "error" });
            return;
          }

          const params = {
            materials: this.listData,
            orderInfo: this.form,
          };
          console.log(params);

          var res = null;
          if (this.mode == "edit") {
            res = await this.$API[module.name][module.edit].http(params);
          } else {
            res = await this.$API[module.name][module.add].http(params);
          }

          this.isSaveing = false;
          if (res.code == 0) {
            this.$emit("success");
            this.$message.success("操作成功");
            this.back();
          } else {
            this.$alert(res.message, "提示", { type: "error" });
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .el-overlay {
  position: absolute;

  .el-dialog__header {
    padding: 0;
  }
  .el-dialog__body {
    padding: 0;
    height: 100%;
  }
}
</style>
