<!-- 整件拣货-待索取  -->
<template>
  <div class="tab0">
    <!-- 商品详情 -->
    <itemDetail ref="detailItem" :itemId="itemId" />
    <header>
      <p-input placeholder="请输入工号" v-model="search.operatorCode" />
      <p-input placeholder="请输入容器号" v-model="search.containerNo" />
      <p-checkbox :checked="isPrint" @change="onCheckChange"> 自动打印</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>
    <p-grid-form ref="search" :span="8" :label-col="{ span: 9 }" :items="items0" @submit="hanlderSubmit" />
    <p-table
      :columns="columns"
      :data-source="data"
      :has-row-count="true"
      :row-select-type="2"
      rowKey="pickTaskDId"
      dragle
      auto-width
      rowSelectFixed
      :scroll="{ x: true }"
      hasRowSelectCheck
      @checkRow="checkRow"
      :selectedRowKeys.sync="selectIds"
      :loading="loading"
      :pagination="pagination"
      @change="paginationChange"
      bordered
    >
      <!-- :pagination="pagination"
            @change="paginationChange" -->
      <template slot="status" slot-scope="text, rows, index">
        {{ text | statusFilter }}
      </template>
      <template slot="operation" slot-scope="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 { create_pickorder2, page_picktaskall, picktask_confirm, print_whole_labels } from "../../config/api.js";
// 设置默认仓库
import { setwarehouse } from "@/views/kzyWMS/SearchModal/mixins_warehouse.js";
import { items0, columns } from "../../config/wholePicking.js";
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: [],
      search: {
        warehouseId: this.$store.state.user.warehouse.warehouseId, //仓库id
        operatorCode: this.$store.getters.userInfo.employeeNo, //搜索工号
        containerNo: "", // 容器号
        isPrint: 1, //自动打印 ,接口传参
        isConfirm: 0, //自动确认,接口传参
        billNo: "", // 订单号
        containerCode: "", // 容器编号
      },
      isPrint: true, //自动打印
      columns: sorter(columns),
      items0: items0(this),
      data: [],
      loading: false,
      itemId: null,
      selectIds: [],
      type: [],
      pagination: {
        total: 0,
        pageSize: 10, //每页中显示10条数据
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ["10", "15", "20"], //每页中显示的数据
        showTotal: (total) => `共有 ${total} 条数据`, //分页中显示总的数据
      },
    };
  },
  methods: {
    // 异步打印查询
    println_search() {
      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_conba(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);
          });
          this.selectIds.length = 0; //打印完成后清空打印数据
          this.getData({ type: 0, ...this.$refs.search.form.getFieldsValue() }); //打印完刷新页面
        });
      } else {
        this.$message.warning("请选择打印数据！");
      }
    },
    // 索取按钮
    askFor() {
      let operatorCode = this.search.operatorCode;
      let containerNo = this.search.containerNo;

      let selectedRows = this.selectedRows;

      if (!operatorCode) {
        this.$message.warning("请先输入工号!");

        return;
      }
      //   if (selectedRows.length == 0) {
      //     this.$message.warning("请先选择索取数据");
      //     return;
      //   }

      this.isDisabled = true; //禁用，防止重
      this.$nextTick(() => {
        this.$refs.search.form.validateFields((err, values) => {
          if (!err) {
            console.log(this.search, values);
            // return;
            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: 0, ...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);
    },
    // 选择时的变化, 必须点到 checkbox 上或者'hasRowSelectCheck=true'点击行
    checkRow(selectedRowKeys, selectedRows) {
      console.log(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)));

      this.$emit("emitData", selectedRows); //可暂时不管
    },

    getData(params) {
      // 待索取tab=1，任务索取界面增加参数tab=2
      params = {
        pageNum: this.pagination.current, // 当前页码
        pageSize: this.pagination.pageSize, // 每页数量
        ...params,
        pickTaskType: 0,
        tab: "1",
      };
      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;
        });
    },
    paginationChange(pagination) {
      this.pagination = pagination;
      this.pagination.pageNum = pagination.current;
      this.getData({ ...this.$refs.gridform.form.getFieldsValue() });
    },
    // 索取 提交
    hanlderSubmit(event, form) {
      event.preventDefault();
      // this.getData(form.getFieldsValue())
      form.validateFields((err, values) => {
        if (!err) {
          console.log("验证通过: ", values);
          this.getData(values);
          // 刷新顶部信息
          this.$bus.$emit("refreshInfo");
        }
      });
    },
    // 重置
    hanlderRest(event, form) {
      form.resetFields();
    },
    // 商品详情
    checkItem(item) {
      this.itemId = item.itemId;
      this.$refs.detailItem.open();
    },
  }, //methods
  mounted() {
    // 	待索取任务分页查询(整件/功能库房)：
    // "pickTaskType", value = "任务类型（0-整件/2-整散合一）
    // this.getData({pickTaskType:0,...this.$refs.gridform.form.getFieldsValue()});
  },
};
</script>

<style scoped="scoped" lang="less">
//
.tab0 {
  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>
