<!-- 主动补货任务查询 -->
<template>
  <p-spin :spinning="spinning">
    <p-card title="主动补货">
      <template slot="extra">
        <p-button type="primary" icon="search" @click="extract" style="margin: 0 15px">查询</p-button>
        <p-button type="primary" icon="delete" @click="delShow" style="margin-right: 15px">删除</p-button>
        <p-button type="primary" icon="save" @click="hanlderSubmit">保存</p-button>
        <!-- <p-button type="primary" icon="save" @click="">生成盘点计划</p-button> -->
      </template>
      <div class="plg-inner-form-mb">
        <p-grid-form ref="search" :items="items" @submit="hanlderSubmit" />
      </div>
      <p-tabs v-model="activeKey" @change="changTabs">
        <p-tab-pane key="1" tab="主动补货A品">
          <p-table-edit-pro
            ref="tableAccord"
            dragle
            autoWidth
            :scroll="{ x: true }"
            hasRowSelectCheck
            editor-row-table
            :columns="columns"
            :data-source.sync="data"
            rowKey="id"
            :selectedRowKeys.sync="selectedRowKeys"
            :row-select-type="2"
            @colChange="colChange"
            @change="changePagination"
            @checkRow="checkRow"
            :pagination="pagination"
            :loading="loading"
            bordered
          >
            <template v-slot:pieceNum>
              <span style="color: red">*实补件数</span>
            </template>
            <template slot="sjHLimitPer" slot-scope="text, record">
              <span>{{ record.sjHLimitPer }}%</span>
            </template>
          </p-table-edit-pro>
        </p-tab-pane>
        <p-tab-pane key="2" tab="主动补货BC品">
          <div class="auto">
            <p-switch style="margin-right: 10px" checked-children="开" un-checked-children="关" :checked="regValue" :replaceFields="{ true: '1', false: '0' }" @change="changeSwitch" />
            <span style="margin-right: 10px"> 自动波次</span>
          </div>
          <p-table-edit-pro
            ref="tableBC"
            dragle
            autoWidth
            :autoLoad="false"
            :scroll="{ x: true }"
            hasRowSelectCheck
            editor-row-table
            :columns="columns2"
            :data-source.sync="data2"
            rowKey="id"
            :selectedRowKeys.sync="selectedRowKeys2"
            :row-select-type="2"
            @colChange="colChange2"
            @change="changePagination2"
            @checkRow="checkRow2"
            :pagination="pagination2"
            :loading="loading"
            bordered
          >
            <template v-slot:pieceNum>
              <span style="color: red">*实补件数</span>
            </template>
            <template slot="sjHLimitPer" slot-scope="text, record">
              <span>{{ record.sjHLimitPer }}%</span>
            </template>
          </p-table-edit-pro>
        </p-tab-pane>
      </p-tabs>
    </p-card>
  </p-spin>
</template>

<script>
// 设置默认仓库
import { setwarehouse } from "@/views/kzyWMS/SearchModal/mixins_warehouse.js";
import { items, columns, columns2 } from "./config/accord.js";
import { search_page, initiative_save, urgent_save, updateByCode, getSwatichValue } from "../api/api.js";

import { sorter } from "../../utils/sort";

export default {
  mixins: [setwarehouse],
  data() {
    return {
      regValue: "1",
      activeKey: "1",
      items,
      columns: null,
      data: [],
      selectId: [],
      selectData: [],
      selectedRowKeys: [],
      columns2: null,
      data2: [],
      selectId2: [],
      selectData2: [],
      selectedRowKeys2: [],
      loading: false,
      spinning: false,
      pagination: {
        total: 0,
        pageSize: 10, //每页中显示10条数据
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ["10", "15", "20"], //每页中显示的数据
        showTotal: (total) => `共有 ${total} 条数据`, //分页中显示总的数据
      },
      pagination2: {
        total: 0,
        pageSize: 10, //每页中显示10条数据
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ["10", "15", "20"], //每页中显示的数据
        showTotal: (total) => `共有 ${total} 条数据`, //分页中显示总的数据
      },
    };
  },

  created() {
    this.columns = sorter(columns);
    this.columns2 = sorter(columns2);
  },
  methods: {
    async getSwatichValue(warehouseId) {
      //   console.log(warehouseId, "warehouseId===");
      if (!warehouseId) return;
      try {
        let res = await getSwatichValue({ warehouseId, regCode: "is_auto_bc_pre" });
        if (res.success) {
          let { regValue } = res.data;
          this.regValue = regValue == 1 ? true : false;
          console.log(res, "===");
        } else {
          this.$exception(res);
        }
      } catch (error) {
        this.$exception(error);
      }
    },
    async changeSwitch(value) {
      let data = {
        regCode: "is_auto_bc_pre",
        regValue: value,
      };
      try {
        let res = await updateByCode(data);
        if (res.success) {
          this.getSwatichValue(this.$store.getters.warehouse.warehouseId);
          this.data = [];
          this.data2 = [];
          this.extract();
          // this.getConfig();
        } else {
          this.$exception(res);
        }
      } catch (error) {
        this.$exception(error);
      }
      console.log(value);
    },
    changTabs(activeKey) {
      this.data = [];
      this.data2 = [];
      this.extract();
    },
    getData(val) {
      if (this.activeKey === "1") {
        val = {
          pageNum: this.pagination.current,
          pageSize: this.pagination.pageSize,
          num: "querylocator",
          params: { ...val },
        };
      }
      if (this.activeKey === "2") {
        val = {
          pageNum: this.pagination2.current,
          pageSize: this.pagination2.pageSize,
          num: "querylocator_b",
          params: { ...val },
        };
      }
      this.loading = true;
      search_page(val)
        .then((res) => {
          if (res.success) {
            if (res.data) {
              let temp = res.data.list;
              if (this.activeKey === "1") {
                this.data = temp.map((item) => {
                  return {
                    pieceQuantity: 0, //实补数量（混入后台未定义）
                    pieceNum: item.totalReplenishNum, //实补件数（混入后台未定义）
                    ...item,
                  };
                });
                this.pagination.total = Number(res.data.totalCount);
              }
              if (this.activeKey === "2") {
                this.data2 = temp.map((item) => {
                  return {
                    pieceQuantity: 0, //实补数量（混入后台未定义）
                    pieceNum: item.totalReplenishNum, //实补件数（混入后台未定义）
                    ...item,
                  };
                });
                this.pagination2.total = Number(res.data.totalCount);
              }
            }
            this.loading = false;
            if (this.activeKey === "1") {
              this.selectId.length = 0;
              this.selectData.length = 0;
              this.selectedRowKeys.length = 0;
            }
            if (this.activeKey === "2") {
              this.selectId2.length = 0;
              this.selectData2.length = 0;
              this.selectedRowKeys2.length = 0;
            }
          } else {
            this.loading = false;
            this.$exception(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 右上角保存按钮
    // 保存 提交
    hanlderSubmit(event) {
      // event.preventDefault();
      if (this.selectData.length === 0 && this.activeKey === "1") {
        this.$message.warning("请选择数据！");
        return;
      }
      if (this.selectData2.length === 0 && this.activeKey === "2") {
        this.$message.warning("请选择数据！");
        return;
      }
      if (this.selectData.length && this.activeKey === "1") {
        this.$refs.tableAccord.validateFields((err, values) => {
          if (!err) {
            // 较验实补件数（及对应补货数量）不能为0
            /* let temp = this.selectData.some(item=>item.pieceQuantity==0);
						if(temp){
							this.$message.warn('请输入实补件数！')
							return  false;
						} */
            let params = {
              warehouseId: this.$refs.search.form.getFieldsValue().warehouseId,
              details: [...this.selectData],
            };
            this.spinning = true;
            urgent_save(params).then((res) => {
              this.spinning = false;
              if (res.success) {
                this.$message.success("保存成功！");
                this.data = [];
                this.data2 = [];
                this.extract();
              } else {
                this.$exception(res);
              }
            });
          }
        });
      }
      if (this.selectData2.length && this.activeKey === "2") {
        this.$refs.tableBC.validateFields((err, values) => {
          if (!err) {
            let params = {
              warehouseId: this.$refs.search.form.getFieldsValue().warehouseId,
              details: [...this.selectData2],
            };
            this.spinning = true;
            initiative_save(params).then((res) => {
              this.spinning = false;
              if (res.success) {
                this.$message.success("保存成功！");
                this.data2 = [];
                this.extract();
              } else {
                this.$exception(res);
              }
            });
          }
        });
      }
    },
    // 重置
    hanlderRest(event, form) {
      this.$refs.search.form.resetFields();
    },
    changePagination(pagination, filters, sorter) {
      // 分页变化
      this.pagination = pagination;
      this.getData({ ...this.$refs.search.form.getFieldsValue() }); //分页查询所有列表
    },
    changePagination2(pagination, filters, sorter) {
      // 分页变化
      this.pagination2 = pagination;
      this.getData({ ...this.$refs.search.form.getFieldsValue() }); //分页查询所有列表
    },
    checkRow(selectId, selectRows) {
      console.log("selectId,selectRows：", selectId, selectRows);
      this.selectId = [...selectId];
      this.selectData = selectRows.map((item) => {
        return {
          id: item.id,
          cargoOwnerId: item.cargoOwnerId, //货主ID
          itemId: item.itemId, //商品ID
          pieceQuantity: item.pieceNum * item.caseConversionRate, //补货数量
          warehouseAreaCategory: item.warehouseCategoryCode, //库别
          toWhLocatorId: item.sjLocatorId,
          whLocatorId: item.locatorId,
          pieceQuantity: item.avlQuantity,
          batchId: item.batchId,
          containerCode: item.containerCode,
        };
      });
      console.log("准备保存数组：", this.selectData);
    },
    checkRow2(selectId, selectRows) {
      this.selectId2 = [...selectId];
      this.selectData2 = selectRows.map((item) => {
        return {
          id: item.id,
          cargoOwnerId: item.cargoOwnerId, //货主ID
          itemId: item.itemId, //商品ID
          pieceQuantity: item.pieceNum * item.caseConversionRate, //补货数量
          warehouseAreaCategory: item.warehouseCategoryCode, //库别
        };
      });
    },
    colChange({ name, value, index, label, record, modalRowData, config, vNode, options, moment, event }) {
      if (this.selectData.length === 0) return;
      this.selectData.forEach((item) => {
        if (item.id == record.id) {
          item.pieceQuantity = value * record.caseConversionRate;
        }
      });
    },
    colChange2({ name, value, index, label, record, modalRowData, config, vNode, options, moment, event }) {
      if (this.selectData2.length === 0) return;
      this.selectData2.forEach((item) => {
        if (item.id == record.id) {
          item.pieceQuantity = value * record.caseConversionRate;
        }
      });
    },
    // 提取
    extract() {
      this.data = [];
      this.data2 = [];
      this.getData({ ...this.$refs.search.form.getFieldsValue() });
    },
    // 仅前台显示删除，后台不做删除
    delShow() {
      if (this.selectData.length === 0 && this.activeKey === "1") {
        this.$message.warning("请选择数据！");
        return;
      }
      if (this.selectData2.length === 0 && this.activeKey === "2") {
        this.$message.warning("请选择数据！");
        return;
      }
      if (this.selectId.length && this.activeKey === "1") {
        this.$refs.tableAccord.removeRow(this.selectId);
        this.selectId = [];
      }
      if (this.selectId2.length && this.activeKey === "2") {
        this.$refs.tableBC.removeRow(this.selectId2);
        this.selectId2 = [];
      }
    },
  }, // methods
  mounted() {
    this.getData({ ...this.$refs.search.form.getFieldsValue() });
  },
};
</script>

<style lang="less" scoped>
.auto {
  display: flex;
  justify-content: flex-end;

  padding-bottom: 16px;
}
</style>
