<!-- 紧急补货 -->
<template>
  <div>
    <p-card title="紧急补货">
      <template slot="extra">
        <p-button type="primary" icon="plus" @click="addRow" style="margin-right: 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>
      </template>
      <div class="plg-inner-form-mb">
        <p-grid-form ref="search" :items="items" @submit="hanlderSubmit" />
      </div>
      <p-table-edit-pro
        ref="tableInstancy"
        dragle
        auto-width
        :scroll="{ x: true }"
        hasRepairDataSource
        editor-row-table
        :columns="columns"
        :data-source.sync="data"
        rowKey="{record => record.ids + Math.random()}"
        :row-select-type="2"
        @change="changePagination"
        @checkRow="checkRow"
        :pagination="pagination"
        :loading="loading"
        bordered
      >
      </p-table-edit-pro>
    </p-card>
  </div>
</template>

<script>
// 设置默认仓库
import { setwarehouse } from "@/views/kzyWMS/SearchModal/mixins_warehouse.js";
import { items, columns } from "./config/instancy.js";
import { search_page, initiative_save, urgent_save } from "../api/api.js";
// import store  from '@/store';
import { diffOption } from "@/views/kzyWMS/utils/index.js";
import { sorter } from "../../utils/sort";

export default {
  mixins: [setwarehouse],
  data() {
    return {
      items,
      columns: columns(this),
      data: [
        // {
        // 	cargoOwnerName: "",
        // 	caseConversionRate: "",
        // 	companyName: "",
        // 	destWarehouseAreaName: "",
        // 	id: 1,
        // 	itemName: "",
        // 	locatorName: "",
        // 	pieceQuantity: "",
        // 	warehouseLocatorName: "",
        // }
      ],
      selectId: [],
      selectData: [],
      loading: false,
      pagination: {
        total: 0,
        pageSize: 10, //每页中显示10条数据
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ["10", "15", "20"], //每页中显示的数据
        showTotal: (total) => `共有 ${total} 条数据`, //分页中显示总的数据
      },
    };
  },

  created() {
    diffOption(columns(this)).then((res) => {
      this.columns = sorter(res);
    });
  },
  methods: {
    getData(params) {
      (params = {
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize,
        ...params,
      }),
        (this.loading = true);
      urgent_save(params).then((res) => {
        if (res.success) {
          this.loading = false;
          this.$message.success("保存成功！");
          this.data = [];
          //   this.$refs.tableInstancy.reset()
          //   this.$refs.tableInstancy.createRow(null, { pieceQuantity: '', caseConversionRate: 0, pieceNum: 0 }, false)
        } else {
          this.loading = false;
          this.$exception(res);
        }
      });
    },
    // 保存 提交
    hanlderSubmit(event) {
      event.preventDefault();
      // console.log("getFieldsValue:",form.getFieldsValue());
      // this.getData(form.getFieldsValue())
      if (this.selectData.length) {
        this.$refs.tableInstancy.validateFields((err, values) => {
          console.log("验证通过: ", this.$refs.search.form.getFieldsValue());
          if (!err) {
            // 较验补货件数（及对应补货数量）不能为0
            let temp = this.selectData.some((item) => item.pieceNum == 0);
            if (temp) {
              this.$message.warn("请输入补货件数！");
              return false;
            }
            let details = this.selectData.map((item) => {
              return {
                batchId: item.batchId,
                cargoOwnerId: item.cargoOwnerId,
                itemId: item.itemId,
                toWhLocatorId: item.toWhLocatorId,
                whLocatorId: item.whLocatorId,
                pieceQuantity: item.pieceQuantity,
              };
            });
            this.selectId.length = 0; //清除当前选择id
            this.getData({ details: details, ...this.$refs.search.form.getFieldsValue() });
          }
        });
      } else {
        this.$message.warning("请选择数据！");
      }
    },
    changePagination(pagination, filters, sorter) {
      // 分页变化
      console.log(pagination, filters, sorter, "分页变化分页变化");
      this.pagination = pagination;
      this.getData(); //分页查询所有列表
    },
    checkRow(selectId, selectRows) {
      this.selectId = [...selectId];
      this.selectData = [...selectRows];
      console.log("selectId,selectRows：", selectId, selectRows);
    },
    colChange({ name, value, index, label, record, modalRowData, config, vNode, options, moment, event }) {
      console.log("改变单元格数据：", name, value, index, label, record, modalRowData);
      this.data[index].pieceQuantity = value; //补货数量
      console.log("行修改后：", this.data);
    },
    // 重置
    resetRow() {
      this.$emit("update:dataSource", []);
      this.$refs.tableInstancy.dataSource[0].cargoOwnerId = "";
      this.$refs.tableInstancy.dataSource[0].cargoOwnerName = "";
      console.log("this.$refs.tableInstancy:", this.$refs.tableInstancy.dataSource, this.data);
    },
    // 增加行
    addRow() {
      if (this.data.length != 0) {
        this.$refs.tableInstancy.validateFields((err, values) => {
          if (!err) {
            this.$refs.tableInstancy.createRow(null, { pieceQuantity: "", caseConversionRate: 0, pieceNum: 0 }, false);
          } else {
            this.$message.warning("有必填项！");
          }
        });
      } else {
        this.$refs.tableInstancy.createRow(null, { pieceQuantity: "", caseConversionRate: 0, pieceNum: 0 }, false);
      }
      // this.data.push({pieceQuantity:'',caseConversionRate:''});
      console.log(this.$refs.tableInstancy, this.data);
    },
    // 仅前台显示删除，后台不做删除
    delShow() {
      console.log("this.selectId:", this.selectId);
      if (this.selectId.length) {
        this.$refs.tableInstancy.removeRow(this.selectId);
        this.selectId = [];
      } else {
        this.$message.warning("请选择数据！");
      }
    },
  }, // methods
  mounted() {},
  beforeDestroy() {
    console.log("紧急补货销毁了。");
  },
  //解决方案： 触发beforeDestory和destoryed
  beforeRouteLeave(to, from, next) {
    this.$destroy();
    next();
  },
};
</script>

<style lang="less" scoped>
::v-deep .p-table-edit {
  .ant-table-thead {
    tr {
      th:nth-child(2) {
        display: none;
      }
    }
  }
  .ant-table-body {
    min-height: auto;
    tr {
      td:nth-child(2) {
        display: none;
      }
    }
  }
}
</style>
