<template>
  <div>
    <searchTable
      :tableColumns="columns"
      :title="title"
      :tableRemoteUrl="tableRemoteUrl"
      :tableRowKey="tableRowKey"
      :btnOptions="btnOptions"
      :tableAutoLoad="false"
      :items="items"
      :spinning="spinning"
      :ajaxId="ajaxId"
      @savePlan="savePlan"
      @savePlanAll="savePlanAll"
      @selectChange="selectChange"
      ref="detial"
    />
  </div>
</template>

<script>
import searchTable from "../components/searchTable";
// import { detailConfig } from './config/planCheck'
import { invcheckAdd } from "../api/api";
import API from "../api/default";
import { remote } from "../api/remote";
import {
  genWarehouseAuthSearchModal,
  genBldgSearchModal,
  genWarehouseRoomSearchModal,
  genCargoownerAuthSearchModal,
} from "../../SearchModal";
import { sorter } from "../../utils/sort";
import { diffOption } from "@/views/kzyWMS/utils/index.js";
import { SERVICE_DATA_API_BASE, upcloud_base_common } from "@/config/serviceSettings";
import { getCargoOwner } from "../../utils/index";

let warehouseId = "";
let bldgId = "";
let warehouseRoomId = "";
let warehouseAreaId = "";
let warehouseLocatorId = "";
const items = (self) => {
  return [
    ...genWarehouseAuthSearchModal(
      1,
      true,
      false,
      null,
      function (modalRowData, form) {
        if (modalRowData) {
          warehouseId = modalRowData[0].warehouseId ? modalRowData[0].warehouseId : modalRowData[0].companyId;
        } else {
          form.setFieldsValue({
            bldgId: "",
            bldgName: "",
            warehouseRoomId: "",
            warehouseRoomName: "",
            warehouseAreaId: "",
            warehouseAreaName: "",
            warehouseLocatorId: "",
            warehouseLocatorName: "",
          });
          warehouseId = "";
          bldgId = "";
          warehouseRoomId = "";
          warehouseAreaId = "";
          warehouseLocatorId = "";
        }
      },
      { span: 8 }
    ),
    ...genBldgSearchModal(
      1,
      false,
      false,
      function (res, remoteParams) {
        remoteParams.params.warehouseId = warehouseId; // 添加仓库id查询
        return remoteParams;
      },
      function (modalRowData, form) {
        if (modalRowData) {
          bldgId = modalRowData[0].bldgId;
        } else {
          bldgId = "";
          warehouseRoomId = "";
          warehouseAreaId = "";
          warehouseLocatorId = "";
          form.setFieldsValue({
            warehouseRoomId: "",
            warehouseRoomName: "",
            warehouseAreaId: "",
            warehouseAreaName: "",
            warehouseLocatorId: "",
            warehouseLocatorName: "",
          });
        }
      },
      { span: 8 }
    ),
    ...genWarehouseRoomSearchModal(
      1,
      false,
      false,
      function (res, remoteParams) {
        remoteParams.params.warehouseId = warehouseId; // 添加仓库id查询
        remoteParams.params.bldgId = bldgId; // 添加建筑物id查询
        return remoteParams;
      },
      function (modalRowData, form) {
        if (modalRowData) {
          warehouseRoomId = modalRowData[0].warehouseRoomId;
        } else {
          warehouseRoomId = "";
          form.setFieldsValue({
            warehouseAreaId: "",
            warehouseAreaName: "",
            warehouseLocatorId: "",
            warehouseLocatorName: "",
          });
          warehouseAreaId = "";
          warehouseLocatorId = "";
        }
      },
      { span: 8 }
    ),
    {
      type: "select",
      name: "warehouseAreaCategory",
      label: "库别",
      value: "",
      span: 8,
      ...remote("wms_storeroom"),
      // options: [
      //   { label: '零货库', value: '零货库' },
      //   { label: '整件库', value: '整件库' },
      //   { label: '退货库', value: '退货库' },
      //   { label: '不合格库', value: '不合格库' }
      // ]
    },
    ...genCargoownerAuthSearchModal(1, true, false, null, null, { span: 8 }),
    {
      type: "select",
      name: "checkWay",
      label: "盘点方式",
      allowClear: false,
      span: 8,
      required: true,
      defaultValueIndex: 0,
      value: "",
      ...remote("inv_stockcheck_h_checkgroup2"),
      on: {
        change(value, label, options, form) {
          console.log(form.getFieldsValue());
          console.log(value);
        },
      },
    },
    { type: "input", name: "warehouseAreaId", label: "库区ID", hidden: true },
    {
      type: "search",
      name: "warehouseAreaName",
      label: "库区",
      targetValueKey: "warehouseAreaName",
      destroyOnClose: true,
      targetClick: true,
      span: 8,
      toolBar: {
        items: [
          {
            type: "input",
            name: "warehouseAreaName",
            label: "库区名称",
            span: 8,
            value: "",
          },
          {
            type: "input",
            name: "warehouseAreaCode",
            label: "库区编码",
            span: 8,
            value: "",
          },
        ],
      },
      tableConfig: {
        rowKey: "warehouseAreaId",
        rowSelectType: 1,
        hasRowSelectCheck: true,
        columns: [
          { dataIndex: "warehouseAreaName", title: "库区名称", key: "warehouseAreaName" },
          { dataIndex: "warehouseAreaCode", title: "库区编码", key: "warehouseAreaCode" },
          { dataIndex: "warehouseAreaId", title: "库区ID", key: "warehouseAreaId" },
        ],
        remoteBefore(res, remoteParams) {
          console.log(arguments, "66666666");
          remoteParams.params.warehouseId = warehouseId; // 添加仓库id查询
          remoteParams.params.bldgId = bldgId; // 添加建筑物查询
          remoteParams.params.warehouseRoomId = warehouseRoomId; // 添加库房查询
        },
      },
      value: "",
      remoteUrl: API.wmsWhArea,
      on: {
        ok(event, value, rowData, form) {
          form.setFieldsValue({
            warehouseAreaId: rowData[0].warehouseAreaId,
          });
          warehouseAreaId = rowData[0].warehouseAreaId;
        },
        change(event, value, options, form) {
          if (!value) {
            form.setFieldsValue({ warehouseAreaId: "" });
            warehouseAreaId = "";
          }
          form.setFieldsValue({
            warehouseLocatorId: "",
            warehouseLocatorName: "",
          });
          warehouseLocatorId = "";
        },
      },
    },
    { type: "input", name: "warehouseLocatorId", label: "货位ID", hidden: true },
    { type: "input", name: "warehouseLocatorCode", label: "货位" },
    // {
    //   type: 'search',
    //   name: 'warehouseLocatorName',
    //   label: '货位',
    //   targetValueKey: 'warehouseLocatorName',
    //   destroyOnClose: true,
    //   targetClick: true,
    //   span: 8,
    //   value: '',
    //   toolBar: {
    //     items: [
    //       {
    //         type: 'input',
    //         name: 'warehouseLocatorName',
    //         label: '货位名称',
    //         span: 8,
    //         value: ''
    //       },
    //       {
    //         type: 'input',
    //         name: 'warehouseLocatorCode',
    //         label: '货位编码',
    //         span: 8,
    //         value: ''
    //       }
    //     ]
    //   },
    //   tableConfig: {
    //     rowKey: 'warehouseLocatorId',
    //     rowSelectType: 1,
    //     hasRowSelectCheck: true,
    //     columns: [
    //       { dataIndex: 'warehouseLocatorName', title: '货位名称', key: 'warehouseLocatorName' },
    //       { dataIndex: 'warehouseLocatorCode', title: '货位编码', key: 'warehouseLocatorCode' },
    //       { dataIndex: 'warehouseLocatorId', title: '货位ID', key: 'warehouseLocatorId' }
    //     ],
    //     remoteBefore(res, remoteParams) {
    //       console.log(arguments, '66666666')
    //       remoteParams.params.warehouseId = warehouseId // 添加仓库id查询
    //       remoteParams.params.bldgId = bldgId // 添加建筑物查询
    //       remoteParams.params.warehouseRoomId = warehouseRoomId // 添加库房查询
    //       remoteParams.params.warehouseAreaId = warehouseAreaId // 添加库区查询
    //     }
    //   },
    //   value: '',
    //   remoteUrl: API.locatorPage,
    //   on: {
    //     ok(event, value, rowData, form) {
    //       form.setFieldsValue({
    //         warehouseLocatorId: rowData[0].warehouseLocatorId
    //       })
    //     },
    //     change(event, value, options, form) {
    //       if (!value) {
    //         form.setFieldsValue({ warehouseLocatorId: '' })
    //       }
    //     }
    //   }
    // },
    {
      type: "select",
      name: "checkType",
      label: "盘点类型",
      allowClear: false,
      span: 8,
      required: true,
      defaultValueIndex: 3,
      value: "",
      remoteUrl: {
        url: upcloud_base_common + `/dict/listbytype/?dicttypeCodes=inv_stockcheck_type`,
        method: "post",
      },
      replaceFields: {
        label: "dictName",
        value: "dictCode", // 这个地方后端单独需要code
      },
      autoLoad: true,
      on: {
        change(value, name, options, form) {
          if (name == "动销") {
            form.enableItem(["startDate", "endDate"]);
            let date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            let dates = year + "-" + month + "-" + day;
            form.setFieldsValue({ startDate: dates, endDate: dates });
          } else {
            form.setFieldsValue({ startDate: "", endDate: "" });
            form.disableItem(["startDate", "endDate"]);
          }
        },
      },
    },
    // {
    //   type: "select",
    //   name: "stockStatus",
    //   label: "库存状态",
    //   span: 8,
    //   required: true,
    //   value: "",
    //   remoteUrl: {
    //     url: upcloud_base_common + `/dict/listbytype/?dicttypeCodes=common_stockstatus`,
    //     method: "post",
    //   },
    //   replaceFields: {
    //     label: "dictName",
    //     value: "dictCode",
    //   },
    //   autoLoad: true,
    // },
    // {
    //   type: "row",
    //   label: "日期",
    //   span: 8,
    //   list: [
    //     {
    //       type: "date",
    //       name: "startDate",
    //       placeholder: "请输入开始日期",
    //       // disabled: true,
    //       value: "",
    //       format: "YYYY-MM-DD",
    //     },
    //     {
    //       type: "date",
    //       name: "endDate",
    //       // disabled: true,
    //       placeholder: "请输入结束日期",
    //       format: "YYYY-MM-DD",
    //       value: "",
    //     },
    //   ],
    // },

    // {
    //   type: 'select',
    //   name: 'platStatus1',
    //   label: '区域编号',
    //   value: '01',
    //   options: [
    //     { label: '01', value: '01' },
    //     { label: '02', value: '02' },
    //     { label: '03', value: '03' },
    //     { label: '04', value: '04' }
    //   ]
    // },
    {
      type: "row",
      label: "货位区间",
      list: [
        {
          type: "input",
          name: "locatorCodeStart",
          placeholder: "请输入货位(起)",
          value: "",
          style: "padding-right:5px;",
        },
        {
          type: "input",
          name: "locatorCodeEnd",
          placeholder: "请输入货位(止)",
          value: "",
        },
      ],
    },
    {
      type: "input",
      span: 8,
      name: "itemCode",
      label: "商品编号",
    },
  ];
};
const columns = function (self) {
  return [
    { dataIndex: "warehouseName", title: "仓库名称" },
    { dataIndex: "cargoOwnerName", title: "货主名称", width: 150 },
    { dataIndex: "warehouseAreaName", title: "库区" },
    { dataIndex: "warehouseLocatorName", title: "货位名称" },
    { dataIndex: "containerCode", title: "托盘号" },
    // { dataIndex: 'warehouseLocatorCode', title: '货位编码'' },
    // { dataIndex: 'code1', title: '区域编号'' },
    { dataIndex: "oddCaseQuantity", title: "库存整件数" },
    { dataIndex: "oddPieceQuantity", title: "库存零散数" },
    { dataIndex: "quantity", title: "库存总数量" },
    { dataIndex: "rcvQuantity", title: "入库已分配" },
    { dataIndex: "outQuantity", title: "出库已分配" },
    { dataIndex: "manufacturerLotNum", title: "批号" },
    { dataIndex: "batchNum", title: "批次号" },
    { dataIndex: "itemCode", title: "商品编号" },
    { dataIndex: "itemName", title: "商品名称" },
    { dataIndex: "specification", title: "商品规格" },
    { dataIndex: "uom", title: "包装单位" },
    { dataIndex: "caseConversionRate", title: "包装数量" },
    { dataIndex: "manufacturerName", title: "生产厂家" },
    { dataIndex: "batchProductionDate", title: "生产日期" },
    { dataIndex: "batchExpiredDate", title: "有效期" },
    { dataIndex: "bldgName", title: "建筑物" },
    { dataIndex: "warehouseRoomName", title: "库房" },
    { dataIndex: "warehouseAreaCategory", title: "库别" },
  ];
};

export default {
  components: { searchTable },
  data() {
    return {
      spinning:false,
      items: items(this),
      columns: columns(this),
      title: "盘点计划",
      tableRowKey: "id",
      selectedRowKeys: [],
      selectedRows: [],
      ajaxId: "578638984813613056",
      tableRemoteUrl: {
        url: SERVICE_DATA_API_BASE + "/search/page",
        method: "post",
        headers: {
          "Content-Type": "application/JSON",
        },
      },
      btnOptions: [
        {
          name: "生成计划",
          icon: "",
          action: "savePlan",
        },
        //todo 生成盘点计划
        // {
        //   name: "生成盘点计划",
        //   icon: "",
        //   action: "savePlanAll",
        // },
        // {
        //   name: '打印设置',
        //   icon: 'delete',
        //   action: 'delAll'
        // }
      ],
    };
  },
  created() {
    console.log();
    diffOption(columns(this)).then((res) => {
      this.columns = sorter(res);
    });
    this.getAuthBycargoOwner();
  },
  mounted() {
    warehouseId = this.$store.state.user.warehouse.warehouseId;
    this.$refs.detial.$refs.forms.form.setFieldsValue({
      warehouseId: this.$store.state.user.warehouse.warehouseId,
      warehouseName: this.$store.state.user.warehouse.warehouseName,
    });
  },
  methods: {
    async getAuthBycargoOwner() {
      await getCargoOwner().then((res) => {
        if (res.success) {
          this.$nextTick(() => {
            this.$refs.detial.$refs.forms.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;
        }
      });
    },
    savePlan() {
      console.log(this.$refs.detial.$refs.forms.form.getFieldsValue(), "333333");
      // 生成计划
      if (this.selectedRowKeys.length < 1) return this.$message.warn("请选择盘点商品!");
      if (!this.$refs.detial.$refs.forms.form.getFieldsValue().warehouseId) return this.$message.warn("请选择仓库!");
      // if (!this.$refs.detial.$refs.forms.form.getFieldsValue().cargoOwnerId) return this.$message.warn('请选择货主!')
      if (!this.$refs.detial.$refs.forms.form.getFieldsValue().checkWay) return this.$message.warn("请选择盘点方式!");
      if (!this.$refs.detial.$refs.forms.form.getFieldsValue().checkType) return this.$message.warn("请选择盘点类型!");
      let arrList = [];
      this.selectedRows.map((res, index) => {
        let item = {};
        item.batchExpiredDate = res.batchExpiredDate;
        item.batchId = res.batchId;
        item.batchNum = res.batchNum;
        item.cargoOwnerId = res.cargoOwnerId;
        item.caseQuantityAccount = res.oddCaseQuantity;
        item.conversionRate = res.caseConversionRate;
        item.itemId = res.itemId;
        item.stockStatus = res.status;
        item.lineNum = index;
        item.dcId = res.dcId;
        item.oddQuantityAccount = res.oddPieceQuantity;
        item.pieceQuantityAccount = res.quantity;
        item.productionDate = res.batchProductionDate;
        item.uom = res.uom;
        item.warehouseId = res.warehouseId;
        item.whLocatorId = res.locatorId;
        item.containerCode=res.containerCode
        item.manufacturerLotNum = res.manufacturerLotNum;
        arrList.push(item);
      });
      this.invcheckAdd(arrList);
    },
    savePlanAll() {
      // 全部生成计划
      let that = this;
      this.$confirm({
        title: "",
        content: "是否全部生成计划?",
        onOk() {
          that.$message.warn("接口待开发！");
        },
        onCancel() {},
      });
    },
    invcheckAdd(arrList) {
      console.log(arrList);
      // 生成盘点
      let params = {
        checkMethod: this.$refs.detial.$refs.forms.form.getFieldsValue().checkWay,
        checkType: "0",
        invCheckDVOList: arrList,
      };
      this.spinning = true
      invcheckAdd(params).then((res) => {
        this.spinning = false
        console.log(res);
        if (res.success) {
          this.$message.success("生成盘点计划成功！");
          this.$refs.detial.remoteParams = { ...this.$refs.detial.remoteParams };
        } else {
          this.$exception(res);
        }
      });
    },
    selectChange(selectedRowKeys, selectedRows) {
      // 勾选框
      console.log(selectedRowKeys, selectedRows, "selectedRowKeys, selectedRows");
      this.selectedRows = selectedRows;
      this.selectedRowKeys = selectedRowKeys;
    },
  },
};
</script>

<style></style>
