<template>
  <div>
    <a-spin :spinning="loading">
      <detail-page ref="detail" :list="detailtList" :isView="isView" :defData="detailData" @ok="onOk"> </detail-page>
    </a-spin>
  </div>
</template>

<script>
import DetailPage from "../components/bill-editor/index";
import { detailConfig } from "./config/position";
import { moveLocator } from "../api/api";
import { getCargoOwner } from "../../utils/index";
export default {
  components: { DetailPage },
  props: {
    detailItem: {
      type: Object,
      default: null,
    },
    isView: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {
      isReady: false,
      detailtList: null,
      dcId: "",
      detailData: null,
      loading: false,
      visible: false,
      formsVal: {},
    };
  },
  created() {
    // if (this.detailItem)
    //   this.getData().then(res => {
    //     this.isReady = true
    //   })
    // else this.isReady = true
    this.handleView();
    this.getAuthBycargoOwner();
  },
  mounted() {
    let user = this.$store.state.user;
    let warehouse = this.$store.state.user.warehouse;
    let today = new Date();
    let tYear = today.getFullYear();
    let tMonth = today.getMonth() + 1;
    let tDate = today.getDate();
    let day = tYear + "-" + tMonth + "-" + tDate;
    this.queryRefFromName("main").form.setFieldsValue({
      today: day,
      warehouseName: warehouse.warehouseName,
      warehouseId: warehouse.warehouseId,
      warehouseWorkerId: user.info.userId,
      warehouseWorkerName: user.info.username,
      departmentId: user.info.organizations ? (user.info.organizations[0] ? user.info.organizations[0].id : "") : "",
      departmentName: user.info.organizations
        ? user.info.organizations[0]
          ? user.info.organizations[0].name
          : ""
        : "",
    });
  },
  methods: {
    async getAuthBycargoOwner() {
      await getCargoOwner().then((res) => {
        if (res.success) {
          this.$nextTick(() => {
            this.queryRefFromName("main").form.setFieldsValue({
              cargoOwnerId: res.data.list[0].companyId,
              cargoOwnerName: res.data.list[0].companyName,
              cargoOwnerCode: res.data.list[0].companyCode,
            });
          });
        }
        if (!res.success) {
          this.$exception(res);
          return;
        }
      });
    },
    onOk() {
      let today = new Date();
      let tYear = today.getFullYear();
      let tMonth = today.getMonth() + 1;
      let tDate = today.getDate();
      let day = tYear + "-" + tMonth + "-" + tDate;
      this.queryRefFromName("main").form.setFieldsValue({
        today: day,
        warehouseId: this.$store.state.user.warehouse.warehouseId,
        warehouseName: this.$store.state.user.warehouse.warehouseName,
      });
    },
    toBack() {
      this.$emit("changeStep", { step: 1, item: null });
    },
    queryRefFromName(name) {
      return this.$refs.detail.$refs[name][0];
    },
    getData() {
      return queryItem({ itemId: this.detailItem.itemId }).then((res) => {
        if (!res.success) {
          this.$message.error(res.message);
          return;
        }
        let d = { main: {} };
        Object.keys(res.data).forEach((k) => {
          if (res.data[k] === null) {
            // d.main[k] = res.data[k];
            d.main[k] = "";
          } else if (typeof res.data[k] === "object") {
            d[k] = res.data[k];
          } else {
            d.main[k] = res.data[k];
          }
        });
        this.detailData = d;
      });
    },
    getDetailData() {
      let vals = this.$refs.detail.getDetailData();
      let main = vals.main;
      delete vals.main;
      let params = { ...main, ...vals };
      // console.log('vals', vals);
      if (!vals) {
        return;
      }
      if (this.detailItem) {
        this.$confirm({
          content: this.$lang("是否提交修改?"),
          onOk: () => {
            return this.handleUpload(params);
          },
        });
      } else {
        this.$confirm({
          content: this.$lang("是否确定提交?"),
          onOk: () => {
            return this.handleAdd(params);
          },
        });
      }
    },
    saveData(datas) {
      console.log(datas, "datasdatasdatas");

      let vals = this.$refs.detail.getDetailData();
      let main = vals.main;
      console.log(datas, vals, main);
      //   return;
      if (!datas) {
        return;
      }
      if (datas.length < 1) {
        return this.$message.warn("请选择商品");
      }
      console.log(vals);
      let statusNum = true;
      datas.map((res) => {
        if (!res.oddPieceQuantity) {
          res.oddPieceQuantity = 0;
        }
        if (!res.caseQuantity) {
          res.caseQuantity = 0;
        }
        console.log(res.numData);
        if (Number(res.numData) <= 0) {
          statusNum = false;
          return this.$message.warn("移位数量不能为0！");
        }
        if (res.outLocatorId && res.outLocatorId == res.inLocatorId) {
          statusNum = false;
          return this.$message.warn("移出货位与移入货位不能相同！");
        }
      });
      if (!statusNum) return;
      let params = {
        moveDetails: datas,
        ...main,
      };
      //   .保存时校验【移出库别】=【立库】或【移入库别】=【立库】则提示“立库不能进行货位调整操作”（立库货位调整从EIS发起）；
      let s = datas.some((i) => {
        if (i.outwarehouseAreaCategory == "立库" || i.inwarehouseAreaCategory == "立库") {
          return true;
        } else {
          return false;
        }
      });
      console.log(s);
      if (s) this.$message.warn("立库不能进行货位调整操作!");

      let a = datas.some((i) => {
        console.log(i);
        return i.outwarehouseAreaCategoryCode != i.inwarehouseAreaCategory;
      });
      //   console.log(s);
      if (a) this.$message.warn("移位操作只能在同库别内操作!");
      //   return;

      this.loading = true;
      moveLocator(params).then((res) => {
        this.loading = false;
        if (!res.success) {
          return this.$exception(res);
        }
        this.$message.success("保存成功");
        this.$refs.detail.$refs["baseMtlItemUomConversionsList"][0].delItems();
      });
    },
    handleView() {
      let arr = detailConfig(this);
      if (this.isView) {
        arr.forEach((t) => {
          t.list.forEach((tt) => {
            if (tt.item.type === "p-grid-form") {
              tt.item.config = tt.item.config.map((t) => ({ ...t, disabled: true, placeholder: "" }));
            } else if (tt.item.type === "p-table-edit") {
            }
          });
        });
      }
      this.detailtList = arr;
    },

    handleAdd(params) {
      return addItem(params).then((res) => {
        if (!res.success) {
          this.$message.error(res.message);
          return;
        }
        this.$message.success(this.$lang("新增成功"));
        this.toBack();
      });
    },

    handleUpload(params) {
      params.itemId = this.detailItem.itemId;
      return uploadItem(params).then((res) => {
        if (!res.success) {
          this.$message.error(res.message);
          return;
        }
        this.$message.success(this.$lang("新增成功"));
        this.toBack();
      });
    },
  },
};
</script>

<style></style>
