<template>
  <div class="page-body">
    <p-spin :spinning="spinning">
      <div v-show="isShow == 1" class="main">
        <p-card title="波次下发">
          <template v-if="toggleFormTag">
            <p-grid-form class="mb-10" ref="formTarget" :items="gridItems" :span="8" :labelCol="{ span: 8 }" @submit="handleSubmit" />
          </template>
          <div slot="extra">
            <p-button icon="filter" @click="toggleFormTag = !toggleFormTag">
              {{ toggleFormTag ? "隐藏" : "显示" }}
            </p-button>
            <p-button v-if="tabs == 1" type="primary" class="ml-10" v-action:viewTop @click="waveDetail">波次详情</p-button>
            <!-- <p-button v-if="tabs == 1" type="primary" class="ml-10" @click="trialShow">波次试算</p-button> -->
            <p-button v-if="tabs == 1" type="primary" class="ml-10" @click="issue">波次下发</p-button>

            <!--          <p-button type="primary" class="ml-10" v-action:manualorder v-if="projectsType != 'cube'"-->
            <!--                    @clickSync="manualOrder">手工合单-->
            <!--          </p-button>-->
            <!-- <p-button type="primary" class="ml-10" v-action:trial @click="trialShow">波次试算</p-button> -->
            <!-- <p-button v-if="tabs == 1" type="primary" class="ml-10" @click="trialShow">波次试算</p-button> -->
            <!-- <p-button type="primary" class="ml-10" :disabled="this.selectedRows.length == 1 ? false : true" @click="replenishment" v-action:replenishment>补货 </p-button> -->
            <p-button v-if="tabs == 2" type="primary" class="ml-10" @click="replenish_pre">补货</p-button>
          </div>

          <a-tabs v-model="tabs" @change="callback">
            <a-tab-pane key="1" tab="波次下发">
              <p-table
                ref="logTable"
                class="table-exp-parent"
                :autoLoad="false"
                :columns="tableColumnsConfig"
                :row-selection="rowSelection"
                :scroll="{ x: true }"
                :execute="false"
                rowKey="id"
                :expandRowByClick="false"
                :hasRowCount="false"
                :remoteUrl="params"
                :remoteParams="params.params"
                :expandedRowKeys="expandedRowKeys"
                @expand="expandedRowRender"
              >
                <div slot="action" slot-scope="text">
                  <a v-action:waveView @click.stop="lookat(text)">详情</a>
                  <a class="ml-10" v-action:waveDelete @click.stop="deleteOne(text, 'waveDelete')">删除</a>
                </div>
                <p-table
                  :columns="orderColumnsConfig"
                  slot="expandedRowRender"
                  :row-selection="rowSelection1"
                  rowKey="id"
                  :scroll="{ x: true }"
                  :showHeader="true"
                  :loading="loading1"
                  :hasRowCount="false"
                  :colorTransformRow="false"
                  :hasRowSelectCheck="true"
                  :data-source.sync="dataSource"
                  :expandedRowKeys="goodsColumnsRowKeys"
                  :pagination="false"
                  @expand="expandedItems"
                >
                  <div slot="action" slot-scope="text">
                    <a v-if="text.status == '已经创建'" @click.stop="deleteOne(text, 'orderDelete')" v-action:orderDelete>删除</a>
                  </div>
                  <div slot="expandedRowRender" style="width: 81vw">
                    <p-table
                      :columns="itemsColumnsConfig"
                      :rowSelectType="false"
                      :showHeader="true"
                      :loading="loading2"
                      :hasRowCount="false"
                      :colorTransformRow="false"
                      :hasRowSelectCheck="true"
                      :data-source.sync="innerData"
                      :pagination="false"
                    >
                      <div slot="action" slot-scope="text">
                        <a v-if="waveStatus == '已创建'" @click.stop="orderModify(text)" v-action:orderModify>库位修改</a>
                        <a class="ml-10" v-action:itemsView @click.stop="itemDet(text)">详情</a>
                      </div>
                    </p-table>
                  </div>
                </p-table>
              </p-table>
            </a-tab-pane>
            <a-tab-pane key="2" tab="预补货" force-render>
              <p-table
                dragle
                :columns="replenishColumns"
                :remoteUrl="replenishRemoteUrl"
                :remoteData="replenishRemoteData"
                rowKey="billid"
                ref="logTable1"
                @selectChange="selectChange"
                :dataSource.sync="dataSource1"
                :rowSelectType="2"
                bordered
              >
              </p-table>
            </a-tab-pane>
          </a-tabs>
        </p-card>
      </div>
    </p-spin>
    <!-- 波次详情 -->
    <detailDialog v-if="isShow == 2" :waveId="wID" @clickEven="detailEvent" />
    <!-- 库位修改 -->
    <detailspilt v-if="isShow == 3" ref="tablelog" @clickEvent="clickEvent" :orderModifyData="orderModifyData" :num="itemNum" />

    <a-modal width="1400px" title="" :visible="rpVisible" :confirm-loading="confirmLoading" @ok="handleOkreplenishment" @cancel="handleCancel">
      <accord v-if="rpVisible" @saveFun="saveFun" :waveId="waveId" />
    </a-modal>
    <a-modal title="" :visible="ORVisible" :confirm-loading="confirmLoading" @ok="handleOkOdermerge" @cancel="handleCancel">
      <p style="margin-top: 35px; padding-right: 10px">
        <p-grid-form class="mb-10" ref="formTarget1" :items="gridItems2" :span="20" :label-col="{ span: 9 }" />
      </p>
    </a-modal>
    <itemDetail ref="detailItem" :itemId="itemId" />
    <!--波次试算-->
    <trialModal v-model="trialVisible" :trialData="trialData"></trialModal>
    <!-- <a-modal
      width="1400px"
      title=""
      :visible="HCVisible"
      :confirm-loading="confirmLoading"
      @ok="handleOkHC"
      @cancel="handleCancel"
    >
      <detailspilt  v-if="isShow == 3" ref="tablelog" :orderModifyData="orderModifyData" :num="itemNum"></detailspilt>
    </a-modal> -->
  </div>
</template>
<script>
import { setFormItems, setFormItems2, tableColumnsConfig, orderColumnsConfig, itemsColumnsConfig, replenishColumns } from "./js/config";
import detailspilt from "./modules/detailspilt.vue";
import detailDialog from "./modules/detailDialog.vue";
import accord from "./modules/accord.vue";
import itemDetail from "@/views/kzyWMS/components/itemDetail";
import trialModal from "./modules/trialModal";

import {
  getWaveList,
  postdistributeList,
  deletWave,
  getavlpagelist,
  getWaveItemList,
  postbillDPrePosition,
  cencelWaveList,
  deleteWaveId,
  orderConsolidation,
  getstatusList,
  getallDataAuthByUser,
  getAuthByUser,
  waveTaskTrial,
  replenish_pre,
} from "./api/index";
import { upcloud_base_wh_outbound, oms_std_maindata } from "@/config/serviceSettings";

export default {
  components: { detailDialog, detailspilt, accord, itemDetail, trialModal },
  data() {
    return {
      spinning: false,
      dataSource1: [],
      replenishRemoteUrl: {
        url: upcloud_base_wh_outbound + "/wave/pre-replenish",
        headers: {
          "Content-Type": "application/JSON",
        },
        method: "post",
      },
      replenishRemoteData: {},
      tabs: "1",
      params: {
        url: upcloud_base_wh_outbound + "/wave/",
        params: {},
        timeout: 30000,
        method: "get",
      },
      itemId: "",
      dataSource: [],
      traceLinkId: "",
      detailsId: "",
      loading: false,
      loading1: false,
      loading2: false,
      detailItem: {},
      gridItems: setFormItems(this),
      gridItems2: setFormItems2(this),
      replenishColumns: replenishColumns(this),
      ORVisible: false,

      tableColumnsConfig,
      orderColumnsConfig,
      itemsColumnsConfig,

      isShow: 1,
      selectedRowKeys: [],
      selectedRows: [],
      expandedRowKeys: [],
      goodsColumnsRowKeys: [],
      formData: {},
      actionUrl: oms_std_maindata + "/pubCustomerTransline/import/v1.0",
      exportData: {
        exportParams: {},
        exportUrl: oms_std_maindata + "/pubCustomerTransline/export/v1.0",
      },
      downLoadUrl: oms_std_maindata + "/pubCustomerTransline/downloadTemplate/v1.0",
      toggleFormTag: true,
      fileName: "客户与线路关联.xls",
      HCVisible: false,
      confirmLoading: false,
      innerData: [],
      itemObj: {},
      selectedRowKeys1: [],
      selectedRowstab2: [],
      selectedRows1: [],
      itemNum: 0,
      computedNum: 0,
      orderModifyData: {},
      wavesIds: "",
      rpVisible: false,
      waveStatus: "",
      waveId: "",
      wID: "",
      statusList: [],
      projectsType: "",
      // rowSelection
      trialVisible: false, //波次试算弹框
      trialRow: [],
      trialData: [],
      subStatus: "",
    };
  },
  created() {
    this.getstatusList();
    this.getAuthByUser();
    // this.params.params.cargoOwnerId = 'E23A4BUUPPW'
    // this.params.params.cargoOwnerName = '曲靖市康桥医药有限责任公司'
    this.params.params.warehouseId = this.$store.getters.warehouse.warehouseId;
    this.params.params.warehouseName = this.$store.getters.warehouse.warehouseName;
    this.params.params.status = "CREATED";
  },
  mounted() {
    let warehouseName = this.$store.getters.warehouse.warehouseName;
    let warehouseId = this.$store.getters.warehouse.warehouseId;
    this.$refs.formTarget.form.setFieldsValue({
      warehouseName: warehouseName,
      warehouseId: warehouseId,
      status: "CREATED",
    });
  },
  computed: {
    rowSelection() {
      let _this = this;
      return {
        selectedRowKeys: _this.selectedRowKeys,
        onSelectAll(selected, selectedRows, changeRows) {
          var checked = selected;
          var key = changeRows.map((item) => item.id);
        },
        onSelect(record, selected, selectedRows, nativeEvent) {
          var checked = selected;
          var key = record.id;
          _this.trialRow = selectedRows;
          console.log(selectedRows);
        },
        onChange(selectedRowKeys, selectedRows) {
          _this.selectedRowKeys = selectedRowKeys;
          _this.selectedRows = selectedRows;
        },
      };
    },
    rowSelection1() {
      let _this = this;
      return {
        selectedRowKeys: _this.selectedRowKeys1,
        onSelect(record, selected, selectedRows, nativeEvent) {
          if (!selected) {
            _this.computedNum = _this.computedNum + Number(record.qty);
            record.qty = 0;
          }
        },
        onChange(selectedRowKeys, selectedRows) {
          _this.selectedRowKeys1 = selectedRowKeys;
          _this.selectedRows1 = selectedRows;
        },
      };
    },
  },
  methods: {
    callback(key) {
      console.log(key);
      this.tabs = key;
      console.log(this.tabs, "tabstabs");
    },
    async replenish_pre() {
      if (this.selectedRowstab2.length == 0) {
        this.$message.warning("请选择波次");
        return;
      }
      //   let { enterpriseId, branchId, consignorId, itemId, shouldQty, allowableQty, batchNo, areaCategory } = this.selectedRowstab2[0];
      let data = this.selectedRowstab2.map((i) => {
        let { enterpriseId, branchId, consignorId, itemId, shouldQty, allowableQty, batchNo, areaCategory } = i;
        return {
          enterpriseId,
          warehouseId: branchId,
          cargoOwnerId: consignorId,
          itemId,
          pieceQuantity: shouldQty > allowableQty ? allowableQty : shouldQty,
          manufacturerLotNum: batchNo,
          warehouseAreaCategory: areaCategory,
        };
      });
      //   let data1 = {
      //     enterpriseId,
      //     warehouseId: branchId,
      //     cargoOwnerId: consignorId,
      //     itemId,
      //     pieceQuantity: shouldQty > allowableQty ? allowableQty : shouldQty,
      //     manufacturerLotNum: batchNo,
      //     warehouseAreaCategory: areaCategory,
      //   };
      console.log(data);
      // return;
      this.spinning = true;
      try {
        let res = await replenish_pre(data);
        if (res.success) {
          this.$message.success(res.message);
          this.replenishRemoteData = { ...this.replenishRemoteData };
          this.spinning = false;
        } else {
          this.spinning = false;
          this.$exception(res);
        }
      } catch (error) {
        this.$exception(error);
      }
    },
    selectChange(selectedRowKeys, selectedRows) {
      // 勾选框
      this.selectedRowstab2 = selectedRows;
    },
    getstatusList() {
      getstatusList().then((res) => {
        if (res.success) {
          console.log(res);
          const arr = [];
          for (let i = 0; i < res.data.length; i++) {
            const obj = {
              value: res.data[i].code,
              label: res.data[i].name,
            };
            arr.push(obj);
          }
          this.statusList = arr;
          this.gridItems = setFormItems(this);
        } else {
          this.$exception(res);
        }
      });
    },
    async getAuthByUser() {
      await getAuthByUser().then((res) => {
        if (res.success) {
          this.params.params.cargoOwnerId = res.data.list[0].companyId;
          this.params.params.cargoOwnerName = res.data.list[0].companyName;
          this.$nextTick(() => {
            this.$refs.formTarget.form.setFieldsValue({
              cargoOwnerId: res.data.list[0].companyId,
              cargoOwnerName: res.data.list[0].companyName,
            });
          });
        }
        if (!res.success) {
          this.$exception(res);
          return;
        }
      });
      this.$refs.logTable.reload();
    },
    waveDetail() {
      if (this.selectedRowKeys.length !== 1) return this.$message.error("请选择一条数据");
      this.wID = this.selectedRowKeys[0];
      this.isShow = 2;
    },
    lookat(data) {
      this.wID = data.id;
      this.isShow = 2;
    },
    test() {
      console.log("test");
    },

    debounce(func, delay) {
      console.log("执行");
      let timer = null; // 计时器
      return function (...args) {
        console.log("定时器");
        clearTimeout(timer); // 清除上一次计时器
        timer = setTimeout(() => {
          // 重新定时
          func.apply(this, args);
        }, delay);
      };
    },
    issue() {
      this.debounce(this.test, 2000);
      if (this.selectedRowKeys.length < 1) {
        this.$message.error("请至少选择一条数据！");
        return;
      }
      const params = { wavesIds: this.selectedRowKeys };
      postdistributeList(params).then((res) => {
        this.selectedRowKeys = [];
        this.$refs.logTable.reload();
        if (res.success) {
          this.$message.success(res.message);
        } else {
          this.$exception(res);
        }
      });
    },
    handleSubmit(event, ref) {
      event.preventDefault();
      console.log(this.$refs.formTarget.form);
      if (this.tabs == 2) {
        this.replenishRemoteData = { ...this.replenishRemoteData };
        return;
      }
      this.$refs.formTarget.form.validateFields((error, values) => {
        if (!error) {
          this.params.params = values;
        }
      });
    },
    getgetWaveListApi(id) {
      getWaveList(id).then((res) => {
        this.loading1 = false;
        if (res.success) {
          this.dataSource = res.data.bills;
        } else {
          this.$exception(res);
        }
      });
    },
    expandedRowRender(expanded, record) {
      this.selectedRowKeys1 = [];
      if (expanded) {
        this.loading1 = true;
        this.waveStatus = record.status;
        this.expandedRowKeys = [record.id];
        this.wavesIds = record.id;
        this.getgetWaveListApi(this.wavesIds);
        console.log(this.expandedRowKeys);
      } else {
        this.expandedRowKeys = this.expandedRowKeys.filter((item) => {
          return item !== record.id;
        });
      }
    },
    itemDet(data) {
      console.log(data);
      this.itemId = data.itemId;
      this.$refs.detailItem.open();
    },
    expandedItems(expanded, record) {
      this.itemObj = {};
      console.log(record);
      this.itemObj = {
        warehouseId: record.warehouseId,
        consignorId: record.consignorId,
      };

      if (expanded) {
        this.loading2 = true;
        this.goodsColumnsRowKeys = [record.id];
        console.log(this.goodsColumnsRowKeys);
        getWaveItemList(record.id).then((res) => {
          this.loading2 = false;
          if (res.success) {
            this.subStatus = res.data.type;
            this.innerData = res.data.items;
          } else {
            this.$exception(res);
          }
        });
      } else {
        this.goodsColumnsRowKeys = this.goodsColumnsRowKeys.filter((id) => id !== record.id);
      }
    },
    orderModify(data) {
      console.log(data);
      this.isShow = 3;
      this.HCVisible = true;
      this.itemNum = data.pieceQty;
      this.computedNum = data.pieceQty;
      const params = {
        warehouseId: this.itemObj.warehouseId,
        cargoOwnerId: this.itemObj.consignorId,
        billId: data.billId,
        billDId: data.id,
        itemId: data.itemId,
        manufacturerLotNum: data.manufacturerLotNum,
        status: data.stockStatus ? data.stockStatus : "",
        subStatus: this.subStatus == "7" ? "3" : "",
      };
      this.orderModifyData = params;
    },
    clickEvent(data) {
      if (data == "handleOkreplenishment") {
        let status = this.$refs.tablelog.chekTableData();
        if (!status) {
          this.HCVisible = false;
          console.log(this.selectedRows1);
          const data = this.$refs.tablelog.innerData;
          console.log(this.orderModifyData);
          let params = [];
          data.forEach((item) => {
            if (item.qty > 0) {
              const obj = {
                areaCategory: item.warehouseAreaCategory,
                areaCode: item.warehouseAreaCode,
                areaId: item.warehouseAreaId,
                batchId: item.batchId,
                billDId: this.orderModifyData.billDId,
                billId: this.orderModifyData.billDId,
                conversionRate: item.caseConversionRate,
                itemId: item.itemId,
                locationId: item.locatorId,
                locationType: item.locatorType,
                manufacturerLotNum: item.manufacturerLotNum,
                status: item.status,
                qty: item.qty,
              };
              params.push(obj);
            }
          });
          postbillDPrePosition(params).then((res) => {
            if (res.success) {
              this.$refs.tablelog.queryReplenishment();
              this.$message.success(res.message);
              // this.$refs.logTable.reload()
            } else {
              this.$exception(res);
            }
          });
        }
      } else if (data == "back") {
        this.isShow = 1;
      }
    },
    replenishment() {
      if (this.selectedRows[0].status != "已创建") {
        this.$message.error("请选择未下发的数据");
        return;
      }
      this.waveId = this.selectedRows[0].id;
      this.rpVisible = true;
    },
    handleCancel() {
      this.HCVisible = false;
      this.rpVisible = false;
      this.ORVisible = false;
    },
    handleOkreplenishment() {
      this.rpVisible = false;
    },
    saveFun() {
      this.rpVisible = false;
    },
    handleOkOdermerge() {
      this.$refs.formTarget1.form.validateFields((error, values) => {
        if (!error) {
          let data = this.$refs.formTarget.form.getFieldsValue();
          const params = {
            billIds: this.selectedRowKeys1,
            sameDeptNo: values.sameDeptNo == "0" ? true : false,
            samePaymentDayTye: values.sameDeptNo == "0" ? true : false,
            warehouseId: data.warehouseId,
            waveId: this.wavesIds,
          };
          orderConsolidation(params).then((res) => {
            if (res.success) {
              this.$message.success(res.message);
              this.selectedRowKeys1 = [];
              this.ORVisible = false;
              // this.$refs.logTable.reload()
              this.getgetWaveListApi(this.wavesIds);
              this.$refs.formTarget1.form.resetFields();
            } else {
              this.$exception(res);
            }
          });
        }
      });
    },
    manualOrder() {
      let data = this.$refs.formTarget.form.getFieldsValue();
      if (this.selectedRowKeys1.length < 2) {
        this.$message.error("请至少选择两条订单数据");
        return;
      }
      if (!data.warehouseId) {
        this.$message.error("请选择仓库数据");
        return;
      }
      let orderStatus = this.selectedRows1.every((items) => {
        return items.isMerged == 0;
      });
      console.log(orderStatus);
      if (!orderStatus) {
        this.$message.error("选择数据包含已合单数据,请重新选择");
      }
      this.ORVisible = true;
    },
    deleteOne(data, event) {
      if (event == "waveDelete") {
        console.log(event.status);
        if (data.status == "已创建") {
          const params = data.id;
          deleteWaveId(params).then((res) => {
            if (res.success) {
              this.$message.success(res.message);
              this.$refs.logTable.reload();
            } else {
              this.$exception(res);
            }
          });
        } else {
          this.$message.error("已下发的单据不能删除");
        }
      } else {
        const params = { billId: data.id };
        cencelWaveList(params).then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.getgetWaveListApi(this.wavesIds);
          } else {
            this.$exception(res);
          }
        });
      }
    },
    detailEvent(event, data) {
      if (event == "back") {
        this.isShow = 1;
      }
    },
    // 波次试算
    trialShow() {
      if (this.trialRow.length != 1) {
        this.$message.error("请选择一条波次进行任务试算");
        return;
      }
      let params = {};
      params.wavesIds = [this.trialRow[0].id];
      waveTaskTrial(params).then((res) => {
        this.selectedRowKeys = [];
        if (!res.success) {
          this.$message.error(res.message);
          return;
        }
        this.$message.success(res.message);
        this.trialData = res.data;
        this.trialVisible = true;
        this.$refs.logTable.reload();
      });
    },
  },
};
</script>
<style lang="less">
.ant-table-body {
  overflow: auto;
}

.table-exp-parent {
  tr.ant-table-expanded-row,
  tr.ant-table-expanded-row:hover {
    background: #fff;
  }
}

.table-exp-children {
  .ant-table-thead > tr > th {
    background: #fff;
  }

  .ant-table-content {
    border: 1px solid #e8e8e8;
    background: #fff;
    margin: 10px;
  }
}
</style>
