<!-- 整件拣货 -->
<template>
  <div class="tab2">
    <!-- 商品详情 -->
    <itemDetail ref="detailItem" :itemId="itemId" />

    <!-- 登录 -->
    <workerLogin
      :loginVisible="loginVisible"
      :isSupervisedData="isSupervisedData"
      @loginResult="loginResult"
      @handleCancel="handleCancel"
    ></workerLogin>
    <!-- 红冲 -->
    <modal-red
      :modal_visible.sync="modal_visible"
      :modal_columns="modal_columns"
      :modal_data="modal_data"
      :modalType="modalType"
      @modal_confirm="modal_confirm"
    >
    </modal-red>

    <p-modal
      title="任务确认"
      width="80%"
      :visible="visible"
      :enlargeable="true"
      :draggable="true"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-table
        :columns="columns2"
        :data-source="data2"
        :has-row-count="true"
        rowKey="pickTaskDId"
        auto-width
        dragle
        :rowSelectType="false"
        :pagination="false"
        :loading="loading"
        bordered
      >
        <span slot="customTitle" style="color: #2b80ff"> 确认已拣数量 <a-icon type="check" /></span>
      </a-table>
      <p-input placeholder="请输入工号" size="large" v-model="search.operatorCode" disabled style="margin-top: 16px">
        <span slot="suffix" style="color: #ccc">工号</span>
      </p-input>
    </p-modal>
    <!-- <p-card title="整件拣货">
			<template slot="extra">
				<p-button type="primary" icon="pull-request" @click="hanlderSubmit">索取</p-button>
				<p-button type="primary" icon="check" @click="showModal">确认</p-button>
				<p-button type="primary" icon="printer">打印</p-button>
				<p-button type="primary" icon="redo" @click="hanlderRest">重置</p-button>
				<p-button type="primary" icon="unlock">解锁数量</p-button>
				<p-button type="primary" icon="scan">扫描监管码/物流码</p-button>
			</template>
		</p-card> -->
    <div style="margin-top: 16px; margin-bottom: 16px">
      <p-grid-form ref="search" :span="8" :label-col="{ span: 9 }" :items="items31" @submit="hanlderSubmit" />
    </div>

    <!--  dragle 通过 header 拖拽列 -->
    <p-table
      ref="table"
      auto-width
      dragle
      rowSelectFixed
      :scroll="{ x: true }"
      :columns="columns3"
      :data-source.sync="data"
      :row-select-type="2"
      :selectedRowKeys.sync="selectedRowKeys"
      rowKey="pickTaskDId"
      hasRowSelectCheck
      @checkRow="checkRow"
      @dblclickRow="dblclickRow"
      @change="paginationChange"
      :pagination="pagination"
      :loading="loading"
      bordered
    >
      <!-- @change='paginationChange'
      :pagination='pagination' -->
      <template slot="printStatus" slot-scope="text"> {{ text == "1" ? "已打印" : "未打印" }}</template>
      <template slot="status" slot-scope="text, rows, index">
        {{ text | statusFilter }}
      </template>
      <template v-slot:operation="text, rows, index">
        <a @click="checkItem(rows)">详情</a>
      </template>
    </p-table>
  </div>
</template>

<script>
// 商品详情
import itemDetail from "@/views/kzyWMS/components/itemDetail";
import { sorter } from "@/views/kzyWMS/utils/sort.js";

import modalRed from "../../components/modal_red.vue";
import workerLogin from "@/views/kzyWMS/outBound/check/innerCheck/components/workerLogin.vue";
import { modal_columns } from "../../config/zeroStockPicking.js";

// 设置默认仓库
import { setwarehouse } from "@/views/kzyWMS/SearchModal/mixins_warehouse.js";
import { items31, columns2, columns3 } from "../../config/wholePicking.js";
// 打印
import { toPrintServer, tempType } from "@/views/kzyWMS/utils/printServer.js";

import {
  page_picktaskall,
  picktask_confirm,
  picktask_confirm_red,
  isSupervised,
  print_whole_labels,
} from "../../config/api.js";
import { mapGetters } from "vuex";

export default {
  components: { workerLogin, modalRed, itemDetail },
  mixins: [setwarehouse],
  filters: {
    statusFilter(value) {
      if (value === "0") return "待索取";
      if (value === "1") return "待确认";
      if (value === "2") return "待复核";
      if (value === "3") return "已完成";
      return "";
    },
  },
  data() {
    return {
      columns2: sorter(columns2),
      columns3: sorter(columns3),
      modal_columns,
      rowSelection: { fixed: true },
      items31: items31(this),
      data: [],
      data2: [],
      selectedRowKeys: [],
      type: [], //"type":"类型：0-拣货 1-补货"
      selectIds: [],
      values: null,
      visible: false,
      confirmLoading: false,
      loading: false,
      itemId: null,
      search: {
        operatorCode: "", //搜索工号
        autoPrint: true, //自动打印
        autoConfirm: true, //自动确认
      },
      loginVisible: false,
      isSupervisedData: {},
      selectedRows: [], //
      modal_visible: false, //红冲弹窗
      modal_data: [],
      modalType: "wholePicking",
      red_params: {
        operatorCode: "", //工号 {红冲解锁人登录工号}
        redQty: 0, //冲红数量
        messageType: "", //错误处理方式
        redReason: "", //冲红原因
      },
      pagination: {
        total: 0,
        pageSize: 10, //每页中显示10条数据
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ["10", "15", "20"], //每页中显示的数据
        showTotal: (total) => `共有 ${total} 条数据`, //分页中显示总的数据
      },
    };
  },
  methods: {
    // 确认保存
    confirmSave(event) {
      if (this.selectedRows.length) {
        this.selectedRows = this.selectedRows.map((item) => {
          return {
            refBillId: item.pickTaskId, //拣选任务主表id
            refBillLineId: item.pickTaskDId, //拣选任务明细id
            ...item,
          };
        });
        let temp = this.selectedRows.filter((item) => item.isSupervise == 1);
        this.$refs.search.form.validateFields((err, values) => {
          if (!err) {
            // //是否完成扫描监管码
            isSupervised(this.selectedRows).then((res) => {
              if (res.success) {
                if (!res.data && temp.length) {
                  this.$emit("emitData", this.selectedRows, true, true);
                } else {
                  this.values = values;
                  this.$nextTick(() => {
                    this.data2 = [...this.selectedRows];
                    // if(this.search.autoConfirm){
                    this.visible = true;
                    // }
                  });
                }
              }
            });
          }
        });
      } else {
        this.$message.warning("请选择数据！");
      }
    },
    getData(params) {
      params = {
        pageNum: this.pagination.current, // 当前页码
        pageSize: this.pagination.pageSize, // 每页数量
        ...params,
      };
      this.loading = true;
      page_picktaskall(params)
        .then((res) => {
          this.loading = false;
          if (res.success) {
            this.data = res.data.list;
            // 扫描监管码数据
            // this.$emit('emitData',[...this.data]);
            this.pagination.total = Number(res.data.totalCount);
            this.selectedRowKeys.length = 0;
            this.selectedRows.length = 0;
          } else {
            this.$exception(res);
            this.loading = false;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    delSingle(record) {
      console.log({ record });
      this.loading = true;
      /* freightDelete({ ids: record.warehouseLocatorId }).then((res) => {
					if (res.success) {
					  this.visible = false
					  this.$message.success(res.message || '操作成功')
					  this.getData()
					} else {
					  this.$message.warning(res.message || '操作失败')
					}
					this.loading = false
				  }) */
    },
    paginationChange(pagination) {
      this.pagination = pagination;
      this.pagination.pageNum = pagination.current;
      this.getData({ type: 2, ...this.$refs.search.form.getFieldsValue() });
    },
    colChange({ name, value, index, label, record, modalRowData, config, vNode, options, moment, event }) {
      console.log("改变单元格数据：", name, value, index, label, record, modalRowData);
      this.data[index].pickQty = value;
      console.log("行修改后：", this.data[index]);
    },

    // 索取 提交
    hanlderSubmit(event, form) {
      event.preventDefault();
      // console.log("getFieldsValue:",form.getFieldsValue());
      // this.getData(form.getFieldsValue())
      this.$refs.search.form.validateFields((err, values) => {
        if (!err) {
          this.values = values;
          console.log("this.values: ", values);
          this.getData(values);
          // 刷新顶部信息
          this.$bus.$emit("refreshInfo");
        }
      });
    },
    // 重置
    hanlderRest(event, form) {
      this.$refs.search.form.resetFields();
    },
    // 拣货确认前过滤data数据
    getData_modal(val) {
      let _this = this;
      return new Promise(function (resolve, reject) {
        if (_this.data.length) {
          let temp = _this.data.map((item) => {
            return {
              operatorCode: val, // 拣选人工号
              pickQty: item.pickQty, //已拣数量
              pickTaskDId: item.pickTaskDId, //拣选任务明细id
            };
          });
          return resolve(temp);
        } else {
          _this.$message.warning("暂无数据！");
        }
      });
    },
    // 弹出框确认
    handleOk(e) {
      console.log("thsi.values", this.values);
      // this.getData_modal(this.search.operatorCode).then(res=>{
      if (this.selectedRows.length) {
        let params = this.selectedRows.map((item) => {
          return {
            ...item,
            operatorCode: this.values.operatorCode,
            warehouseId: this.values.warehouseId,
            warehouseCode: this.values.warehouseCode,
            warehouseName: this.values.warehouseName,
            bldgId: this.values.bldgId,
            bldgCode: this.values.bldgCode,
            bldgName: this.values.bldgName,
            pickQty: item.qty - item.saleRedQty, //确认已拣数量
          };
        });

        picktask_confirm(params).then((res) => {
          if (res.success) {
            this.visible = false;
            this.$message.success("确认成功");
            this.getData({ type: 2, ...this.$refs.search.form.getFieldsValue() });
            this.selectedRows.length = 0;
          } else {
            this.$exception(res);
          }
        });
      } else {
        this.$message.warning("无数据");
      }
      // })
    },

    // 红冲确认
    modal_confirm(red_data) {
      this.confirmLoading = true;
      console.log("emit红冲确认", red_data);
      picktask_confirm_red(red_data)
        .then((res2) => {
          if (res2.success) {
            this.confirmLoading = false;
            this.visible = false;
            this.$message.success("成功!");
            this.getData({ type: 2, ...this.$refs.search.form.getFieldsValue() });
          } else {
            this.$exception(res2);
            this.confirmLoading = false;
          }
        })
        .finally(() => {
          this.confirmLoading = false;
        });
    },
    // 登录成功后返回函数
    loginResult(bool, values) {
      // 解锁数量 登录工号
      this.red_params.operatorCode = values.workercode;

      this.loginVisible = bool; // 关闭登录窗
      this.modal_visible = true; //打开冲红窗
      let _this = this;
      this.$nextTick(() => {
        // 传入数据前 混入红冲参数 this.red_params 同时混入当前登录工号
        _this.selectedRows.map((item) => {
          return Object.assign(item, _this.red_params, { warehouseId: item.warehouseId || this.warehouse.warehouseId });
        });
        // 红冲数据
        _this.modal_data = [..._this.selectedRows];
      });
    },
    // 数量解锁
    unlock() {
      if (this.selectedRows.length) {
        (this.isSupervisedData = {
          warehouseId: this.$refs.search.form.getFieldsValue().warehouseId,
          specialWorkType: "整件拣货红冲",
        }),
          (this.loginVisible = true);
      } else {
        this.$message.warning("请选择数据！");
      }
    },
    handleCancel(e) {
      console.log("Clicked cancel button");
      this.visible = false; //关闭确认弹窗
      this.loginVisible = false; //关闭登录弹窗
    },
    // 选择时的变化, 必须点到 checkbox 上或者'hasRowSelectCheck=true'点击行
    checkRow(selectedRowKeys, selectedRows) {
      // 选择pickTaskDId，并去重
      this.selectIds = Array.from(new Set(selectedRows.map((item) => item.pickTaskDId)));
      // ,"type":"类型：0-拣货 1-补货"
      this.type = Array.from(new Set(selectedRows.map((item) => item.type)));
      console.log(selectedRowKeys, selectedRows);
      this.selectedRows = [...selectedRows];
      this.$emit("emitData", this.selectedRows, false, false);
    },
    dblclickRow(event, activeID, rowRecord) {
      console.log("双击行", event, activeID, rowRecord);
      this.selectedRows.length = 0;
      this.selectedRows.push(rowRecord);
      if (this.selectedRows[0].isSupervise) {
        this.$emit("emitData", this.selectedRows, true);
      } else {
        this.$message.warning("该单所有商品，无需扫描药品追溯码");
      }
    },
    // 商品详情
    checkItem(item) {
      this.itemId = item.itemId;
      this.$refs.detailItem.open();
    },
    // 异步打印查询
    println_search() {
      let _this = this;
      return new Promise((resolve, reject) => {
        this.$refs.search.form.validateFields((err, values) => {
          if (!err) {
            // 	{"pickTaskDIds":"id数组","warehouseId":"仓id","type":"类型：0-拣货 1-补货"}
            let params = {
              warehouseId: _this.$refs.search.form.getFieldsValue().warehouseId,
              type: _this.type[0], //"type":"类型：0-拣货 1-补货"
              pickTaskDIds: _this.selectIds,
            };
            print_whole_labels(params).then((res) => {
              if (res.success) {
                resolve(res.data[0].data);
              } else {
                _this.$message.warning("打印数据查询失败!", 5);
                reject("打印数据查询失败！");
              }
            });
          }
        });
      });
    },
    // 打印
    println() {
      if (this.selectIds.length) {
        if (this.type.length != 1) {
          this.$message.warn("数据有多个打印任务类型,只能选择一种任务类型打印！");
          return false;
        }

        this.println_search().then((res) => {
          console.log("打印：", res);
          // //"type":"类型：0-拣货标签pick_tag 1-补货标签zjbhbq"
          const warehouseId = this.$refs.search.form.getFieldsValue().warehouseId;
          toPrintServer(
            res,
            warehouseId,
            this.type[0] ? tempType.zjbhbq : tempType.pick_tag,
            this.$refs.search.form.getFieldsValue().bldgId
          ).then((res) => {
            if (!res.success) {
              this.$exception(res);
              return;
            }
            this.$message.success(res.message);
          });
        });
      } else {
        this.$message.warning("请选择打印数据！");
      }
    },
  }, //methods
  computed: {
    ...mapGetters(["userInfo", "warehouse"]),
  },
  mounted() {
    this.search.operatorCode = this.userInfo.employeeNo;
    this.$refs.search.form.setFieldsValue({
      operatorCode: this.userInfo.employeeNo,
    });
    // 	0：任务索取 1：任务确认
    // this.getData({type:1});
    this.$bus.$on("refreshData", (v) => {
      // 监管码后的刷新
      this.getData({ type: 2, ...this.$refs.search.form.getFieldsValue() });
      this.selectedRowKeys.length = 0;
      this.selectedRows.length = 0;
      console.log("整件拣货$bus.$on执行了。");
    });
  },
  // 给router-view加了个keep-alive导致组件缓存了，所以不会触发beforeDestory和destoryed
  beforeDestroy() {
    // 关闭监听
    this.$bus.$off("refreshData");
  },
  // 触发beforeDestory和destoryed
  beforeRouteLeave(to, from, next) {
    this.$destroy();
    next();
  },
};
</script>

<style scoped="scoped" lang="less">
.tab2 {
  min-height: 330px;
  padding-left: 20px;
  padding-right: 20px;
  box-sizing: border-box;

  /deep/ .qtyColor {
    .ant-table-column-title {
      color: #2b80ff;
    }
  }

  ::v-deep {
    .ant-btn {
      border-radius: 2px;
    }

    .p-table-edit .ant-table-body {
      min-height: 0;
    }

    .p-table-edit .ant-table-body ~ .ant-table-placeholder {
      min-height: 150px;
    }
  }
}
</style>
