<template>
  <detail-page
    :tableRemoteUrl="tableRemoteUrl"
    :mainList="mainList"
    :infoList="infoList"
    :ajaxId="ajaxId"
    :remoteDatas="remoteDatas"
    :tableAutoLoad="false"
    @save="save"
    @delAll="delAll"
    @print="print"
    @replay="replay"
    @selectChange="selectChange"
    @colChange="colChange"
    ref="detial"
  >
  </detail-page>
</template>

<script>
import DetailPage from "../components/queryEditTable";
import { toPrintServer } from "@/views/kzyWMS/utils/printServer.js";
import API from "../api/default";
import { remote } from "../api/remote";
import { invcheckUpdate, invcheckExamine, invcheckAddRe, remoteData } from "../api/api";
import { genWarehouseAuthSearchModal, genCargoownerAuthSearchModal } from "../../SearchModal";
import { SERVICE_DATA_API_BASE } from "@/config/serviceSettings";
import { getCargoOwner } from "../../utils/index";
let warehouseId = "";
let bldgId = "";
let warehouseRoomId = "";
let warehouseAreaId = "";
let warehouseLocatorId = "";
const items = [
  ...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 }
  ),
  ...genCargoownerAuthSearchModal(1, true, false, null, null, {
    span: 8,
  }),
  {
    type: "select",
    name: "checkWay",
    label: "盘点方式",
    allowClear: false,
    span: 8,
    value: "0",
    defaultValueIndex: 0,
    ...remote("inv_stockcheck_h_checkgroup2"),
  },
  {
    type: "select",
    name: "condition",
    label: "检索条件",
    span: 8,
    value: "",
    options: [
      { label: "全部明细", value: 0 },
      { label: "实盘数量<>账存数量", value: 1 },
      { label: "实盘数量=账存数量", value: 2 },
      // { label: '已生成损溢明细', value: 3 },
      { label: "未生成损溢明细", value: 4 },
    ],
  },
  {
    type: "search",
    name: "checkHeaderId",
    label: "盘点单",
    destroyOnClose: true,
    targetValueKey: "autoBillNum",
    targetClick: true,
    span: 8,
    value: "",
    toolBar: {
      items: [
        {
          type: "input",
          name: "autoBillNum",
          label: "单据编号",
          span: 8,
          value: "",
        },
      ],
    },
    tableConfig: {
      rowKey: "checkHeaderId",
      rowSelectType: 1,
      hasRowSelectCheck: true,
      columns: [
        { dataIndex: "autoBillNum", title: "单据编号", key: "autoBillNum" },
        { dataIndex: "warehouseName", title: "仓库名称", key: "warehouseName" },
        { dataIndex: "cargoOwnerName", title: "货主", key: "cargoOwnerName" },
        { dataIndex: "gmtCreate", title: "日期", key: "gmtCreate" },
      ],
      remoteBefore: (res, remoteParams) => {
        console.log(remoteParams, "remoteParamsremoteParams");
        remoteParams.data.id = "587643938693844992"; // 添加建筑物查询
        remoteParams.data.params = {
          ...remoteParams.data,
          warehouseId: warehouseId,
        };
        return remoteParams;
      },
    },
    remoteUrl: API.commonUrl,
    on: {
      ok(event, value, rowData, form) {
        console.log(rowData[0].warehouseId, "rowDatarowData");
        form.setFieldsValue({
          warehouseId: rowData[0].warehouseId,
        });
      },
    },
  },
  { type: "input", name: "creator", label: "盘点员Id", hidden: true },
  { type: "input", name: "type", label: "分类", value: "1", hidden: true },
  {
    type: "search",
    name: "locname",
    label: "盘点员",
    destroyOnClose: true,
    targetValueKey: "locname",
    targetClick: true,
    span: 8,
    value: "",
    toolBar: {
      items: [
        {
          type: "input",
          name: "locname",
          label: "盘点员",
          span: 8,
          value: "",
        },
        {
          type: "input",
          name: "jobnumber",
          label: "工号",
          span: 8,
          value: "",
        },
      ],
    },
    tableConfig: {
      rowKey: "id",
      rowSelectType: 1,
      hasRowSelectCheck: true,
      columns: [
        { dataIndex: "locname", title: "盘点员", key: "locname" },
        { dataIndex: "jobnumber", title: "工号", key: "jobnumber" },
        { dataIndex: "id", title: "员工ID", key: "id" },
      ],
      remoteBefore: (res, remoteParams) => {
        console.log(remoteParams, "remoteParamsremoteParams");
        remoteParams.params = {
          ...remoteParams.params,
          warehouseId: warehouseId,
        };
        return remoteParams;
      },
    },
    value: "",
    remoteUrl: API.employeePage,
    on: {
      ok(event, value, rowData, form) {
        console.log(rowData, "rowDatarowData");
        form.setFieldsValue({
          creator: rowData[0].userId,
        });
      },
      change(event, value, rowData, form) {
        if (!value) {
          form.setFieldsValue({
            creator: "",
          });
        }
      },
    },
  },
];
const columns = function (self) {
  return [
    { dataIndex: "autoBillNum", title: "单据编号", key: "autoBillNum", type: "txt" },
    { dataIndex: "itemCode", title: "商品编号", key: "itemCode", type: "txt" },
    { dataIndex: "itemName", title: "商品名称", key: "itemName", type: "txt" },
    {
      dataIndex: "status",
      title: "状态",
      key: "status",
      type: "txt",
      customRender(v) {
        if (v == 0) {
          return "新生成";
        } else if (v == 5) {
          return "盘点已录入";
        } else if (v == 15) {
          return "转损溢";
        } else if (v == 20) {
          return "作废";
        } else if (v == 30) {
          return "复盘";
        } else {
          return v;
        }
      },
    },
    { dataIndex: "checkdate", title: "日期", key: "checkdate", type: "txt" },
    // { dataIndex: 'code4', title: '区域编号', key: 'code4' },
    { dataIndex: "warehouseLocatorCode", title: "货位编码", key: "warehouseLocatorCode", type: "txt" },
    {
      dataIndex: "pieceQuantityAccount",
      title: "账存数量",
      key: "pieceQuantityAccount",
      type: "txt",
      scopedSlots: { customRender: "pieceQuantityAccount" },
    },
    // {
    //   dataIndex: 'caseQuantityFact',
    //   title: '实盘件数',
    //   width: 120,
    //   key: 'caseQuantityFact',
    //   type: 'number',
    //   on: {
    //     change({ event, value, name, index, record }) {
    //       console.log(arguments, 'argumentsargumentsarguments')
    //       record.pieceQuantityFact = record.conversionRate * Number(value) + Number(record.oddQuantityFact)
    //     }
    //   }
    // },
    // {
    //   dataIndex: 'oddQuantityFact',
    //   title: '实盘零散数',
    //   key: 'oddQuantityFact',
    //   width: 120,
    //   type: 'number',
    //   on: {
    //     change({ event, value, name, index, record }) {
    //       console.log(arguments, 'argumentsargumentsarguments')
    //       record.pieceQuantityFact = record.conversionRate * Number(record.caseQuantityFact) + Number(value)
    //     }
    //   }
    // },
    { dataIndex: "caseQuantityFact", title: "实盘件数", key: "caseQuantityFact", type: "txt" },
    { dataIndex: "oddQuantityFact", title: "实盘零散数", key: "oddQuantityFact", type: "txt" },
    { dataIndex: "pieceQuantityFact", title: "实盘数量", key: "pieceQuantityFact", type: "txt" },
    { dataIndex: "quantityDiff", title: "差异数量", key: "quantityDiff", type: "txt" },
    { dataIndex: "manufacturerLotNum", title: "批号", key: "manufacturerLotNum", type: "txt" },
    { dataIndex: "batchProductionDateShow", title: "生产日期", key: "batchProductionDateShow", type: "txt" },
    { dataIndex: "batchExpiredDateShow", title: "有效期", key: "batchExpiredDateShow", type: "txt" },
    { dataIndex: "specification", title: "商品规格", key: "specification", type: "txt" },
    { dataIndex: "conversionRate", title: "包装数量", key: "conversionRate", type: "txt" },
    { dataIndex: "uom", title: "包装单位", key: "uom", type: "txt" },
    { dataIndex: "manufacturerName", title: "生产厂家", key: "manufacturerName", type: "txt" },
    // { dataIndex: 'code18', title: '监管类型', key: 'code18' },
    // { dataIndex: 'code19', title: '库房编号', key: 'code19' }
  ];
};

export default {
  components: { DetailPage },
  props: {
    detailItem: {
      type: Object,
      default: null,
    },
    isView: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {
      mainList: {
        checkedKey: "main",
        list: [
          {
            key: "main",
            tab: "主要信息",
            btns: [
              // {
              //   name: '打印',
              //   icon: '',
              //   action: 'print',
              // },
              {
                name: "查询",
                icon: "",
                action: "hanlderSubmit",
              },
              {
                name: "重置",
                icon: "",
                action: "reset",
              },
              {
                name: "复盘",
                icon: "",
                action: "replay",
              },
              {
                name: "作废",
                icon: "",
                action: "delAll",
              },
              {
                name: "转损溢",
                icon: "",
                action: "save",
              },
            ],
            items: items,
          },
        ],
      },
      printType: "",
      infoList: {
        rowSelectType: 2,
        rowKey: "checkLineId",
        title: "附属信息",
        btns: [],
        columns: columns(this),
      },
      remoteDatas: [],
      ajaxId: "580111717808345088",
      tableRemoteUrl: {
        url: SERVICE_DATA_API_BASE + "/search/page",
        method: "post",
        headers: {
          "Content-Type": "application/JSON",
        },
      },
      selectedRowKeys: [],
      selectedRows: [],
    };
  },

  created() {
    this.getremoteData();
    this.getAuthBycargoOwner();
  },
  mounted() {
    warehouseId = this.$store.state.user.warehouse.warehouseId;
    this.$refs.detial.$refs["main"][0].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["main"][0].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;
        }
      });
    },
    getremoteData() {
      // 字典
      let params = {
        type: "inv_stockcheck_h_checkgroup2",
      };
      remoteData(params).then((res) => {
        if (res.success) {
          console.log();
          this.remoteDatas = res.data;
        } else {
          this.$exception(res);
        }
      });
    },
    save() {
      console.log(this.selectedRows);
      if (this.selectedRows.length > 0) {
        let params = {
          type: "15", // 审核类型
          checkLineIds: this.selectedRowKeys.join(","),
        };
        this.invcheckUp(params, "转损溢");
      } else {
        this.$message.warn("请选择单据！");
      }
    },
    replay() {
      // 复盘
      if (this.selectedRows.length > 0) {
        let params = {
          checkLineIds: this.selectedRowKeys.join(","),
        };
        this.replayAjax(params);
      } else {
        this.$message.warn("请选择单据！");
      }
    },
    delAll() {
      if (this.selectedRows.length > 0) {
        const list = this.selectedRows.map(item => item.warehouseRoomCode)
        if(list.includes('AGVL')) return this.$message.error('有库区为AGVL的数据,无法作废!')
        let params = {
          type: "20", // 审核类型
          checkLineIds: this.selectedRowKeys.join(","),
        };
        this.invcheckUp(params, "作废");
      } else {
        this.$message.warn("请选择单据！");
      }
    },
    print() {
      console.log(this.$refs.detial.$refs["main"][0].form.getFieldsValue());
      let checkWay = this.$refs.detial.$refs["main"][0].form.getFieldsValue().checkWay;
      this.printType = checkWay == "0" ? "PD_MP" : "PD_AP";
      const checkHeaderId = this.$refs.detial.$refs["main"][0].form.getFieldsValue().checkHeaderId;
      const warehouseName = this.$refs.detial.$refs["main"][0].form.getFieldsValue().warehouseName;
      const warehouseId = this.$refs.detial.$refs["main"][0].form.getFieldsValue().warehouseId;
      const cargoOwnerId = this.$refs.detial.$refs["main"][0].form.getFieldsValue().cargoOwnerId;
      const checkdate = this.$refs.detial.$refs["main"][0].form.getFieldsValue().checkdate;
      if (this.selectedRows.length < 1) {
        this.$message.warn("请选择单据！");
        return;
      }
      if (!checkWay) {
        this.$message.warn("请选择盘点方式");
        return;
      }
      if (!checkHeaderId) {
        this.$message.warn("请选择盘点单号");
        return;
      }
      if (!warehouseId) {
        this.$message.warn("请选择仓库");
        return;
      }
      if (!cargoOwnerId) {
        this.$message.warn("请选择货主");
        return;
      }
      const params = [
        {
          head: {
            enterpriseName: this.$store.getters.userInfo.enterpriseName,
            warehouseName: warehouseName,
            checkHeaderId: checkHeaderId,
            checkdate: this.selectedRows[0].checkdate,
            checkUser: this.$store.getters.userInfo.employeeName,
          },
          table: this.selectedRows,
        },
      ];
      toPrintServer(params, warehouseId, this.printType).then((res) => {
        if (!res.success) {
          this.$exception(res);
          return;
        }
        this.$message.success(res.message);
      });
    },
    invcheckUp(params, type) {
      invcheckExamine(params).then((res) => {
        console.log(res);
        if (res.success) {
          this.$message.success(`${type}成功`);
          this.$refs.detial.$refs.table.reload();
        } else {
          this.$exception(res);
        }
      });
    },
    replayAjax(params) {
      // 复盘
      invcheckAddRe(params).then((res) => {
        console.log(res);
        if (res.success) {
          this.$message.success("复盘成功");
          this.$refs.detial.$refs.table.reload();
        } else {
          this.$exception(res);
        }
      });
    },
    selectChange(selectedRowKeys, selectedRows) {
      console.log(selectedRowKeys, selectedRows);
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    colChange(name, value, index, label, record, modalRowData, config, vNode, options, moment, event) {
      console.log(record, "recordrecordrecord");
    },
  },
};
</script>

<style></style>
