import API from "../../api/default";
import {
  genWarehouseAuthSearchModal,
  genCargoownerAuthSearchModal,
  genItemSearchModal,
  genContainerSearchModal,
} from "@/views/kzyWMS/SearchModal";
import { upcloud_base_wh, upcloud_base_common } from "@/config/serviceSettings";

// 主表单
export const formItems = (self) => {
  const grid = {
    span: 8,
  };
  return [
    ...genWarehouseAuthSearchModal(
      1,
      true,
      false,
      null,
      (modalRowData, form) => {
        console.log(modalRowData, form, "modalRowData,formmodalRowData,form");
        if (modalRowData) {
          self.dcId = modalRowData[0].dcId;
          self.remoteParams.warehouseId = modalRowData[0].warehouseId
            ? modalRowData[0].warehouseId
            : modalRowData[0].companyId;
        } else {
          self.dcId = "";
          self.remoteParams.warehouseId = "";
        }
      },
      grid
    ),
    ...genCargoownerAuthSearchModal(1, true, false, null, null, grid),
    {
      type: "input",
      name: "warehouseName2",
      label: "手动单号",
    },
    {
      type: "select",
      name: "moveOutBldg",
      label: "移出建筑",
      required: true,
      defaultValueIndex: 0,
      destroyOptions: true,
      value: "",
      // autoLoad: true,
      remoteUrl: API.wmsWhBldgPage,
      replaceFields: {
        label: "bldgName",
        value: "bldgId",
      },
      // remoteParams: self.remoteParams,
      remoteBefore(res, remoteParams) {
        let vals = self.$refs.formTarget.form.getFieldsValue();
        if (remoteParams.params) {
          remoteParams.params.warehouseId = vals.warehouseId;
        } else {
          remoteParams.params = { warehouseId: vals.warehouseId };
        }
        return remoteParams;
      },
      on: {
        ok(event, value, rowData, form) {
          console.log(rowData, "rowDatarowData");
        },
      },
    },
    {
      type: "input",
      name: "departmentId",
      label: "部门ID",
      hidden: true,
      disabled: true,
    },
    {
      type: "input",
      name: "departmentName",
      label: "部门",
      disabled: true,
    },
    {
      type: "input",
      name: "warehouseName1",
      label: "自动单号",
      disabled: true,
    },
    {
      type: "select",
      name: "moveInBldg",
      label: "移入建筑",
      required: true,
      value: "",
      destroyOptions: true,
      defaultValueIndex: 0,
      remoteUrl: API.wmsWhBldgPage,
      replaceFields: {
        label: "bldgName",
        value: "bldgId",
      },
      remoteBefore(res, remoteParams) {
        let vals = self.$refs.formTarget.form.getFieldsValue();
        if (remoteParams.params) {
          remoteParams.params.warehouseId = vals.warehouseId;
        } else {
          remoteParams.params = { warehouseId: vals.warehouseId };
        }
        return remoteParams;
      },
    },
    { type: "input", name: "warehouseWorkerId", label: "操作员Id", hidden: true },
    { type: "input", name: "warehouseWorkerName", label: "操作员", disabled: true },
    {
      type: "date",
      name: "today",
      label: "单据日期",
      disabled: true,
      placeholder: "请输入开始日期",
      value: "",
      format: "YYYY-MM-DD",
    },
    {
      type: "input",
      name: "enterpriseName",
      label: "企业",
      disabled: true,
    },
    {
      type: "input",
      name: "warehouseLevel",
      disabled: true,
      label: "移货位类型",
      value: "移库",
    },
    {
      type: "select",
      name: "platStatus",
      label: "来源类型",
      disabled: true,
      value: "WMS",
      options: [
        { label: "WMS", value: "WMS" },
        { label: "GSP", value: "GSP" },
        { label: "ERP", value: "ERP" },
        { label: "SC", value: "SC" },
      ],
    },
    {
      type: "input",
      name: "comments",
      label: "备注",
    },
    {
      type: "p-checkbox",
      name: "autoPrint",
      label: "是否打印移库单",
    },
  ];
};
// 表格
export const columns = (self) => {
  return [
    {
      dataIndex: "itemCode",
      title: "商品编码",
      type: "search",
      targetValueKey: "itemCode",
      targetClick: true,
      width: 150,
      modalWidth: "70%",
      destroyOnClose: true,
      required: true,
      toolBar: {
        items: [
          { type: "input", name: "itemCode", label: "商品编码", span: 8, value: "" },
          { type: "input", name: "itemAssistantCode", label: "助记码", span: 8, value: "" },
        ],
      },
      tableConfig: {
        rowKey: "itemId",
        rowSelectType: 2,
        remoteUrl: (res) => {
          return {
            ...API.batchNum,
          };
        },
        remoteBefore: (res, remoteParams) => {
          const values = self.$refs.formTarget.form.getFieldsValue();
          remoteParams.params = {
            ...remoteParams.params,
            ...values,
          };
          return remoteParams;
        },
        columns: [
          { hidden: true, dataIndex: "itemId", title: "商品id" },
          { dataIndex: "itemCode", title: "商品编码" },
          { dataIndex: "itemAssistantCode", title: "助记码" },
          { dataIndex: "itemName", title: "商品名称" },
          { dataIndex: "manufacturerName", title: "生产厂家" },
        ],
      },
      on: {
        ok(event, value, rowData, name, index, tableRowData, event2) {
          // console.log(event, value, rowData, name, index, tableRowData, event2, "event, value, rowData, name, index, tableRowData, event2")
          //   const dataSource = self.dataSource
          //   const tarRowData = rowData.map(item => {
          //     const {itemId, itemCode, itemName, pieceBarcode, pieceUom, caseConversionRate, pieceConversionRate, manufacturerName} = item
          //     return {
          //       itemId, itemCode, itemName, pieceBarcode, pieceUom, uom: pieceUom, caseConversionRate, conversionRate: pieceConversionRate, manufacturerName
          //     }
          //   })
          //   self.selectedRowKeys = []
          //   dataSource.splice(index, 1, ...tarRowData)

          // 1、增加批量新增功能：点击【新增】按钮后，选择【商品编码】弹窗，允许勾选多个商品，点击【确认】按钮时，若勾选多笔商品记录则在PC-仓库移库开票-移库明细中新增多笔记录。
          // 需有数据后验证

          // let rowData = event.modalRowData
          if (rowData.length) {
            // console.log(event, '222')
            // console.log(event2.record, "event2.record")
            // console.log(rowData, "rowData")
            // console.log(self.dataSource, "dataSource")
            // debugger
            let itemArr = self.dataSource.map((item) => item.itemId);

            let arr = rowData.filter((item) => !itemArr.includes(item.itemId) && item.itemId !== event2.record.itemId);
            if (!!event2.record.itemId && arr.length === 0) {
              self.$message.warn("请选择不重复的库存信息");
              return;
            }

            arr.forEach((item) => {
              item.uom = item.pieceUom;
              item.conversionRate = item.pieceConversionRate;
            });
            self.selectedRowKeys = [];
            self.dataSource.splice(index, 1, ...arr);
          }
        },
        change(eventData) {
          const { index, modalRowData, name, record, value } = eventData;
          if (!value) {
            record.itemId = "";
            record.itemName = "";
            record.pieceBarcode = "";
            record.pieceUom = "";
            record.uom = "";
            record.caseConversionRate = "";
            record.conversionRate = "";
            record.manufacturerName = "";
            record.caseConversionRate = "";
          }
        },
      },
    },
    { dataIndex: "itemId", type: "txt", title: "商品Id", hidden: true },
    { dataIndex: "batchId", type: "txt", title: "批次Id", hidden: true },
    { dataIndex: "batchNum", type: "txt", title: "批次号", hidden: true },
    { dataIndex: "itemName", type: "txt", title: "商品名称", ellipsis: true, width: 200 },
    { dataIndex: "uom", type: "txt", title: "包装单位", width: 80 },
    { dataIndex: "caseConversionRate", type: "txt", title: "包装数量", width: 80 },
    { dataIndex: "conversionRate", type: "txt", title: "包装数", hidden: true, width: 150 },
    { dataIndex: "outLocatorId", type: "txt", title: "移出货位ID", hidden: true, width: 100 },
    { dataIndex: "outStockStatus", type: "txt", title: "下架库存状态", hidden: true, width: 100 },
    {
      dataIndex: "locatorCode",
      width: 150,
      title: "移出货位编码",
      type: "search",
      remoteUrl: API.getstock,
      targetValueKey: "locatorCode",
      destroyOnClose: true,
      modalWidth: "70%",
      autoLoad: false,
      targetClick: true,
      required: true,
      //   modalOpenChange: () => {
      //     const index = self.clickRowRecord - 1
      //     console.log(index, "index--2")
      //     const {itemId} = self.dataSource[index] || {}
      //     console.log(itemId, "itemId")
      //     if (itemId) {
      //       return true
      //     } else {
      //       self.$message.warn('请选择商品编码')
      //       return false
      //     }
      //   },
      customColumnProps({ name, value, record, index, props }) {
        props.modalOpenChange = () => {
          // const index = self.clickRowRecord - 1
          let { itemId } = record || {};
          if (itemId) {
            return true;
          } else {
            self.$message.warn("请选择商品编码");
            return false;
          }
        };
        props.remoteBefore = (res, remoteParams) => {
          // const index = self.clickRowRecord - 1
          const form = self.$refs.formTarget.form.getFieldsValue();
          let { itemId, batchId } = record || {};
          //   2、增加弹窗过滤条件：选择【移出货位编码】弹窗时，增加过滤条件：可用量大于0的过滤条件。
          remoteParams.params = {
            ...remoteParams.params,
            ...form,
            itemId,
            batchId,
          };
          // return remoteParams
        };
      },
      tableConfig: {
        columns: [
          { dataIndex: "manufacturerLotNum", title: "批号", width: 250 },
          { dataIndex: "locatorName", title: "货位名称" },
          { dataIndex: "locatorCode", title: "货位编码" },
          { dataIndex: "availableQuantity", title: "可用库存" },
          { dataIndex: "warehouseAreaCategory", title: "库别" },
          { dataIndex: "warehouseAreaName", title: "库区" },
        ],
        // remoteBefore: (res, remoteParams) => {
        //   const index = self.clickRowRecord - 1
        //   console.log(index, "index--3")
        //   const form = self.$refs.formTarget.form.getFieldsValue()
        //   const {itemId, batchId} = self.dataSource[index] || {}
        //   //   2、增加弹窗过滤条件：选择【移出货位编码】弹窗时，增加过滤条件：可用量大于0的过滤条件。
        //   remoteParams.params = {
        //     ...remoteParams.params,
        //     ...form,
        //     itemId, batchId
        //   }
        //   return remoteParams
        // }
      },
      on: {
        ok(event, value, rowData, name, index, tableRowData) {
          console.log(rowData, "rowData");
          tableRowData.outLocatorId = rowData[0].locatorId;
          tableRowData.outStockStatus = rowData[0].status;
          tableRowData.batchNum = rowData[0].batchNum;
          tableRowData.batchId = rowData[0].batchId;
          tableRowData.manufacturerLotNum = rowData[0].manufacturerLotNum;
          tableRowData.batchProductionDate = rowData[0].batchProductionDate;
          tableRowData.batchExpiredDate = rowData[0].batchExpiredDate;
          tableRowData.batchProductionDateShow = rowData[0].batchProductionDateShow;
          tableRowData.batchExpiredDateShow = rowData[0].batchExpiredDateShow;
          tableRowData.availableQuantity = rowData[0].availableQuantity;
          //   tableRowData.outwarehouseAreaCategory = rowData[0].warehouseAreaCategoryName

          //   tableRowData.outwarehouseAreaCategory = rowData[0].outWarehouseAreaCategory
          tableRowData.outwarehouseAreaCategory = rowData[0].warehouseAreaCategory;

          tableRowData.outContainerCode = rowData[0].containerCode;

          tableRowData.caseConversionRate = rowData[0].caseConversionRate;
          tableRowData.conversionRate = rowData[0].caseConversionRate;
        },
        change({ index, modalRowData, name, record, value }) {
          if (!value) {
            record.outLocatorId = "";
            record.outStockStatus = "";
            record.batchNum = "";
            record.batchId = "";
            record.manufacturerLotNum = "";
            record.batchProductionDate = "";
            record.batchExpiredDate = "";
            record.batchProductionDateShow = "";
            record.batchExpiredDateShow = "";
            record.availableQuantity = "";
            record.outwarehouseAreaCategory = "";
            record.outGoodsCaseCode = "";
          }
        },
      },
    },
    { dataIndex: "outwarehouseAreaCategory", type: "txt", title: "移出库别", width: 100 },
    {
      dataIndex: "outGoodsCaseCode",
      type: "edit",
      title: "移出货格号",
      width: 150,
      required: false,
      disabled: true,
      customColumnProps({ name, value, record, index, props }) {
        if (record.outwarehouseAreaCategory == "AGVL") {
          props.disabled = false
          return {
            required: true,
          };
        } else {
          props.disabled = true
        }
      },
    },
    {
      ...genContainerSearchModal(
        2,
        false,
        false,
        function (res, p) {
          const form = self.$refs.formTarget.form.getFieldsValue();
          p.data.warehouseId = form.warehouseId;
          p.data.containerStatus = "10";
          return p;
        },
        null
      ),
      remoteUrl: { url: upcloud_base_wh + "/container/getPageList", method: "post" },
      title: "移出容器",
      dataIndex: "outContainerCode",
      key: "outContainerCode",
      targetValueKey: "containerCode",
      rowKey: "containerId",
      width: 150,
      targetClick: true,
      disabled: true,
    },
    { dataIndex: "manufacturerLotNum", type: "txt", title: "批号", width: 80 },
    { dataIndex: "batchProductionDateShow", type: "txt", title: "显示生产日期", width: 150 },
    { dataIndex: "batchExpiredDateShow", type: "txt", title: "显示有效期至", width: 150 },
    { dataIndex: "moveRuleId", type: "txt", title: "移入库别规则ID", hidden: true, width: 200 },
    {
      dataIndex: "inwarehouseAreaCategoryName",
      width: 150,
      title: "移入库别",
      type: "searchModal",
      remoteUrl: API.ruleMoveList,
      targetClick: true,
      targetValueKey: "destWarehouseCategoryName",
      toolBar: {},
      customColumnProps({ name, value, record, index, props }) {
        props.modalOpenChange = () => {
          // const index = self.clickRowRecord - 1
          let { outwarehouseAreaCategory } = record || {};
          if (!outwarehouseAreaCategory) {
            self.$message.warn("请选择移出货位编码");
            return false;
          } else {
            return true;
          }
        };
        props.remoteBefore = (res, remoteParams) => {
          let values = self.$refs.formTarget.form.getFieldsValue();
          //   let index = self.clickRowRecord - 1
          let { warehouseAreaCategory } = record || {};
          remoteParams.params = {
            ...remoteParams.params,
            srcWarehouseCategory: warehouseAreaCategory,
            warehouseId: values.warehouseId,
          };
          // return remoteParams
        };
      },
      //   modalOpenChange: () => {
      //     const index = self.clickRowRecord - 1
      //     const {outwarehouseAreaCategory} = self.dataSource[index] || {}
      //     if (!outwarehouseAreaCategory) {
      //       self.$message.warn('请选择移出货位编码')
      //       return false
      //     } else {
      //       return true
      //     }
      //   },
      tableConfig: {
        rowKey: "moveRuleId",
        rowSelectType: 1,
        hasRowSelectCheck: true,
        columns: [
          { dataIndex: "srcWarehouseCategoryName", title: "源库别", key: "srcWarehouseCategory" },
          { dataIndex: "destWarehouseCategoryName", title: "目标库别", key: "destWarehouseCategory" },
          { dataIndex: "quantityModeName", title: "包装属性", key: "quantityModeName" },
        ],
        // remoteBefore: (res, remoteParams) => {
        //   const values = self.$refs.formTarget.form.getFieldsValue()
        //   const index = self.clickRowRecord - 1
        //   const {warehouseAreaCategory} = self.dataSource[index] || {}
        //   remoteParams.params = {
        //     ...remoteParams.params,
        //     srcWarehouseCategory: warehouseAreaCategory,
        //     warehouseId: values.warehouseId
        //   }
        //   return remoteParams
        // },
        done(data) {
          data.map((res) => {
            if (res.quantityMode == "1") {
              res.quantityModeName = "整件";
            }
            if (res.quantityMode == "2") {
              res.quantityModeName = "零散";
            }
            if (res.quantityMode == "3") {
              res.quantityModeName = "整散";
            }
          });
          return data;
        },
      },
      on: {
        ok(event, value, rowData, name, index, tableRowData) {
          tableRowData.inwarehouseAreaCategoryName = rowData[0].destWarehouseCategoryName;
          tableRowData.inwarehouseAreaCategory = rowData[0].destWarehouseCategory;
          tableRowData.destWarehouseCategory = rowData[0].destWarehouseCategory;
          tableRowData.moveRuleId = rowData[0].moveRuleId;
          tableRowData.inStockStatus = rowData[0].stockStatus;
          tableRowData.quantityMode = rowData[0].quantityMode;
        },
        change({ index, modalRowData, name, record, value }) {
          if (!value) {
            record.inwarehouseAreaCategory = "";
            record.moveRuleId = "";
            record.quantityMode = "";
            record.inStockStatus = "";
          }
        },
      },
      required: true,
    },
    { dataIndex: "inwarehouseAreaCategory", type: "txt", title: "移入库别编码", hidden: true, width: 80 },
    { dataIndex: "destWarehouseCategory", type: "txt", title: "移入库别编码", hidden: true, width: 80 },
    { dataIndex: "quantityMode", type: "txt", title: "包装属性", hidden: true, width: 80 },
    { dataIndex: "inStockStatus", type: "txt", title: "上架库存状态", hidden: true, width: 200 },
    {
      dataIndex: "warehouseLocatorCode",
      width: 150,
      title: "移入货位编码",
      type: "search",
      remoteUrl: API.locatorPage,
      targetClick: true,
      targetValueKey: "warehouseLocatorCode",
      //   modalOpenChange: open => {
      //     const index = self.clickRowRecord - 1
      //     const {inwarehouseAreaCategory} = self.dataSource[index] || {}
      //     if (!inwarehouseAreaCategory) {
      //       self.$message.warn('请选择移入库别')
      //       return false
      //     } else {
      //       return true
      //     }
      //   },

      customColumnProps({ name, value, record, index, props }) {
        props.modalOpenChange = () => {
          // let index = self.clickRowRecord - 1
          let { inwarehouseAreaCategory } = record || {};
          if (!inwarehouseAreaCategory) {
            self.$message.warn("请选择移入库别");
            return false;
          } else {
            return true;
          }
        };
        props.remoteBefore = (res, remoteParams) => {
          let index = self.clickRowRecord - 1;
          let form = self.$refs.formTarget.form.getFieldsValue();
          const { batchId } = self.dataSource[index];
          let { itemId, inwarehouseAreaCategory } = record || {};
          remoteParams.params = {
            ...remoteParams.params,
            warehouseAreaCategory: inwarehouseAreaCategory,
            warehouseId: form.warehouseId,
            cargoOwnerId: form.cargoOwnerId,
            itemId,
            batchId,
            // batchId[index] : rowData[0].batchId;
          };
          //   return remoteParams
        };
      },

      toolBar: {
        items: [
          { type: "input", name: "warehouseLocatorName", label: "货位名称", span: 6, value: "" },
          { type: "input", name: "warehouseLocatorCode", label: "货位编码", span: 6, value: "" },
        ],
      },
      tableConfig: {
        rowKey: "warehouseLocatorId",
        rowSelectType: 1,
        hasRowSelectCheck: true,
        columns: [
          { dataIndex: "warehouseLocatorName", title: "货位名称" },
          { dataIndex: "warehouseLocatorCode", title: "货位编码" },
        ],
        // remoteBefore: (res, remoteParams) => {
        //   let index = self.clickRowRecord - 1
        //   let form = self.$refs.formTarget.form.getFieldsValue()
        //   const {itemId, inwarehouseAreaCategory} = self.dataSource[index] || {}
        //   remoteParams.params = {
        //     ...remoteParams.params,
        //     warehouseAreaCategory: inwarehouseAreaCategory,
        //     warehouseId: form.warehouseId,
        //     cargoOwnerId: form.cargoOwnerId,
        //     itemId
        //   }
        //   return remoteParams
        // }
      },
      on: {
        ok(event, value, rowData, name, index, tableRowData) {
          tableRowData.inLocatorId = rowData[0].warehouseLocatorId;
        },
        change({ index, modalRowData, name, record, value }) {
          if (!value) {
            record.inLocatorId = "";
            record.inStockStatus = "";
          }
        },
      },
      required: true,
    },
    {
      ...genContainerSearchModal(
        2,
        false,
        false,
        function (res, params) {
          let form = self.$refs.formTarget.form.getFieldsValue();
          params.data.warehouseId = form.warehouseId;
          params.data.containerStatus = "10";
          return params;
        },
        null
      ),
      remoteUrl: { url: upcloud_base_wh + "/container/getPageList", method: "post" },
      title: "移入容器",
      dataIndex: "inContainerCode",
      key: "inContainerCode",
      targetValueKey: "containerCode",
      rowKey: "containerId",
      width: 150,
      targetClick: true,
      on: {
        change({ index, modalRowData, name, record, value }) {
          if (value && value == record.outContainerCode) {
            self.$message.warn("移入容器不能与移出容器相同！");
            record.inContainerCode = "";
          }
        },
      },
    },
    { dataIndex: "inLocatorId", title: "移入货位ID", hidden: true, width: 200 },
    { dataIndex: "availableQuantity", type: "txt", title: "可用库存数量", width: 100 },
    { dataIndex: "numData", type: "txt", title: "数量", width: 80 },
    {
      dataIndex: "caseQuantity",
      title: "件数",
      width: 100,
      key: "caseQuantity",
      type: "number",
      on: {
        keydown(event) {
          const index = self.clickRowRecord - 1;
          const { quantityMode } = self.dataSource[index] || {};
          if (quantityMode == "2") {
            event.stopPropagation();
            event.preventDefault();
            event.target.value = 0;
            self.$message.warn("当前行移入库别禁止输入整件数！");
            return false;
          } else {
            return true;
          }
        },
        change({ event, value, name, index, record }) {
          record.numData = record.caseConversionRate * value + Number(record.oddPieceQuantity);
          if (record.availableQuantity < record.numData) {
            self.$message.warn("可用库存数量不足");
            record.caseQuantity = 0;
            self.dataSource = [...self.dataSource];
            return;
          }
        },
      },
    },
    {
      dataIndex: "oddPieceQuantity",
      width: 100,
      title: "零散数",
      type: "number",
      on: {
        keydown(event) {
          const index = self.clickRowRecord - 1;
          const { quantityMode } = self.dataSource[index] || {};
          if (quantityMode == "1") {
            event.stopPropagation();
            event.preventDefault();
            event.target.value = "0";
            self.$message.warn("当前行移入库别禁止输入零散数！");
            return false;
          }
        },
        change({ event, value, name, index, record }) {
          record.numData = record.caseConversionRate * Number(record.caseQuantity) + Number(value);
          if (record.availableQuantity < record.numData) {
            self.$message.warn("可用库存数量不足");
            record.oddPieceQuantity = 0;
            self.dataSource = [...self.dataSource];
            return;
          }
        },
      },
    },
    { dataIndex: "reason", type: "edit", title: "移库原因", value: "库内调整", width: 150 },
    {
      dataIndex: "unqualifiedReason",
      type: "select",
      title: "不合格原因",
      width: 130,
      remoteUrl: {
        url: upcloud_base_common + `/dict/listbytype/?dicttypeCodes=bhgyy`,
        method: "post",
      },
      replaceFields: {
        label: "dictName",
        value: "dictCode",
      },
      autoLoad: true,
    },
    { dataIndex: "manufacturerName", type: "txt", title: "生产厂家", width: 250 },
  ];
};
