<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">
      <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" v-if="mode=='add'">保存</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" v-if="mode=='add'">
            <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 #warehouse="scoped">
              <thirdselect
                v-model="scoped.row.warehouse"
                :item="warehousesItem"
              >
              </thirdselect>
            </template>

            <!-- 入库数量 -->
            <template #receiptQuantity="scoped">
              <el-input-number
                v-model="scoped.row.receiptQuantity"
                :step="1"
                :min="1"
                :precision="0"
                :controls="true"
                v-if="mode=='add'"
              ></el-input-number>
              <span v-else>{{ scoped.row.receiptQuantity }}</span>
            </template>
            
            <!-- 包装数量 -->
            <template #packingQuantity="scoped">
              <el-input-number
                v-model="scoped.row.packingQuantity"
                :step="1"
                :min="1"
                :precision="0"
                :controls="true"
                v-if="mode=='add'"
              ></el-input-number>
              <span v-else>{{ scoped.row.packingQuantity }}</span>
            </template>


            <!-- 实际重量 -->
            <template #actualWeight="scoped">
              <el-input-number
                v-model="scoped.row.actualWeight"
                :step="0.01"
                :min="0"
                :precision="2"
                :controls="true"
                v-if="mode=='add'"
              ></el-input-number>
              <span v-else>{{ scoped.row.actualWeight }}</span>
            </template>
          </scTable>
        </el-card>
      </el-main>
    </el-container>
  </el-dialog>
  <materialsSelect
    v-if="dialog.product"
    ref="materialsSelect"
    @success="handleSuccess"
    @closed="dialog.product = false"
  ></materialsSelect>
</template>

<script>
import useTabs from "@/utils/useTabs";

import module from "./module";
import materialsSelect from "./materialsSelect";
import thirdselect from '@/components/scForm/items/thirdselect'

export default {
  emits: ["success", "closed"],
  components: {
    materialsSelect,
    thirdselect
  },
  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",
      visible: false,
      warehousesItem: {
        options: { tb: 'warehouses' }
      }
    };
  },
  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) {
        newVal.forEach((item) => {
          /* 支数 */
          item["pieces"] = parseFloat(
            Number(item["piecesBundle"]) * Number(item["receiptQuantity"])
          );

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

          /* 单价 */
          item["unitPrice"] = parseFloat(
            ((Number(this.form["price"]) || 0) / 1000).toFixed(2)
          );

          /* 金额 */
          item["amount"] = parseFloat(
            (
              Number(item["unitPrice"]) * Number(item["receiptQuantity"])
            ).toFixed(2)
          );

          /* 税率 */
          item["taxRate"] = parseFloat(this.supplier["tax"]);

          /* 含税单价 */
          item["priceWithTax"] = parseFloat(
            (Number(item["unitPrice"]) +
              parseFloat(
                (Number(item["unitPrice"]) * Number(item["taxRate"])).toFixed(2)
              )).toFixed(2)
          );

          /* 含税金额 */
          item["amountWithTax"] = parseFloat(
            (
              Number(item["priceWithTax"]) * Number(item["receiptQuantity"])
            ).toFixed(2)
          );
        });
      },
      deep: true,
    },
  },
  created() {},
  mounted() {
    //修改tab名称
    // this.$store.commit(
    //   "updateViewTagsTitle",
    //   this.id ? `CURD编辑ID:${this.id}` : "CURD新增"
    // );
    // this.loadDetail();
  },
  methods: {
    open(mode="add") {
      this.mode = mode;
      this.visible = true;
      return this;
    },
    setData(row) {
      this.loadDetail(row.documentNumber)
    },
    async loadDetail(documentNumber) {
      var res = await this.$API[module.name][module.detail].http({
        documentNumber: documentNumber,
      });

      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) {
      const _this = this;
      data.forEach((item) => {
        for (let key in _this.initComputed) {
          if (!item[key]) {
            item[key] = _this.initComputed[key];
          }
        }
      });
      this.listData = [...data, ...this.listData];
    },
    async queryInventoryQuantity(row) {
      // 查看现有库存
      const res = await this.$API.currentInventory.queryInventory.http({
        materialCode: row.materialCode,
        supplier: this.form.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>
</style>
