<!--
@name: 销售订单管理
@author: dufeng
@time: 2021-12-29
-->
<template>
  <p-spin :spinning="spinning">
    <div v-if="!editType">
      <p-card title="出库订单管理">
        <div slot="extra">
          <p-button icon="filter" @click="toggleFormTag = !toggleFormTag">{{ toggleFormTag ? "隐藏" : "显示" }}</p-button>
          <p-button class="ml-10" type="primary" @click="toEdit('add')">新增订单</p-button>
        </div>
        <p-grid-form ref="formTarget" v-show="toggleFormTag" :span="6" :labelCol="{ span: 6 }" :items="items" @submit="handleSubmit" />
        <p-card title="订单列表">
          <p-table
            ref="masterTable"
            :remoteUrl="tableRemoteUrl"
            :remoteData="remoteParams"
            :remoteParams="remoteParams"
            :selectedRowKeys.sync="selectedRowKeys"
            :scroll="{ x: true }"
            dragle
            :columns="masterColumns"
            row-key="billid"
            @clickRow="clickRow"
          >
            <span slot="action" slot-scope="text, record">
              <!--            <a href="javascript:;" @click.stop="toEdit('edit', record)">编辑</a>-->
              <a-space>
                <a href="javascript:;" @click.stop="onDownload(record)">发票下载</a>
                <a href="javascript:;" @click.stop="onShowPrint('PRINT_NULL', record)">空模板打印</a>
                <a href="javascript:;" @click.stop="onShowPrint('WMS_PRINT', record)">出库清单打印</a>
                <a href="javascript:;" @click.stop="onShowPrint('download', record)">出库清单下载</a>
                <a href="javascript:;" @click.stop="invoicePrint(record)">发票打印</a>
                <a href="javascript:;" @click.stop="cancel(record)">取消</a>
              </a-space>
            </span>
          </p-table>
        </p-card>
        <p-card title="明细列表">
          <p-table
            ref="detailsTable"
            dragle
            bordered
            row-key="lineid"
            :scroll="{ x: true }"
            :autoLoad="false"
            :rowSelectType="false"
            :columns="detailsColumns"
            :data-source.sync="detailsDataList"
            :remote-url="detailsRemoteUrl"
            :remoteParams="detailsRemoteData"
          />
        </p-card>
      </p-card>
    </div>
    <edit v-else :editData="editData" :type="editType" @back="back" />
    <p-modal :visible="visible" title="公共字典-打印类型" :width="1000" @ok="handleOk" @cancel="handleCancel">
      <p-table
        ref="print"
        row-key="dictId"
        bordered
        dragle
        :remoteUrl="printRemoteUrl"
        :remoteData="printParams"
        :rowSelectType="1"
        :autoLoad="false"
        :selectedRowKeys.sync="printRowKeys"
        :data-source="printDataList"
        :scroll="{ x: true }"
        @selectChange="selectChange"
      >
        <p-table-column data-index="dictCode" title="字典编号" />
        <p-table-column data-index="dictName" title="字典名称" />
        <p-table-column data-index="attr1" title="分组1" />
        <p-table-column data-index="attr2" title="分组2" />
        <p-table-column data-index="attr3" title="分组3" />
        <p-table-column data-index="attr4" title="分组4" />
        <p-table-column data-index="attr5" title="分组5" />
        <p-table-column data-index="dictDesc" title="备注" />
      </p-table>
    </p-modal>
  </p-spin>
</template>
<script>
import { formItems, masterColumns, detailsColumns } from "./js/config";
import edit from "./edit";
import { upcloud_base_wh_outbound, upcloud_base_common } from "@/config/serviceSettings";
import { getDefaultCargoOwner } from "@/views/kzyWMS/utils/setCargoOwner";
import { cancelDoBillH, outDetailedPrint, outReceiptPrint, getDicttype, detailedPrint, printAll, getInvoices, detailedDownload } from "./api";

export default {
  components: { edit },
  data() {
    return {
      spinning: false,
      visible: false,
      toggleFormTag: true,
      items: formItems(this),
      masterColumns,
      detailsColumns,
      selectedRowKeys: [],
      tableRemoteUrl: {
        url: upcloud_base_wh_outbound + "/outboundOrder/queryDoBillHList",
        method: "post",
      },
      remoteParams: {},
      editData: {},
      editType: "",
      detailsRemoteData: {},
      detailsDataList: [],
      detailsRemoteUrl: {
        url: upcloud_base_wh_outbound + "/outboundOrderLine/queryDoBillDList",
        method: "post",
      },
      printRemoteUrl: {
        url: upcloud_base_common + "/dict/page",
        method: "post",
      },
      printParams: {},
      printDataList: [],
      printRowKeys: [],
      printInfo: {},
      printRows: [],
      printType: "",
    };
  },
  mounted() {
    this.setDefaultData();
  },
  methods: {
    onDownload(record) {
      this.spinning = true;
      getInvoices({ billno: record.billno }).then((res) => {
        this.spinning = false;
        if (res.success) {
          if (!res.data) return this.$message.warn("暂无数据");
          let list = res.data;
          if (list.length === 0) return;
          list.forEach((item, index) => {
            setTimeout(() => {
              window.open(item, `one${index}`);
            }, 0);
          });
        } else {
          this.$message.error(res.message);
        }
      });
    },
    onDownloadOrder(record) {
      this.spinning = true;
      getInvoices({ billno: record.billno }).then((res) => {
        this.spinning = false;
        if (res.success) {
          if (!res.data) return this.$message.warn("暂无数据");
          let list = res.data;
          if (list.length === 0) return;
          list.forEach((item, index) => {
            setTimeout(() => {
              window.open(item, `one${index}`);
            }, 0);
          });
        } else {
          this.$message.error(res.message);
        }
      });
    },
    selectChange(p1, p2) {
      console.log(p2, "p2");
      this.printRows = p2;
    },
    async onShowPrint(type, record) {
      this.printType = type;
      this.printInfo = JSON.parse(JSON.stringify(record));
      if (type == "download") {
        type = "WMS_PRINT";
      }
      this.visible = true;
      let res = await getDicttype({ typeCode: type, pageNum: 1, pageSize: 999 });
      console.log(res, "res");
      if (res.success) {
        this.printDataList = [];
        this.printParams = {
          dicttypeId: res.data.list[0].typeId,
          isEnable: 1,
        };
      } else {
        this.printDataList = [];
      }
    },
    handleOk() {
      if (this.printRows.length == 0) return this.$message.warn("请选择一条数据");
      const code = this.printRows[0].dictCode;
      // 出库清单打印
      if (this.printType === "WMS_PRINT") this.outOrderPrint(code);
      // 空模板打印
      if (this.printType === "PRINT_NULL") this.outDetailedPrint(code);
      //出库清单下载
      if (this.printType === "download") this.outOrderPrintdownload(code);
    },
    handleCancel() {
      this.printRowKeys = [];
      this.printRows = [];
      this.printDataList = [];
      this.printInfo = {};
      this.visible = false;
    },
    // 出库清单打印
    outOrderPrint(code) {
      console.log(this.printInfo, "this.printInfo");
      const { warehouseId } = this.$store.getters.warehouse;
      let par = {
        warehouseId: warehouseId,
        consignorid: this.printInfo.consignorid,
        billId: this.printInfo.billid,
        printBillCode: code,
      };
      this.spinning = true;
      detailedPrint(par).then((res) => {
        this.spinning = false;
        if (res.success) {
          this.handleCancel();
          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("暂无打印数据");
          }
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 出库清单下载
    outOrderPrintdownload(code) {
      console.log(this.printInfo, "this.printInfo");
      const { warehouseId } = this.$store.getters.warehouse;
      let par = {
        warehouseId: warehouseId,
        consignorid: this.printInfo.consignorid,
        billId: this.printInfo.billid,
        printBillCode: code,
      };
      this.spinning = true;
      detailedDownload(par).then((res) => {
        this.spinning = false;
        this.handleCancel();
        const url = window.URL.createObjectURL(new Blob([res]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "出库清单.pdf");
        document.body.appendChild(link);
        link.click();
      
      });
    },
    // 发票打印
    invoicePrint(record) {
      const { warehouseId } = this.$store.getters.warehouse;
      let par = {
        warehouseId: warehouseId,
        consignorid: record.consignorid,
        billId: record.billid,
      };
      this.spinning = true;
      outReceiptPrint(par).then((res) => {
        this.spinning = false;
        if (res.success) {
          this.$message.success(res.message);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 空模板打印
    outDetailedPrint(code) {
      console.log(this.printInfo, "this.printInfo");
      // const { warehouseId } = this.$store.getters.warehouse
      let par = {
        // warehouseId:warehouseId,
        // consignorid:this.printInfo.consignorid,
        // billId:this.printInfo.billid,
        printBillCode: code,
      };
      this.spinning = true;
      outDetailedPrint(par).then((res) => {
        this.spinning = false;
        if (res.success) {
          this.handleCancel();
          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("暂无打印数据");
          }
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 设置默认数据
    async setDefaultData() {
      // 设置仓库
      const { warehouseId, warehouseCode, warehouseName } = this.$store.getters.warehouse || {};
      this.$refs.formTarget.form.setFieldsValue({
        branchid: warehouseId,
        branchcode: warehouseCode,
        branchname: warehouseName,
      });
      // 设置货主
      const cargoOwner = await getDefaultCargoOwner();
      if (!!cargoOwner) {
        const { companyCode, companyId, companyName } = cargoOwner;
        this.$refs.formTarget.form.setFieldsValue({
          consignorid: companyId,
          consignorcode: companyCode,
          consignorname: companyName,
        });
        this.$refs.formTarget.form.disableItem("consignorname");
      }
    },
    handleSubmit(event, form) {
      event.preventDefault();
      form.validateFields((error, values) => {
        if (error) return;
        delete values.adata;
        delete values.bdata;
        values.shipperid = values.customerId;
        this.remoteParams = values;
        this.detailsDataList = [];
      });
    },
    back() {
      this.editType = "";
      this.$nextTick(this.onSubmit);
    },
    toEdit(type, row = {}) {
      this.editData = row;
      this.editType = type;
    },
    // 取消
    cancel(record) {
      const { billid } = record;
      const self = this;
      this.$confirm({
        title: `确定是否要取消?`,
        onOk() {
          return new Promise((resolve, reject) => {
            cancelDoBillH({ billid })
              .then((res) => {
                if (res.success) {
                  self.$message.success(res.message);
                  self.$refs.masterTable.reload();
                  self.detailsDataList = [];
                  resolve();
                } else {
                  self.$message.warn(res.message);
                  resolve();
                }
              })
              .catch(() => {
                resolve();
              });
          });
        },
      });
    },
    clickRow(form, rowKey, data) {
      const { billid, billno } = data;
      this.detailsRemoteData = { billid, billno };
    },
  },
};
</script>
<style lang="less" scoped>
/deep/ .date-range {
  .ant-calendar-picker {
    width: 100% !important;
  }
}
</style>
<style>
.dropdownClassName1 {
  left: auto !important;
  right: 50px !important;
}
</style>
