<!-- 整件拣货  tab任务索取-->
<template>
  <div class="tab1">
    <!-- 商品详情 -->
    <itemDetail ref="detailItem" :itemId="itemId" />

    <p-modal
      title="自动确认"
      width="80%"
      :visible="visible"
      :enlargeable="true"
      :draggable="true"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <!-- 弹出窗数据同tab列表数据-->
      <a-table
        :columns="columns2"
        :data-source="data"
        :has-row-count="true"
        rowKey="pickOrderId"
        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" disabled v-model="search.operatorCode" style="margin-top: 16px" />
    </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> -->
    <header>
      <p-input placeholder="请输入工号" v-model="search.operatorCode" />
      <!--      <p-input v-if="businessData == 'int'" placeholder="请输入订单号" v-model="search.billNo" />-->
      <p-input placeholder="请输入托盘号" v-model="search.containerCode" />
      <p-checkbox :checked="isPrint" @change="onCheckChange"> 自动打印</p-checkbox>
      <!-- <p-checkbox :checked="isConfirm" @change="onCheckConfirm"> 自动确认 </p-checkbox> -->
      <p-button ref="refButton" type="primary" icon="pull-request" @clickSync="askFor">索取</p-button>
      <p-button type="primary" icon="printer" @click="println">打印</p-button>
    </header>
    <div style="margin-top: 16px; margin-bottom: 16px">
      <p-grid-form ref="search" :items="items" @submit="hanlderSubmit" />
    </div>

    <p-table
      :columns="columns"
      :data-source="data"
      :has-row-count="true"
      :rowSelectType="2"
      rowKey="pickTaskDId"
      dragle
      rowSelectFixed
      :scroll="{ x: true }"
      :selectedRowKeys.sync="selectedRowKeys"
      hasRowSelectCheck
      @checkRow="checkRow"
      @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 { toPrintServer, tempType } from "@/views/kzyWMS/utils/printServer.js";
// 设置默认仓库
import { setwarehouse } from "@/views/kzyWMS/SearchModal/mixins_warehouse.js";
import { items, columns, columns2 } from "../../config/wholePicking.js";
import { create_pickorder2, page_picktaskall, picktask_confirm, print_whole_labels } from "../../config/api.js";
import { mapGetters } from "vuex";
import { getBusiness } from "@/views/kzyWMS/api/business"; // 系统参数接口
import { page_waitpicktask } from "../../config/api.js";

export default {
  components: { 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 {
      selectedRows: [],
      columns: sorter(columns),
      columns2: sorter(columns2),
      items: items(this),
      data: [],
      selectedRowKeys: [],
      type: [], //"type":"类型：0-拣货 1-补货"
      itemId: null,
      businessData: "",
      selectIds: [],
      isDisabled: false,
      visible: false,
      confirmLoading: false,
      loading: false,
      isPrint: true, //自动打印
      isConfirm: false, //自动确认
      search: {
        warehouseId: this.$store.state.user.warehouse.warehouseId, //仓库id
        operatorCode: this.$store.getters.userInfo.employeeNo, //搜索工号
        isPrint: 1, //自动打印 ,接口传参
        isConfirm: 0, //自动确认,接口传参
        billNo: "", // 订单号
        containerCode: "", // 容器编号
      },
      pagination: {
        total: 0,
        pageSize: 10, //每页中显示10条数据
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ["10", "15", "20"], //每页中显示的数据
        showTotal: (total) => `共有 ${total} 条数据`, //分页中显示总的数据
      },
    };
  },
  methods: {
    // 选择时的变化, 必须点到 checkbox 上或者'hasRowSelectCheck=true'点击行
    checkRow(selectedRowKeys, selectedRows) {
      this.selectedRows = 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("类型：", this.type);
    },
    getData(params) {
      // 待索取tab=1，任务索取界面增加参数tab=2
      params = {
        pageNum: this.pagination.current, // 当前页码
        pageSize: this.pagination.pageSize, // 每页数量
        ...params,
        pickTaskType: 0,
        type: 0,
        tab: "2",
      };
      this.loading = true;
      page_waitpicktask(params)
        .then((res) => {
          this.loading = false;
          if (res.success) {
            this.data = res.data.list;
            // 扫描监管码数据
            // this.$emit('emitData',[...res.data.list]);
            this.pagination.total = Number(res.data.totalCount);
          } else {
            this.$exception(res);
            this.loading = false;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 索取按钮
    askFor() {
      // this.selectIds = Array.from(new Set(this.data.map((item) => item.pickTaskDId)))
      // console.log(this.data,'data')
      // console.log(this.selectIds,'222')
      // return
      let operatorCode = this.search.operatorCode;
      let selectedRows = this.selectedRows;
      if (!operatorCode) {
        this.$message.warning("请先输入工号!");
        return;
      }
      this.isDisabled = true; //禁用，防止重
      this.$nextTick(() => {
        this.$refs.search.form.validateFields((err, values) => {
          if (err) return;
          console.log(this.search, values);
          let params = Object.assign(this.search, {
            isPrint: this.search.isPrint ? 1 : 0,
            bldgId: this.$refs.search.form.getFieldsValue().bldgId,
            bldgCode: this.$refs.search.form.getFieldsValue().bldgCode,
            type: 0,
          });
          // console.log("索取参数：", params);
          let containerNo = [...new Set(selectedRows.map((i) => i.containerNo))].join(",");
          let pickTaskId = [...new Set(selectedRows.map((i) => i.pickTaskId))].join(",");
          console.log(containerNo, pickTaskId);
          params = { ...params, containerNo, pickTaskId };
          console.log(params);
          // return;
          create_pickorder2(params).then((res) => {
            if (res.success) {
              this.$message.success(`索取拣选单成功, 共${res.data.count}个任务`, 5);
              // 自动打印
              if (this.search.isPrint) {
                if (res.data.count) {
                  this.selectIds = Array.from(new Set(this.data.map((item) => item.pickTaskDId)));
                  console.log("this.selectIds:", this.selectIds);
                  this.println(); //调用打印
                } else {
                  this.$message.info("无自动打印数据！");
                }
              }

              this.getData({ type: 1, ...this.$refs.search.form.getFieldsValue() });
              setTimeout(() => {
                this.isDisabled = false;
              }, 500);
            } else {
              this.$exception(res);
              this.isDisabled = false;
            }
          });

          // 自动确认
          // if (this.search.isConfirm) {
          //   this.visible = true;
          // }
        });
      });
    },
    // 搜索自动打印
    onCheckChange(e) {
      // 同步:checked
      this.isPrint = e.target.checked;
      // 转换到搜索参数
      this.search.isPrint = e.target.checked ? 1 : 0;
      console.log(`checked = ${e.target.checked}`, this.search);
    },
    // 搜索自动确认
    onCheckConfirm(e) {
      // 同步:checked
      this.isConfirm = e.target.checked;
      // 转换到搜索参数
      this.search.isConfirm = e.target.checked ? 1 : 0;
      console.log(`checked = ${e.target.checked}`, this.search);
    },
    // 异步打印查询
    println_search() {
      return new Promise((resolve, reject) => {
        this.$refs.search.form.validateFields((err, values) => {
          if (err) return;
          // 	{"pickTaskDIds":"id数组","warehouseId":"仓id","type":"类型：0-拣货 1-补货"}
          const 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 === 0) return;
      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);
        });
        this.selectIds.length = 0; //打印完成后清空打印数据
        this.getData({ type: 1, ...this.$refs.search.form.getFieldsValue() }); //打印完刷新页面
      });
    },
    paginationChange(pagination) {
      this.pagination = pagination;
      this.pagination.pageNum = pagination.current;
      this.getData({ ...this.$refs.search.form.getFieldsValue() });
    },
    // 索取弹出窗 自动确认
    hanlderSubmit(event, form) {
      event.preventDefault();
      // console.log("getFieldsValue:",form.getFieldsValue());
      this.$refs.search.form.validateFields((err, values) => {
        if (!err) {
          console.log("验证通过: ", 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, //已拣数量
              warehouseId: item.warehouseId, // 仓库id
              pickTaskDId: item.pickTaskDId, //拣选任务明细id
            };
          });
          return resolve(temp);
        } else {
          _this.$message.warning("暂无数据！");
        }
      });
    },
    // 弹出框确认
    handleOk(e) {
      if (this.search.operatorCode) {
        this.confirmLoading = true;
        this.getData_modal(this.search.operatorCode).then((res) => {
          console.log("拣货确认弹出data:", res);
          picktask_confirm(res).then((res2) => {
            if (res2.success) {
              this.confirmLoading = false;
              this.visible = false;
              this.$message.success("确认成功");
            } else {
              this.$exception(res);
              this.confirmLoading = false;
            }
          });
        });
      } else {
        this.$message.warning("请输入工号");
      }
      /* this.$refs.modalOk.form.validateFields((err, values) => {
				        if (!err) {
				          console.log('弹出框: ', values);
				        }
				      }); */
    },
    // 弹出框取消
    handleCancel(e) {
      console.log("Clicked cancel button");
      this.visible = false;
    },
    // 商品详情
    checkItem(item) {
      this.itemId = item.itemId;
      this.$refs.detailItem.open();
    },
  }, //methods
  computed: {
    ...mapGetters(["userInfo"]),
  },
  mounted() {
    // 	0：任务索取 1：任务确认
    // this.getData({type:0});
    this.$refs.search.form.setFieldsValue({
      operatorCode: this.userInfo.employeeNo,
    });
    this.$refs.refButton.wait = 1000;
    getBusiness().then((res) => {
      this.businessData = res; // 系统参数
    });
    // this.getData({type:0,...this.$refs.search.form.getFieldsValue()});
  },
};
</script>

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

  header {
    height: 68px;
    line-height: 68px;
    background: #feffe0;

    ::v-deep {
      // 工号
      .ant-input {
        width: 246px;
        height: 36px;
        border-radius: 2px;
        margin-left: 14px;
      }

      // 自动打印
      .ant-checkbox-wrapper {
        margin-left: 20px;

        > span:last-child {
          font-weight: bold;
          font-size: 14px;
          color: #323233;
          letter-spacing: 1px;
        }
      }

      .ant-btn-primary {
        margin-left: 20px;
        height: 36px;
      }
    }
  }

  ::v-deep {
    .ant-btn {
      border-radius: 2px;
    }
  }
}
</style>
