<template>
  <div>
    <p-spin :spinning="loadding">
      <!-- <detail-page
      v-show="!detialShow"
      :tableColumns="columns"
      :title="title"
      :tableRemoteUrl="tableRemoteUrl"
      :tableRowKey="tableRowKey"
      :btnOptions="btnOptions"
      :items="items"
      :ajaxId="ajaxId"
      :tableAutoLoad="false"
      @checkOk="checkOk"
      @changeClick="changeClick"
      @selectChange="selectChange"
      ref="detial"
    >
    </detail-page> -->
      <p-card :title="title">
        <span slot="extra">
          <div v-for="(item, index) in btnOptions" :key="index">
            <p-button type="primary" style="margin-right: 10px" :icon="item.icon" @click="checkOk">{{
              item.name
            }}</p-button>
          </div>
        </span>
        <div class="gridClass">
          <p-grid-form
            :span="8"
            ref="forms"
            :labelCol="{ span: 8 }"
            :items="items"
            @submit="hanlderSubmit"
          ></p-grid-form>
        </div>
        <p-table-edit-pro
          ref="table"
          :scroll="{ x: true }"
          :row-key="tableRowKey"
          :bordered="true"
          dragle
          :dataSource.sync="dataSource"
          auto-width
          :autoLoad="false"
          :filterDropdownColum="false"
          :colorTransformRow="false"
          :columns="columns"
          :rowSelectType="2"
          :selectedRowKeys.sync="selectedRowKeys"
          :remoteUrl="tableRemoteUrl"
          :remoteBefore="remoteBefore"
          :remoteData="remoteParams"
          :remoteParams="remoteParams"
          @selectChange="selectChange"
        >
          <span slot="action" slot-scope="text, record">
            <a @click="changeClick(record)" style="margin-right: 10px" href="javascript:;">损溢管理编辑</a>
          </span>
        </p-table-edit-pro>
      </p-card>
    </p-spin>
  </div>
</template>

<script>
import DetailPage from "../components/commonTable";
import { moveCheck, moveCancel, MoveList, WmsLoctype } from "../api/api";
import API from "../api/default";
import { genWarehouseAuthSearchModal, genCargoownerAuthSearchModal } from "@/views/kzyWMS/SearchModal";
import { sorter } from "../../utils/sort";
import { upcloud_base_wh_operate, upcloud_base_wh_control } from "@/config/serviceSettings";
import { getCargoOwner } from "../../utils/index";

const items = function (that) {
  let grid = {
    labelCol: { span: 8 },
    span: 8,
  };
  return [
    ...genWarehouseAuthSearchModal(1, true, false, null, null, grid),
    ...genCargoownerAuthSearchModal(1, true, false, null, null, grid),
    {
      type: "select",
      name: "moveOutBldg",
      label: "移出建筑",
      required: true,
      defaultValueIndex: 0,
      destroyOptions: true,
      value: "",
      autoLoad: true,
      remoteUrl: API.wmsWhBldgPage,
      replaceFields: {
        label: "bldgName",
        value: "bldgId",
      },
      remoteBefore(res, remoteParams) {
        // console.log(arguments, 'warehouseIdwarehouseId')
        that.$nextTick(() => {
          let values = that.$refs.detial.$refs.forms.form.getFieldsValue();
          if (remoteParams.params) {
            remoteParams.params.warehouseId = values.warehouseId;
          } else {
            remoteParams.params = { warehouseId: values.warehouseId };
          }
        });
      },
      on: {
        ok(event, value, rowData, form) {
          console.log(rowData, "rowDatarowData");
        },
      },
    },
    {
      type: "select",
      name: "moveInBldg",
      label: "移入建筑",
      required: true,
      defaultValueIndex: 0,
      destroyOptions: true,
      value: "",
      autoLoad: true,
      remoteUrl: API.wmsWhBldgPage,
      replaceFields: {
        label: "bldgName",
        value: "bldgId",
      },
      remoteBefore(res, remoteParams) {
        // console.log(arguments, 'warehouseIdwarehouseId')
        that.$nextTick(() => {
          let values = that.$refs.detial.$refs.forms.form.getFieldsValue();
          if (remoteParams.params) {
            remoteParams.params.warehouseId = values.warehouseId;
          } else {
            remoteParams.params = { warehouseId: values.warehouseId };
          }
        });
      },
      on: {
        ok(event, value, rowData, form) {
          console.log(rowData, "rowDatarowData");
        },
      },
    },
    {
      type: "input",
      name: "autoBillNum",
      label: "自动单号",
    },
    // {
    //   type: 'input',
    //   name: 'warehouseName2',
    //   label: '手动单号'
    // },
    {
      type: "row",
      label: "单据日期",
      name: "ff",
      list: [
        {
          type: "date",
          name: "start",
          style: { paddingRight: "5px" },
          format: "YYYY-MM-DD",
          placeholder: "请输入开始日期",
          value: "",
        },
        {
          style: { paddingLeft: "5px" },
          type: "date",
          name: "end",
          placeholder: "请输入结束日期",
          format: "YYYY-MM-DD",
          value: "",
        },
      ],
    },
    {
      type: "select",
      name: "moveBillType",
      label: "来源类型",
      value: "",
      defaultValueIndex: 0,
      options: [
        // { label: '全部', value: '' },
        { label: "WMS", value: "WMS" },
        { label: "GSP", value: "GSP" },
        { label: "ERP", value: "ERP" },
        { label: "SC", value: "SC" },
        { label: "CHECK", value: "CHECK" },
      ],
    },
    {
      span: 8,
      type: "buttonGroup",
      style: { textAlign: "right" },
      options: [
        {
          value: "查询",
          icon: "search",
          btnType: "primary",
          style: "margin-right:10px",
          htmlType: "submit",
        },
        {
          value: "重置",
          icon: "redo",
          style: "margin-right:50px",
          on: {
            click: (event, form) => {
              console.log(form);
              form.resetFields();
            },
          },
        },
      ],
    },
  ];
};
const columns = function (that) {
  return [
    { dataIndex: "autoBillNum", title: "自动单号", key: "autoBillNum", width: 150, type: "txt" },
    { dataIndex: "cargoOwnerName", title: "货主", key: "cargoOwnerName", width: 150, type: "txt" },
    { dataIndex: "moveOutBldgName", title: "移出建筑", key: "moveOutBldgName", width: 80, type: "txt" },
    { dataIndex: "moveInBldgName", title: "移入建筑", key: "moveInBldgName", width: 80, type: "txt" },
    { dataIndex: "moveBillType", title: "来源类型", key: "moveBillType", width: 80, type: "txt" },
    { dataIndex: "moveDate", title: "单据日期", key: "moveDate", width: 150, type: "txt" },
    { dataIndex: "itemCode", title: "商品编码", key: "itemCode", width: 150, type: "txt" },
    { dataIndex: "itemName", title: "商品名称", key: "itemName", width: 100, type: "txt" },
    { dataIndex: "outLocatorCode", title: "移出货位编码", key: "outLocatorCode", width: 180, type: "txt" },
    {
      dataIndex: "outWarehouseAreaCategory",
      title: "移出库别",
      key: "outWarehouseAreaCategory",
      width: 100,
      type: "txt",
    },

    //   {
    //     dataIndex: "inLocatorCode",
    //     title: "移入货位编码(未联调)",
    //     key: "inLocatorCode",
    //     width: 180,
    //     scopedSlots: { customRender: "inLocatorCode" },
    //   },
    {
      type: "txt",
      required: true,
      dataIndex: "inLocatorCode",
      title: "移入货位编码",
      align: "center",
      width: 150,
      //   type: "searchModal",
      targetClick: true,
      // disabled: true,
      targetValueKey: "warehouseLocatorCode",
      remoteUrl: { url: upcloud_base_wh_control + "/item-locator/v1/locator-limit-inbound", method: "get" },
      // remoteData: { consignorId: consignorId || that?.consignorId },

      modalOpenChange(open) {
        return open;
      },
      customColumnProps({ name, value, record, index, props }) {
        console.log(record);
        props.remoteBefore = (res, remoteParams) => {
          remoteParams.params = {
            ...remoteParams.params,
            warehouseAreaId: record.inWarehouseAreaId,
            toWhAreaCategory: record.warehouseAreaCategory,
            cargoOwnerId: record.cargoOwnerId,
            itemId: record.itemId,
            warehouseId: record.warehouseId,
            //   itemName: record.itemName,
            //       { key: "toWhAreaCategory", target: "warehouseAreaCategory" },
            //   { key: "cargoOwnerId", target: "cargoOwnerId" },
            //   { key: "itemId", target: "itemId" },
            //   { key: "warehouseId", target: "warehouseId" },
            //   { key: "itemName", target: "itemHealthCategory" },
          };
          // return remoteParams
        };
      },
      rowKey: "id",
      toolBar: {
        items: [
          { type: "input", name: "warehouseLocatorName", label: "货位名称", value: "" },
          { type: "input", name: "warehouseLocatorCode", label: "货位编码", value: "" },
        ],
      },
      on: {
        search: () => {
          // this.remoteParams = {}
        },
        ok(event, value, rowData, form) {
          // console.log(event, value, rowData, form)
        },
        async change(event, value, rowData, form) {},
      },
      relatedQuery: [
        { key: "toWhAreaCategory", target: "warehouseAreaCategory" },
        { key: "cargoOwnerId", target: "cargoOwnerId" },
        { key: "itemId", target: "itemId" },
        { key: "warehouseId", target: "warehouseId" },
        { key: "itemName", target: "itemHealthCategory" },
      ],
      multipleKey: [{ key: "warehouseLocatorId", target: "toWhLocatorId" }],

      tableConfig: {
        rowKey: "warehouseLocatorId",
        columns: [
          { dataIndex: "warehouseLocatorId", title: "ID", hidden: true },
          { dataIndex: "warehouseLocatorName", title: "货位名称" },
          { dataIndex: "warehouseLocatorCode", title: "货位编码" },
          {
            dataIndex: "warehouseLocatorType",
            title: "货位类型",
            // remoteUrl: { url: upcloud_base_common + "/dict/listbytype?dicttypeCodes=wms_loctype", method: "post" },
            // replaceFields: {
            //   value: "dictCode",
            //   label: "dictName",
            // },
            customRender(text) {
              let a = that.WmsLoctypeOptions.find((i) => {
                if (i.dictCode == text) {
                  return true;
                }
              });

              return a.dictName;
            },
          },
        ],
      },
    },
    {
      dataIndex: "inWarehouseAreaCategory",
      title: "移入库别",
      key: "inWarehouseAreaCategory",
      width: 100,
      type: "txt",
    },
    { dataIndex: "pieceQuantity", title: "移动数量", key: "pieceQuantity", width: 100, type: "txt" },
    { dataIndex: "uom", title: "单位", key: "uom", width: 80, type: "txt" },
    { dataIndex: "caseConversionRate", title: "包装数量", key: "caseConversionRate", width: 100, type: "txt" },
    { dataIndex: "manufacturerLotNum", title: "批号", key: "manufacturerLotNum", width: 150, type: "txt" },
    { dataIndex: "reason", title: "移库原因", key: "reason", width: 150, type: "txt" },
    // { dataIndex: 'code14', title: '源容器', key: 'code14', type: 'edit' },
    // { dataIndex: 'code15', title: '源货格', key: 'code15', type: 'edit' },
    // { dataIndex: 'code16', title: '目标容器', key: 'code16', type: 'edit' },
    // { dataIndex: 'code17', title: '目标货格', key: 'code17', type: 'edit' },
    {
      dataIndex: "batchProductionDateShow",
      title: "生产日期",
      key: "batchProductionDateShow",
      width: 100,
      type: "txt",
    },
    { dataIndex: "batchExpiredDateShow", title: "有效期至", key: "batchExpiredDateShow", width: 100, type: "txt" },
    { dataIndex: "shelfLifeDays", title: "保质天数", key: "shelfLifeDays", width: 80, type: "txt" },
    { dataIndex: "warehouseName", title: "仓库名称", key: "warehouseName", width: 150, type: "txt" },
    { dataIndex: "warehouseWorkerId", title: "库工编码", key: "warehouseWorkerId", width: 150, type: "txt" },
    { dataIndex: "warehouseWorkerName", title: "库工名称", key: "warehouseWorkerName", width: 80, type: "txt" },
    { dataIndex: "comments", title: "备注", key: "comments", width: 150, type: "txt" },
  ];
};

export default {
  components: { DetailPage },
  data() {
    return {
      loadding: false,
      WmsLoctypeOptions: [],
      dataSource: [],
      items: items(this),
      columns: columns(this),
      title: "移库上架",
      tableRowKey: "moveLineId",
      remoteParams: {},
      selectedRowKeys: [],
      selectedRows: [],
      detialRecord: {},
      addStatus: false,
      detialShow: false,
      ajaxId: "", // 移库类型 1 移库 2移位
      tableRemoteUrl: {
        url: upcloud_base_wh_operate + "/move/v1/list",
        method: "get",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        params: {
          subBillType: "1",
          statusList: "W20",
        },
      },
      btnOptions: [
        {
          name: "上架",
          icon: "",
          action: "checkOk",
        },
      ],
    };
  },
  created() {
    // this.columns = sorter(columns);
    this.getAuthBycargoOwner();
  },
  mounted() {
    // warehouseId = this.$store.state.user.warehouse.warehouseId
    this.$refs.forms.form.setFieldsValue({
      warehouseId: this.$store.state.user.warehouse.warehouseId,
      warehouseName: this.$store.state.user.warehouse.warehouseName,
      start: this.getDay(-7),
      end: this.getDay(0),
    });
    this.getWmsLoctype();
  },
  methods: {
    async getWmsLoctype() {
      let res = await WmsLoctype();
      console.log(res);
      this.WmsLoctypeOptions = res.data.map((i) => {
        return {
          dictCode: i.dictCode,
          dictName: i.dictName,
        };
      });
      console.log(this.WmsLoctypeOptions);
    },
    clickBtn(item) {
      // 按钮
      this.$emit(item.action, true);
    },
    async hanlderSubmit(event, form) {
      // 查询
      console.log(form);
      event.preventDefault();
      form.validateFields(async (error, values) => {
        console.log(error, values, "valuesvaluesvaluesvaluesvalues");
        // this.queryName = values.name
        // this.queryType = values.type
        // this.getlistCompanyByAuthId()

        if (!error) {
          //   let data = {
          //     ...values,
          //     subBillType: "1",
          //     statusList: "W20",
          //   };
          //   let res = await MoveList(data);
          //   console.log(res);

          this.remoteParams = { ...this.remoteParams, ...values, subBillType: "1", statusList: "W20" };
        }
      });
      //   this.$emit("hanlderSubmit", event, form);
      //   this.remoteParams = { ...this.remoteParams };
    },
    remoteBefore(data, dataParams) {
      console.log(dataParams, "dataParamsdataParamsdataParams");

      dataParams.params = {
        ...dataParams.params,
        ...this.tableRemoteUrl.params,
      };
      return dataParams;
    },
    selectChange(selectedRowKeys, selectedRows) {
      // 勾选框
      console.log(selectedRowKeys, selectedRows);
      this.selectedRowKeys = selectedRowKeys;
      this.$emit("selectChange", selectedRowKeys, selectedRows);
    },
    changeClick(record) {
      this.$emit("changeClick", record);
    },
    async getAuthBycargoOwner() {
      await getCargoOwner().then((res) => {
        if (res.success) {
          this.$nextTick(() => {
            this.$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;
        }
      });
    },
    getDay(day) {
      let today = new Date();
      var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
      today.setTime(targetday_milliseconds); //注意，这行是关键代码
      var tYear = today.getFullYear();
      var tMonth = today.getMonth();
      var tDate = today.getDate();
      tMonth = this.doHandleMonth(tMonth + 1);
      tDate = this.doHandleMonth(tDate);
      return tYear + "-" + tMonth + "-" + tDate;
    },
    doHandleMonth(month) {
      var m = month;
      if (month.toString().length == 1) {
        m = "0" + month;
      }
      return m;
    },
    changeClick(record) {
      // 编辑
      this.detialShow = true;
      this.detialRecord = record;
      console.log(record);
    },
    requestUrl(val) {
      this.detialShow = val;
    },
    cancelBtn(val) {
      this.addStatus = false;
    },
    checkOk() {
      // 审核
      if (this.selectedRowKeys < 1) {
        return this.$message.warn("请选择商品！");
      }
      let params = {
        lineIds: this.selectedRowKeys,
        moveFlag: "1", // 上架
      };
      this.loadding = true;
      moveCheck(params).then((res) => {
        this.loadding = false;
        if (res.success) {
          this.selectedRowKeys = [];
          this.$message.success(res.message);
          this.$refs.forms.form.validateFields(async (error, values) => {
            this.remoteParams = { ...this.remoteParams, ...values, subBillType: "1", statusList: "W20" };
          });
        } else {
          this.loadding = false;
          this.$exception(res);
        }
      });
    },
    successBtn() {
      this.addStatus = false;
      this.$refs.detial.$refs.table.reload();
    },
    selectChange(selectedRowKeys, selectedRows) {
      // 勾选框
      console.log(selectedRowKeys, selectedRows, "selectedRowKeys, selectedRows");
      this.selectedRows = selectedRows;
      this.selectedRowKeys = selectedRowKeys;
    },
  },
};
</script>

<style></style>
