<template>
  <detailPage
    :tableRemoteUrl="tableRemoteUrl"
    :mainList="mainList"
    :infoList="infoList"
    :ajaxId="ajaxId"
    :remoteDatas="remoteDatas"
    :tableAutoLoad="false"
    :spinning="spinning"
    @save="save"
    @send="send"
    @selectChange="selectChange"
    @colChange="colChange"
    ref="detail"
  />
</template>

<script>
import detailPage from "../components/queryEditTable";
import API from "../api/default";
import { remote } from "../api/remote";
import { invcheckUpdate, remoteData, sendToEis } 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,
    required: true,
    defaultValueIndex: 0,
    value: "",
    ...remote("inv_stockcheck_h_checkgroup2"),
  },
  {
    type: "input",
    name: "billNo",
    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: "warehouseName", title: "仓库名称", key: "warehouseName" },
        { dataIndex: "cargoOwnerName", title: "货主", key: "cargoOwnerName", width: 280 },
        { dataIndex: "autoBillNum", title: "单据编号", key: "autoBillNum" },
        { dataIndex: "gmtCreate", title: "日期", key: "gmtCreate" },
      ],
      remoteBefore: (res, remoteParams) => {
        remoteParams.data.id = "587643938693844992";
        remoteParams.data.params = {
          ...remoteParams.data,
          warehouseId: warehouseId,
        };
        return remoteParams;
      },
    },
    remoteUrl: API.commonUrl,
    on: {
      ok(event, value, rowData, form) {},
    },
  },
];
const columns = function (self) {
  return [
    { dataIndex: "autoBillNum", title: "单据编号", type: "txt" },
    // { dataIndex: 'status', title: '状态' },
    { dataIndex: "checkDate", title: "单据日期", type: "txt" },
    {
      dataIndex: "checkStatus",
      title: "盘点状态",
      type: "txt",
      customRender(text) {
        if (text == 0) return "新生成";
        if (text == 5) return "盘点已录入";
        if (text == 15) return "转损溢";
        if (text == 20) return "作废";
        if (text == 30) return "复盘";
        return text;
      },
    },
    { dataIndex: "checkMethod", title: "盘点方式", scopedSlots: { customRender: "checkWay" }, type: "txt" },
    { dataIndex: "warehouseLocatorCode", title: "货位编码", type: "txt" },
    { dataIndex: "containerCode", title: "托盘号", type: "txt" },
    {
      dataIndex: "pieceQuantityAccount",
      title: "账存数量",
      type: "txt",
      scopedSlots: { customRender: "pieceQuantityAccount" },
    },
    {
      dataIndex: "caseQuantityFact",
      title: "实盘件数",
      width: 120,
      hasRepairDataSource: true,
      type: "number",
      on: {
        change({ event, value, name, index, record }) {
          record.pieceQuantityFact = record.conversionRate * Number(value) + Number(record.oddQuantityFact);
        },
      },
    },
    {
      dataIndex: "oddQuantityFact",
      title: "实盘零散数",
      width: 120,
      type: "number",
      hasRepairDataSource: true,
      on: {
        change({ event, value, name, index, record }) {
          record.pieceQuantityFact = record.conversionRate * Number(record.caseQuantityFact) + Number(value);
        },
      },
    },
    { dataIndex: "pieceQuantityFact", value: "0", type: "txt", title: "实盘数量" },
    { dataIndex: "manufacturerLotNum", title: "批号", type: "txt" },
    { dataIndex: "batchNum", title: "批次", type: "txt", hidden: true },
    { dataIndex: "batchProductionDateShow", title: "生产日期", type: "txt" },
    { dataIndex: "batchExpiredDateShow", title: "有效期", type: "txt" },
    { dataIndex: "itemCode", title: "商品编号", type: "txt" },
    { dataIndex: "itemName", title: "商品名称", type: "txt" },
    { dataIndex: "pieceConversionRate", title: "商品规格", type: "txt" },
    { dataIndex: "conversionRate", title: "包装数量", type: "txt" },
    { dataIndex: "uom", title: "包装单位", type: "txt" },
    { dataIndex: "manufacturerName", title: "生产厂家", type: "txt" },
    { dataIndex: "warehouseAreaCode", title: "库区编号", type: "txt" },
    { dataIndex: "warehouseRoomCode", title: "库房编号", type: "txt" },
  ];
};

export default {
  components: { detailPage },
  props: {
    detailItem: {
      type: Object,
      default: null,
    },
    isView: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      spinning:false,
      mainList: {
        checkedKey: "main",
        list: [
          {
            key: "main",
            tab: "主要信息",
            btns: [
              {
                name: "发送设备指令",
                icon: "",
                action: "send",
              },
              {
                name: "查询",
                icon: "",
                action: "hanlderSubmit",
              },
              {
                name: "重置",
                icon: "",
                action: "reset",
              },
              {
                name: "保存",
                icon: "",
                action: "save",
              },
            ],
            items: items,
          },
        ],
      },
      remoteDatas: [],
      infoList: {
        rowSelectType: 2,
        rowKey: "checkLineId",
        title: "附属信息",
        btns: [],
        columns: columns(this),
      },
      ajaxId: "578650241314721792",
      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.detail.$refs["main"][0].form.setFieldsValue({
      warehouseId: this.$store.state.user.warehouse.warehouseId,
      warehouseName: this.$store.state.user.warehouse.warehouseName,
    });
  },
  methods: {
    // queryRefFromName(name) {
    //   return this.$refs.detail.$refs[name][0]
    // },
    async getAuthBycargoOwner() {
      await getCargoOwner().then((res) => {
        if (res.success) {
          this.$nextTick(() => {
            this.$refs.detail.$refs["main"][0].form.setFieldsValue({
              cargoOwnerId: res.data.list[0].companyId,
              cargoOwnerName: res.data.list[0].companyName,
              cargoOwnerCode: res.data.list[0].companyCode,
            });
          });
        } else {
          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() {
      if (this.selectedRows.length > 0) {
        let list = [];
        this.selectedRows.map((res) => {
          let item = {
            caseQuantityFact: res.caseQuantityFact,
            checkLineId: res.checkLineId,
            conversionRate: res.conversionRate,
            oddQuantityFact: res.oddQuantityFact,
            pieceQuantityAccount: res.pieceQuantityAccount,
            pieceQuantityFact: res.pieceQuantityFact ? res.pieceQuantityFact : 0,
            // batchExpiredDate: res.batchExpiredDate
          };
          list.push(item);
        });
        console.log(list, "list");
        let params = list;
        this.invcheckUp(params);
      } else {
        this.$message.warn("请选择单据！");
      }
    },
    send() {
      console.log("发送设备指令");
      const selectedRowKeys = this.selectedRowKeys;
      const selectedRows = this.selectedRows;
      if (selectedRowKeys.length === 0) return this.$message.error("请勾选需要发送设备指令的养护记录信息");
      //判断是否为立体库
      let LTKType = selectedRows.find(
        (i) => i.warehouseRoomCode == "AGVZ" || i.warehouseRoomCode == "AGVL" || i.warehouseRoomCode == "MJK"
      );
      let warehouseRoomCodeList = [...new Set(selectedRows.map((i) => i.warehouseRoomCode))];
      if (LTKType && warehouseRoomCodeList.length != 1) {
        this.$message.error("不同库区不能同时发送设备指令!");
        return;
      }
      this.spinning = true
      sendToEis(selectedRows.map((i) => i.checkLineId)).then((res) => {
        this.spinning = false
        if (res.success) {
          this.$refs.detail.remoteParams = { ...this.$refs.detail.remoteParams };
          this.$message.success(res.message);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    invcheckUp(params) {
      invcheckUpdate(params).then((res) => {
        if (res.success) {
          // this.$refs.detail.$refs.table.reload()
          this.$refs.detail.remoteParams = { ...this.$refs.detail.remoteParams };
        } 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");
      this.selectedRows.map((res) => {
        // 处理勾选后修改数据
        if (res.checkLineId == record.checkLineId) {
          res = record;
        }
      });
    },
  },
};
</script>

<style></style>
