<!--
  @name: 采购订单管理明细
 -->
<template>
  <p-spin :spinning="spinning">
    <p-card>
      <div slot="title" style="display: inline-block; cursor: pointer" @click="backPage">
        <a-icon type="arrow-left" style="color: #1990ff" class="mr-10" />
        入库订单-{{ typeTitle }}
      </div>
      <div slot="extra" v-show="type !== 'view'">
        <p-button class="ml-10" @click="onReset">重置</p-button>
        <p-button style="margin-left: 5px" type="primary" class="ml-10" @click="onSave">保存</p-button>
      </div>
      <p-grid-form ref="formTarget" :span="8" :labelCol="{ span: 6 }" :items="detailItems" />
    </p-card>
    <p-card title="采购订单明细列表">
      <div class="btnList" slot="extra">
        <p-button type="primary" @click="onAdd">新增</p-button>
      </div>
      <div class="table">
        <p-table-edit-pro
          ref="table"
          bordered
          dragle
          :columns="columns"
          :dataSource.sync="tableData"
          row-key="lineid"
          :rowSelectType="false"
          :scroll="{ x: true }"
        >
          <span slot="action" slot-scope="text, record">
            <div>
              <a @click="grid_deleteClick(record)">删除</a>
            </div>
          </span>
        </p-table-edit-pro>
      </div>
    </p-card>
  </p-spin>
</template>

<script>
import { queryOmsPoBillDNo, save } from "./api";
import { detailItems, columns } from "./js/config";
import { getDefaultCargoOwner } from "@/views/kzyWMS/utils/setCargoOwner";

export default {
  props: {
    type: "",
    data: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  watch: {
    data: {
      handler(val) {
        console.log(val, "val");
        this.formData = Object.assign({}, this.formData, val);
        if (this.formData.billid) {
          console.log(this.formData, "formDataformData");
          this.queryDetails(this.formData);
        }
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      spinning: false,
      detailItems: detailItems(this),
      columns: columns(this),
      tableData: [],
    };
  },
  mounted() {
    // 设置订单状态为刚生成
    this.$refs.formTarget.form.setFieldsValue({ status: "10" });
    if (this.type === "add") {
      this.setDefaultData();
    }
    if (this.type === "edit") {
    }
  },
  computed: {
    typeTitle() {
      const dictionary = {
        add: "新增",
        edit: "编辑",
        view: "查看",
      };
      return dictionary[this.type] || this.type;
    },
  },
  methods: {
    // 设置默认数据
    async setDefaultData() {
      // 设置仓库
      const { warehouseId, warehouseCode, warehouseName } = this.$store.getters.warehouse || {};
      this.$refs.formTarget.form.setFieldsValue({
        branchid: warehouseId,
        branchcode: warehouseCode,
        branchname: warehouseName,
      });
      // 设置货主
      const cargoOwner = await getDefaultCargoOwner();
      if (!!cargoOwner) {
        const { companyCode, companyId, companyName } = cargoOwner;
        console.log(cargoOwner);
        this.$refs.formTarget.form.setFieldsValue({
          consignorid: companyId,
          consignorcode: companyCode,
          consignorname: companyName,
        });
        this.$refs.formTarget.form.disableItem("consignorname");
      }
    },
    backPage() {
      this.$emit("back");
    },
    // 查询明细
    queryDetails(data) {
      this.spinning = true;
      this.$nextTick(() => {
        data.warehouseId = data.branchid;
        data.warehouseCode = data.branchcode;
        data.warehouseName = data.branchname;
        data.cargoOwnerId = data.consignorid;
        data.cargoOwnerCode = data.consignorcode;
        data.cargoOwnerName = data.consignorname;
        data.supplierId = data.shipperid;
        data.supplierName = data.shippername;
        data.supplierCode = data.shippercode;
        this.$refs.formTarget.form.setFieldsValue(data);
      });
      queryOmsPoBillDNo({ billId: this.formData.billid, pageSize: 10, pageNum: 1 })
        .then((res) => {
          this.spinning = false;
          let list = res.data.list;
          list.forEach((t) => {
            t.itemCode = t.itemcode;
            t.itemName = t.itemname;
            t.manufacturerName = t.manufacturer;
          });
          this.tableData = list;
        })
        .catch(() => {
          this.spinning = false;
        });
    },
    // 保存
    onSave() {
      const that = this;
      this.$refs.formTarget.form.validateFields((error, values) => {
        if (error) return;
        delete values.adata;
        delete values.bdata;
        // 字段转换
        values.shipperid = values.supplierId;
        values.shippercode = values.supplierCode;
        values.shippername = values.supplierName;
        values.shipperType = 2;
        console.log(values, that.tableData, "values");
        let params = values;
        params.detailList = that.tableData;
        if (that.type === "add") {
          params.detailList.forEach((item) => {
            item.lineid = "";
          });
        }
        //件数或零散数必须大于0
        let num = 0;
        params.detailList.forEach((item) => {
          if (item.itemQty <= 0) {
            num = 1;
          }
        });
        if (num == 1) {
          this.$message.warn("请注意数量不能为0！！");
          return;
        }
        console.log(params);
        // return;
        that.$confirm({
          content: that.$lang("是否确定提交?"),
          onOk: () => {
            return save([params]).then((res) => {
              // that.spinning = false
              if (res.success) {
                that.$message.success(res.message);
                that.$emit("back");
              } else {
                that.$message.warn(res.message);
              }
            });
          },
        });
      });
    },
    // 新增明细
    onAdd() {
      const { cargoOwnerId, cargoOwnerName, cargoOwnerCode, warehouseId, billid, billno } =
        this.$refs.formTarget.form.getFieldsValue();
      // if (!cargoOwnerId) return this.$message.warn('请选择货主')
      // if (!warehouseId) return this.$message.warn('请选择收货仓库')
      this.$refs.table.createRow(0, {
        consignorname: cargoOwnerName,
        consignorid: cargoOwnerId,
        consignorcode: cargoOwnerCode,
        billid,
        billno,
      });
    },
    // 删除明细
    grid_deleteClick(record) {
      let index = this.tableData.findIndex((item) => item.lineid === record.lineid);
      this.tableData.splice(index, 1);
      this.$message.success("明细删除成功");
      return;
    },
    //重置
    onReset() {
      this.$refs.formTarget.form.resetFields();
      this.tableData = [];
    },
  },
};
</script>

<style lang="less"></style>
