<template>
  <div>
    <!-- 单据补 -->
    <p-spin :spinning="spinning">
      <p-card title="单据补打">
        <span slot="extra">
          <a-space>
            <p-button type="primary" style="margin-right: 10px" @click="print">打印</p-button>
            <!-- <p-button v-if="key == 2" type="primary" style="margin-right: 10px" @click="PrintList">打印出库清单</p-button> -->
          </a-space>
        </span>
        <p-grid-form ref="form" :span="8" :items="config.items" @submit="hanlderSubmit" />
        <p-tabs default-active-key="1" @change="callback">
          <p-tab-pane key="1" tab="整件标签" force-render>
            <p-table
              ref="table"
              row-key="barcode"
              bordered
              :autoLoad="false"
              :selectedRowKeys.sync="selectedRowKeys1"
              :columns="config.TaskColumns"
              :remoteUrl="config.remoteUrl"
              :remoteParams="remoteParams1"
              @selectChange="selectChange"
              :rowSelectType="2"
              :doneBefore="doneBefore"
              :data-source="data"
              :scroll="{ x: 2500 }"
            >
              <span slot="action" slot-scope="text, record">
                <a href="javascript:;" class="ml-10" @click.stop="onShowCarrier(record)">修改承运商</a>
                <!-- <a href="javascript:;" class="ml-10" @click.stop="invoicePrint(record)">发票打印</a> -->
                <a href="javascript:;" class="ml-10" @click.stop="cancel(record)">取消</a>
              </span>
            </p-table>
          </p-tab-pane>
          <p-tab-pane key="2" tab="拼箱标签" force-render>
            <p-table
              ref="table"
              row-key="barcode"
              :autoLoad="false"
              bordered
              hasRowSelectCheck
              @selectChange="selectChange"
              :columns="config.OrderColumns"
              :remoteUrl="config.remoteUrl2"
              :remoteParams="remoteParams2"
              :selectedRowKeys.sync="selectedRowKeys2"
              :rowSelectType="1"
              :doneBefore="doneBefore"
              :data-source="data2"
              :scroll="{ x: true }"
            >
              <span slot="action" slot-scope="text, record">
                <a href="javascript:;" class="ml-10" @click.stop="onShowCarrier(record)">修改承运商</a>
                <!-- <a href="javascript:;" class="ml-10" @click.stop="invoicePrint(record)">发票打印</a> -->
                <a href="javascript:;" class="ml-10" @click.stop="cancel(record)">取消</a>
              </span>
            </p-table>
            <div>明细数据</div>
            <p-table
              ref="table"
              row-key="lclNo"
              bordered
              :selectedRowKeys.sync="selectedRowKeys22"
              @selectChange="selectChangesub"
              :columns="config.OrderColumnsSub"
              :rowSelectType="2"
              :data-source="data22"
              :scroll="{ x: true }"
            />
          </p-tab-pane>
          <!-- <p-tab-pane key="3" tab="整散合一拣货纸单" force-render>
            <p-table
              ref="table"
              row-key="id"
              :autoLoad="false"
              bordered
              hasRowSelectCheck
              @selectChange="selectChange"
              :columns="config.OrderColumns"
              :remoteUrl="config.remoteUrl3"
              :remoteParams="remoteParams3"
              :rowSelectType="1"
              :doneBefore="doneBefore"
              :data-source="data3"
              :scroll="{ x: true }"
            > -->
              <!-- <template slot="operation" slot-scope="text, record">
         
              <a @click="showmodel(text)">修改</a>
              <a-divider type="vertical" />
              <a @click="del(text)">删除</a>
            </template> -->
            <!-- </p-table> -->

            <!-- <div>明细数据</div>
            <p-table
              ref="table"
              row-key="pickTaskDId"
              bordered
              :selectedRowKeys.sync="selectedRowKeys3"
              @selectChange="selectChangesubwholeBulk"
              :columns="config.TaskColumns3Sub"
              :rowSelectType="2"
              :data-source="data33"
              :scroll="{ x: true }"
            />
          </p-tab-pane> -->
          <!-- <p-tab-pane key="4" tab="报告单" force-render>
            <p-table
              ref="table"
              row-key="id"
              :autoLoad="false"
              bordered
              hasRowSelectCheck
              @selectChange="selectChange"
              :columns="config.OrderColumns"
              :remoteUrl="config.remoteUrl3"
              :remoteParams="remoteParams3"
              :rowSelectType="1"
              :doneBefore="doneBefore"
              :data-source="data3"
              :scroll="{ x: true }"
            >
        
            </p-table>

            <div>明细数据</div>
            <p-table
              ref="table"
              row-key="pickTaskDId"
              bordered
              :selectedRowKeys.sync="selectedRowKeys3"
              @selectChange="selectChangesubwholeBulk"
              :columns="config.TaskColumns3Sub"
              :rowSelectType="2"
              :data-source="data33"
              :scroll="{ x: true }"
            />
          </p-tab-pane> -->
        </p-tabs>
      </p-card>
      <p-modal :visible="isShow"
              title="承运商"
              :width="1000"
              @ok="onSubmit"
              @cancel="onClose">
        <p-table ref="carrier"
                row-key="dictId"
                bordered dragle
                :remoteUrl="carrierRemoteUrl"
                :remoteData="carrierParams"
                :rowSelectType="1"
                :autoLoad="false"
                :selectedRowKeys.sync="carrierRowKeys"
                :data-source="carrierDataList"
                :scroll="{ x: true }"
                @selectChange = "selectCarrier"
                >
        <p-table-column data-index='dictCode' title='承运商编码' />
        <p-table-column data-index='dictName' title='承运商名称' />
        </p-table>
      </p-modal>
    </p-spin>
  </div>
</template>

<script>
import config from "./config.js";
import pick from "lodash.pick";
import { taskPrint, billPrint, wholeLabels, bulkdetail, lclPrint, wholeBulkdetail, printPaperslip, printAll, printInfo, carrierUrl, getDicttype, changeCarrier, cancelDoBillH } from "./api";
import { diffOption } from "@/views/kzyWMS/utils/index.js";
// 打印
import { toPrintServer, tempType } from "@/views/kzyWMS/utils/printServer.js";
export default {
  data() {
    return {
      isShow: false,
      carrierRowKeys:[],
      carrierRows:[],
      carrierDataList:[],
      carrierInfo: {},
      carrierParams:{},
      carrierRemoteUrl:carrierUrl,
      spinning: false,
      config: config(this),
      dataMark: {
        0: "pick_tag",
        1: "zjbhbq",
        2: "itemList.dataMark",
        3: "gnkfjhzd",
      },
      data: [],
      data2: [],
      data22: [],
      data3: [],
      data33: [],
      selectedRows: [],
      selectedRows1: [],
      selectedRows2: [],
      selectedRowKeys1: [],
      selectedRowKeys2: [],
      selectedRowKeys22: [],
      selectedRowKeys3: [],
      selectedRowKeys33: [],
      type: true,
      remoteParams1: {},
      remoteParams2: {},
      remoteParams3: {},
      visible: false,
      confirmLoading: false,
      key: 1,
    };
  },
  mounted() {
    // this.getinfo()
  },
  created() {
    // diffOption(this.config.OrderColumns).then((res) => {
    //   this.config.OrderColumns = res;
    // });
    // diffOption(this.config.TaskColumns).then((res) => {
    //   this.config.TaskColumns = res;
    // });
  },
  methods: {
    selectCarrier(selectedRowKeys, selectedRows) {
      this.carrierRows = selectedRows
    },
    selectChange(selectedRowKeys, selectedRows) {
      if (this.key == 1) {
        this.selectedRows = selectedRows
      }
      if (this.key == 2) {
        this.selectedRows2 = selectedRows
        // this.printwholeLabels();
        console.log(selectedRowKeys);
        if (selectedRowKeys.length) {
          this.selectedRowKeys2 = selectedRowKeys;
          this.getbulkdetail(selectedRows);
        } else {
          this.data22 = [];
        }
      }

      if (this.key == 3) {
        // this.printwholeLabels();
        console.log(selectedRowKeys);
        if (selectedRowKeys.length) {
          this.selectedRowKeys3 = selectedRowKeys;
          this.getwholeBulkdetail(selectedRowKeys);
        } else {
          this.data33 = [];
        }
      }

      //   this.selectedRows = selectedRows;
    },
    selectChangesub(selectedRowKeys, selectedRows) {
      this.selectedRowKeys22 = selectedRowKeys;
    },
    selectChangesubwholeBulk(selectedRowKeys, selectedRows) {
      this.selectedRowKeys33 = selectedRowKeys;
    },
    //整件打印
    async printwholeLabels() {
      if (this.selectedRowKeys1.length == 0) {
        this.$message.warning("请选择数据!");
        return;
      }
      let res1 = await printAll(this.selectedRows)
      if (res1.success) {
        res1.data.forEach(item => {
          printInfo(item.data.printAddress, item.data.printData).then(res2 => {
            console.log(res2, 'res2');
            if (res2.success) {
              this.$message.success(res2.message)
            } else {
              this.$message.error(res2.message)
            }
          })
        })
      } else {
        this.$message.error(res1.success)
      }
      //   let list = [];
      // console.log(this.selectedRowKeys1);
      // let warehouseId = this.$store.getters.warehouse.warehouseId;
      // let enterpriseId = this.$store.state.user.info.enterpriseId;
      // let data = {
      //   ids: this.selectedRowKeys1,
      //   enterpriseId,
      //   warehouseId,
      // };
      // let res = await wholeLabels(data);
      // console.log(res);

      // if (res.success) {
      //   let list = res.data;

      //   console.log(list);
        
      //   // for (let i = 0; i < list.length; i++) {
      //   //   await toPrintServer(list[i].data, warehouseId, this.dataMark[list[i].dataMark]);
      //   // }
      //   // toPrintServer(res.data.data, warehouseId, this.dataMark[res.data.dataMark]);
      // }
    },

    //获取拼箱打印
    async lclprint() {
      if (this.selectedRowKeys2.length == 0) {
        this.$message.warning("请选择数据!");
        return;
      }
      let res1 = await printAll(this.selectedRows2)
      if (res1.success) {
        this.$message.success(res1.success)
      } else {
        this.$message.error(res1.success)
      }
      // console.log(this.selectedRowKeys2, this.selectedRowKeys22);
      // let warehouseId = this.$store.getters.warehouse.warehouseId;
      // let enterpriseId = this.$store.state.user.info.enterpriseId;
      // let data = {
      //   billNo: this.selectedRowKeys2[0],
      //   ids: this.selectedRowKeys22,
      //   enterpriseId,
      //   warehouseId,
      // };

      // let res = await lclPrint(data);
      // console.log(res);
      // if (res.success) {
      //   let list = res.data;

      //   // for (let i = 0; i < list.length; i++) {
      //   //   await toPrintServer(list[i].data, warehouseId, this.dataMark[list[i].dataMark]);
      //   // }
      // }
    },

    //整散打印
    async printPaperslipFun() {
      if (!this.selectedRowKeys3.length || !this.selectedRowKeys33.length) {
        this.$message.warning("请选择数据!");
        return;
      }

      let warehouseId = this.$store.getters.warehouse.warehouseId;
      let enterpriseId = this.$store.state.user.info.enterpriseId;
      let data = {
        billNo: this.selectedRowKeys3[0],
        ids: this.selectedRowKeys33,
        enterpriseId,
        warehouseId,
      };

      let res = await printPaperslip(data);
      console.log(res);
      if (res.success) {
        let list = res.data;
        for (let i = 0; i < list.length; i++) {
          await toPrintServer(list[i].data, warehouseId, this.dataMark[list[i].dataMark]);
        }
      }
    },
    //获取拼箱明细
    async getbulkdetail(selectedRows) {
      console.log(selectedRows,'selectedRows');
      if (!selectedRows.length) return;
      let warehouseId = this.$store.getters.warehouse.warehouseId;
      let enterpriseId = this.$store.state.user.info.enterpriseId;
      let ids = selectedRows.map(item=>item.billId)

      // bulkdetail
      let data = {
        ids: ids,
        enterpriseId,
        warehouseId,
      };
      this.spinning = true;
      let res = await bulkdetail(data);
      this.spinning = false;
      console.log(res);
      if (res.success) {
        this.data22 = res.data;
      }
    },
    //获取整散明细行
    async getwholeBulkdetail(selectedRowKeys) {
      if (!selectedRowKeys.length) return;
      let warehouseId = this.$store.getters.warehouse.warehouseId;
      let enterpriseId = this.$store.state.user.info.enterpriseId;

      // bulkdetail
      let data = {
        ids: selectedRowKeys,
        enterpriseId,
        warehouseId,
      };
      this.spinning = true;
      let res = await wholeBulkdetail(data);
      this.spinning = false;
      console.log(res);
      if (res.success) {
        this.data33 = res.data;
      }
    },
    async print() {
      const warehouseId = this.$store.getters.warehouse.warehouseId;
      console.log(this.key);
      if (this.key == 1) {
        this.printwholeLabels();
      }
      if (this.key == 2) {
        this.lclprint();
      }
      if (this.key == 3) {
        this.printPaperslipFun();
      }
      if (this.key == 4) {
        this.printPaperslipFun();
      }
      return;
    },

    async PrintList() {
      const warehouseId = this.$store.getters.warehouse.warehouseId;
      if (this.selectedRows1.length == 0) {
        this.$message.warning("请选择数据!");
        return;
      }

      let data = {
        billnos: this.selectedRows1.map((i) => i.billno),
        taskIds: this.selectedRows1.map((i) => i.taskId),
        warehouseid: this.$store.getters.warehouse.warehouseId,
      };
      console.log(data);
      try {
        let res = await billPrint(data);
        console.log(res);
        if (res.success) {
          let print = res.data.filter(async (item) => {
            if (item.data.length > 0) {
              return toPrintServer(item.data, warehouseId, item.dataMark);
            } else {
              return false;
            }
          });
          console.log(print);
          let resList = await Promise.all(print);
          console.log(resList);
        } else {
          this.$exception(res);
        }
      } catch (error) {
        this.$exception(error);
      }
      this.selectedRows1 = [];
      //
    },
    callback(key) {
      console.log(key);
      this.key = key;
      //   this.selectedRows = [];
    },
    doneBefore(res) {
      console.log(res);
      return res;
    },
    hanlderSubmit(e, form) {
      e.preventDefault();
      console.log(this.key);
      form.validateFields((error, values) => {
        if (!error) {
          console.log(error, values, "valuesvaluesvaluesvaluesvalues");
          this["remoteParams" + this.key] = { ...this["remoteParams" + this.key], ...values };
        }
      });
    },
    async onShowCarrier(record) {
      this.carrierInfo = JSON.parse(JSON.stringify(record))
      
      this.isShow = true
      let res = await getDicttype({ typeCode: 'carrier_code', pageNum: 1, pageSize: 15 })
      console.log(res, 'res');
      if (res.success) {
        this.carrierDataList = []
        this.carrierParams = {
          dicttypeId: res.data.list[0].typeId,
          isEnable: 1,
        }
      } else {
        this.carrierDataList = []
      }
    },
    // 取消
    cancel(record) {
      const {barcode} = record
      const self = this
      this.$confirm({
        title: `确定是否要取消?`,
        onOk() {
          return new Promise((resolve, reject) => {
            cancelDoBillH([barcode]).then(res => {
              if (res.success) {
                self.$message.success(res.message)
                if (self.key == 1) {
                  self.remoteParams1 = { ...self.remoteParams1 }
                }
                if (self.key == 2) {
                  self.remoteParams2 = { ...self.remoteParams2 }
                }
                resolve()
              } else {
                self.$message.warn(res.message)
                resolve()
              }
            }).catch(() => {
              resolve()
            })
          })
        }
      })
    },
    // 修改承运商
    changeCarrier(code) {
      console.log(this.carrierInfo, 'this.carrierInfo')
      const { warehouseId } = this.$store.getters.warehouse
      let par = {
        billNo:this.carrierInfo.billId,
        oldWaybillCode:this.carrierInfo.barcode,
        oldCarrierCode:this.carrierInfo.carrierCode,
        newCarrierCode: code,
      }
      this.spinning = true
      changeCarrier(par).then(res => {
        this.spinning = false
        if (res.success) {
          if (res.data?.data?.printData?.data) {
            let par = {
              ...res.data.data.printData,
            }
            printAll(res.data.data.printAddress,par).then(res1 => {
              console.log(res1, 'res1');
              if (res1.success) {
                this.$message.success(res1.message)
              } else {
                this.$message.error(res1.message)
              }
            })
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },
    onSubmit() {
      if(this.carrierRows.length == 0) return this.$message.warn('请选择一条数据')
      const code = this.carrierRows[0].dictCode
      this.changeCarrier(code)
      this.onClose()
    },
    onClose() {
      this.carrierRowKeys = []
      this.carrierRows = []
      this.carrierDataList = []
      this.carrierInfo = {}
      this.isShow = false
    },
    handleOk(e) {
      console.log(this.$refs.model);
      this.$refs.model.form.validateFields(async (err, value) => {
        if (!err) {
          console.log(value);
          this.spinning = true;
          if (this.type) {
            let res = await update(value);
            console.log(res);
            if (res.success) {
              this.visible = false;
              this.$message.success(res.message);
              this.remoteParams = { ...this.remoteParams };
            } else {
              this.$exception(res);
              this.visible = false;
            }
          } else {
            let res = await add(value);
            console.log(res);

            if (res.success) {
              this.$message.success(res.message);
              this.visible = false;
              this.remoteParams = { ...this.remoteParams };
            } else {
              this.$exception(res);
              this.visible = false;
            }
          }

          this.spinning = false;
          //
        }
      });
    },
    handleCancel(e) {
      console.log("Clicked cancel button");
      this.visible = false;
    },

    del(text) {
      let that = this;
      console.log(text);
      this.$confirm({
        title: "确定是否要删除?",
        content: "",
        async onOk() {
          let res = await deletes({ areaNo: text.areaNo });
          if (res.success) {
            that.$message.success("删除成功");
            that.remoteParams = { ...that.remoteParams };
          } else {
            that.$exception(res);
          }
        },
        onCancel() {},
      });
    },
  },
};
</script>

<style lang="less" scoped></style>
