<template>
  <!-- 我的运单 -->
  <div class="home">
    <actionBar :operateList="operateList" :formList="formList" :ruleForm="searchRuleForm" @openModel="openModel"
      @searchProtocol="searchProtocol"></actionBar>
    <div class="card_content">
      <!-- 表单 -->
      <tables ref="refWaybill" :suspension="true" :tableList="tableList" :tableData="tableData"
        @buttonData="buttonData"></tables>
      <!-- 分页 -->
      <div v-if="Total">
        <pagination :total="Total" :currentPage="Pagination.PageIndex" @changeSize="changeSize"
          @changeCurrent="changeCurrent">
        </pagination>
      </div>
    </div>
    <el-dialog :title="staffTitle" :visible.sync="staffDialogVisible" width="60%" :close-on-click-modal="false"
      @close="closePopup">
      <div class="card_waybill">
        <div class="waybill_item" style="margin-right: 10px;">
          <waybillForm ref="sender" title="寄件人" :ruleForm="senderForm" @addressBook="getAddressBook('sender')">
          </waybillForm>
        </div>
        <div class="waybill_item" style="margin-left: 10px;">
          <waybillForm ref="recipients" title="收件人" :ruleForm="recipientsForm"
            @addressBook="getAddressBook('consignee')"></waybillForm>
        </div>
      </div>
      <div style="margin-top: 20px;">
        <forms ref="childRules" :formNewList="formRuleList" :ruleForm="ruleForm" labelWidth="80px">
        </forms>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="staffDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="handleAdd">确 定</el-button>
      </span>
    </el-dialog>
    <orderDetails ref="order" :mywaybill="mywaybill" :waybillData="waybillData"></orderDetails>
    <el-dialog title="批量导入" :visible.sync="bulkImportVisible" width="600px">
      <div class="card_bulkImport">
        <el-upload class="upload-demo" drag action="#" :limit="1" multiple :http-request="UploadImage">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">请上传xls或者xlsx格式文件</div>
        </el-upload>
        <div style="margin-top: 15px;">
          <el-button size="medium" type="primary" icon="el-icon-upload" :loading="importFlag"
            @click="immediateImport">立即导入</el-button>
          <el-button size="medium" icon="el-icon-download" :loading="downloadFlag"
            @click="templateDownload">模板下载</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="批量打印" :visible.sync="bulkPrintVisible" width="60%" :close-on-click-modal="false">
      <tables :suspension="true" :tableList="tableList1" :tableData="tableData1">
      </tables>
      <div style="display: flex;margin-top: 15px;justify-content: flex-end;">
        <div style="display: flex;align-items: center;margin-right: 10px;">
          <span style="font-size: 14px;margin-right: 8px;">湿度展示</span>
          <el-switch v-model="humidity"></el-switch>
        </div>
        <el-button size="medium" type="primary" icon="el-icon-printer" :loading="peintFlag"
          @click="bulkPrint">批量打印</el-button>
      </div>
    </el-dialog>
    <el-dialog title="下载PDF" :visible.sync="pdfDialogVisible" width="400px">
      <div style="display: flex;align-items: center;margin-right: 10px;">
        <span style="font-size: 14px;margin-right: 8px;">湿度展示</span>
        <el-switch v-model="humidityil"></el-switch>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="pdfDialogVisible = false">取 消</el-button>
        <el-button size="medium" type="primary" @click="downloadPdf(waybillNo)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    PDFDocument
  } from 'pdf-lib'
  import axios from 'axios'
  import Buffer from 'vue-buffer'
  import {
    waybillImport,
    exportTemplate
  } from '@/api/waybill'
  import {
    getWaybill,
    getWaybillDetails,
    addWaybill,
  } from '@/api/myWaybill'
  import {
    putWaybill,
    delWaybill,
    getTemperature
  } from '@/api/waybill'
  import actionBar from '@/components/actionBar'
  import tables from '@/components/tables'
  import pagination from '@/components/pagination'
  import waybillForm from '@/components/waybillForm'
  import forms from '@/components/forms'
  import orderDetails from '@/components/orderDetails'
  import {
    formRules,
    employee,
    employeeil
  } from "./myWaybillTable.js";
  import {
    myOrder
  } from '@/assets/js/blockSort'
  export default {
    name: 'MyWaybill',
    components: {
      actionBar,
      tables,
      pagination,
      waybillForm,
      forms,
      orderDetails
    },
    data() {
      return {
        mywaybill: true,
        operateList: [{
          type: 'print',
          title: '批量打印',
          colour: 'success',
          icon: 'el-icon-printer',
        }, {
          type: 'add',
          title: '添加运单',
          icon: 'el-icon-plus',
        }, {
          type: 'import',
          title: '批量导入',
          colour: 'warning'
        }],
        formList: [{
          type: 'input',
          label: '运单号',
          field: 'name',
          placeholder: '请输入运单号',
        }, {
          type: 'select',
          label: '状态',
          field: 'status',
          placeholder: '请选择状态',
          options: [{
              label: '未发货',
              value: 1,
            },
            {
              label: '已发货',
              value: 2,
            },
            {
              label: '已签收',
              value: 3,
            }
          ],
        }, {
          type: 'picker',
          label: '下单时间',
          field: 'time',
          placeholder: '下单时间',
        }],
        searchRuleForm: {
          name: '',
          status: '',
          time: [],
        },
        searchValue: {},
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        Total: 0,
        tableData: [],
        operationType: '',
        tableList: employee(),
        tableData: [],
        confirmLoading: false,
        staffTitle: '添加',
        staffDialogVisible: false,
        senderForm: {
          name: '',
          phone: '',
          region: '',
          address: '',
        },
        recipientsForm: {
          name: '',
          phone: '',
          region: '',
          address: '',
        },
        ruleForm: {
          temperatureInterval: '',
          deliveryCondition: '',
          cargoType: '',
          customerName: '',
          remark: '',
          quantity: '',
        },
        formRuleList: [],
        waybillData: {},
        bulkImportVisible: false,
        orderCustomer: '',
        importFile: null,
        importFlag: false,
        downloadFlag: false,
        bulkPrintVisible: false,
        tableList1: employeeil(),
        tableData1: [],
        peintFlag: false,
        humidity: true,
        pdfDialogVisible: false,
        humidityil: true,
        waybillNo: '',
      }
    },
    mounted() {
      const dataList = formRules();
      this.formRuleList = dataList;
      this.getList()
    },
    methods: {
      // 搜索
      searchProtocol(value) {
        this.searchValue = value
        if (value.time) {
          this.searchValue.orderStartTime = value.time[0]
          this.searchValue.orderEndTime = value.time[1]
        }
        this.getList()
      },
      // 获取运单列表
      getList() {
        var params = {
          page: this.Pagination.PageIndex,
          pageSize: this.Pagination.PageSize,
          ...this.searchValue
        }
        delete params.time
        getWaybill(params).then(res => {
          if (res.code == 200) {
            this.tableData = res.data.list
            this.Total = res.data.count
          }
        })
      },
      // 弹窗表单添加
      async handleAdd() {
        let senderFlag = this.$refs['sender'].validateForm();
        let recipientsFlag = this.$refs['recipients'].validateForm();
        let flag = this.$refs['childRules'].validateForm();
        if (senderFlag && recipientsFlag && flag) {
          this.confirmLoading = true
          var params = {
            senderAddressName: this.senderForm.name,
            senderAddressPhone: this.senderForm.phone,
            senderAddressDetails: this.senderForm.address,
            consigneeAddressName: this.recipientsForm.name,
            consigneeAddressPhone: this.recipientsForm.phone,
            consigneeAddressDetails: this.recipientsForm.address,
            ...this.ruleForm
          }
          params.quantity = Number(params.quantity)
          if (this.operationType == 'add') {
            await addWaybill(params).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
              }
              this.staffDialogVisible = false
              this.confirmLoading = false
            }).catch(() => {
              this.confirmLoading = false
            })
          } else if (this.operationType == 'edit') {
            params.id = this.orderId
            await putWaybill(params).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
              }
              this.staffDialogVisible = false
              this.confirmLoading = false
            }).catch(() => {
              this.confirmLoading = false
            })
          }
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      buttonData(row, type) {
        this.operationType = type
        this.orderId = row.id
        if (type == 'logs') {
          this.$refs.order.staffDialogVisible = true
          this.waybillData = row
        } else if (type == 'edit') {
          this.staffTitle = '编辑'
          this.staffDialogVisible = true
          setTimeout(() => {
            this.$nextTick(() => {
              this.senderForm.name = row.senderAddressName
              this.senderForm.phone = row.senderAddressPhone
              this.senderForm.address = row.senderAddressDetails
              this.recipientsForm.name = row.consigneeAddressName
              this.recipientsForm.phone = row.consigneeAddressPhone
              this.recipientsForm.address = row.consigneeAddressDetails
              this.ruleForm.temperatureInterval = String(row.temperatureInterval)
              this.ruleForm.deliveryCondition = row.deliveryCondition
              this.ruleForm.cargoType = row.cargoType
              this.ruleForm.quantity = row.quantity
              this.ruleForm.customerName = row.customerName
              this.ruleForm.remark = row.remark
            })
          })
        } else if (type == 'humiture') {
          const href = this.$router.resolve({
            name: 'WaybillInquiry',
            query: {
              waybillNo: row.waybillNo
            }
          }).href;
          window.open(href, "_blank");
        } else if (type == 'del') {
          this.deleteUser(row.id)
        } else if (type == 'pdf') {
          this.pdfDialogVisible = true
          this.waybillNo = row.waybillNo
          // this.downloadPdf(row)
        }
      },
      // 下载pdf
      downloadPdf(value) {
        getTemperature({
          waybillNo: value,
          humidityShow: this.humidityil,
        }).then(response => {
          if (response.fileName) {
            this.pdfDialogVisible = false
            //fileName = decodeURIComponent(filename);//对filename进行转码
            let fileName = decodeURI(response.fileName);
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(new Blob([response.data]), fileName);
            } else {
              let url = window.URL.createObjectURL(new Blob([response.data]));
              let link = document.createElement('a');
              link.style.display = 'none';
              link.href = url;
              link.setAttribute('download', fileName);
              document.body.appendChild(link);
              link.click();
            }
          } else {
            this.$message.error('未获取到文件名');
          }
        })
      },
      // 获取pdf
      requestPdf(waybillNo) {
        return new Promise((resolve) => {
          getTemperature({
            waybillNo: waybillNo,
            humidityShow: this.humidity,
          }).then(response => {
            if (response.fileName) {
              //fileName = decodeURIComponent(filename);//对filename进行转码
              let fileName = decodeURI(response.fileName);
              if (window.navigator.msSaveOrOpenBlob) {
                navigator.msSaveBlob(new Blob([response.data]), fileName);
              } else {
                let url = window.URL.createObjectURL(new Blob([response.data]));
                resolve(url);
              }
            }
          })
        });
      },
      openModel(type) {
        this.operationType = type
        if (type == 'add') {
          const dataList = formRules();
          this.formRuleList = dataList;
          this.staffTitle = '添加运单'
          this.staffDialogVisible = true
        } else if (type == 'import') {
          this.bulkImportVisible = true
        } else if (type == 'print') {
          const arrID = this.$refs.refWaybill.waybillIds
          if (arrID.length != 0) {
            let arr3 = []
            let arr4 = []
            arrID.forEach(item => {
              if (item.status == 8) {
                arr3.push(item)
                arr4.push(item.id)
              }
            })
            this.tableData1 = arr3
            this.printIdList = arr4
            if (arr3.length > 0) {
              this.bulkPrintVisible = true
            } else {
              this.$message({
                message: '请选择已签收的运单',
                type: 'warning'
              });
            }
          } else {
            this.$message({
              message: '请先选择需要批量操作的运单',
              type: 'warning'
            });
          }
        }
      },
      // 批量打印
      async bulkPrint() {
        this.peintFlag = true
        try {
          let resulr = []
          for (let i = 0; i < this.tableData1.length; i++) {
            let urlimg = await this.requestPdf(this.tableData1[i].waybillNo)
            if (urlimg) {
              resulr.push(urlimg)
            } else {
              throw new Error('请求错误，终止请求');
            }
          }
          const mergeBuffer = await this.mergePdf(resulr)
          //文件以pdf形式进行预览
          let blob = new Blob([mergeBuffer], {
            type: "application/pdf;chartset=UTF-8",
          });
          let fileURL = URL.createObjectURL(blob);
          window.open(fileURL);
          this.peintFlag = false
          this.bulkPrintVisible = false
        } catch (error) {
          throw new Error('请求错误，终止请求');
        }
      },
      async mergePdf(urlList) {
        // eslint-disable-next-line no-async-promise-executor
        return new Promise(async (resolve) => {
          const promises = []
          urlList.map((url) => {
            // eslint-disable-next-line no-async-promise-executor
            const tmp = new Promise(async (resolve) => {
              const response = await axios({
                method: 'get',
                url,
                responseType: 'arraybuffer'
              })
              resolve(Buffer.from(response.data))
            })
            promises.push(tmp)
          })

          const pdfBuffers = await Promise.all(promises)

          const newPdf = await PDFDocument.create()
          for (const buffer of pdfBuffers) {
            const pdfDocument = await PDFDocument.load(buffer)
            const contentPages = await newPdf.copyPages(
              pdfDocument,
              pdfDocument.getPageIndices()
            )
            for (const page of contentPages) {
              newPdf.addPage(page)
            }
          }
          const uint8Array = await newPdf.save()
          const mergeBuffer = Buffer.from(uint8Array)
          resolve(new Blob([mergeBuffer]))
        })
      },
      // 删除用户
      deleteUser(id) {
        this.$confirm('此操作将永久该运单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delWaybill({
            id: id,
          }).then(res => {
            if (res.code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.getList()
            }
          })
        }).catch(() => {});
      },
      // 导入
      immediateImport() {
        if (this.importFile) {
          this.importFlag = true
          let formData = new FormData();
          formData.append('file', this.importFile);
          formData.append('customerName', this.orderCustomer);
          waybillImport(formData).then(res => {
            if (res.code == 200) {
              this.bulkImportVisible = false
              this.getList()
              this.$message({
                message: '恭喜你，导入成功',
                type: 'success'
              });
            }
            this.importFlag = false
          }).catch(() => {
            this.importFlag = false
          })
        } else {
          this.$message({
            message: '请先选择上传文件',
            type: 'warning'
          });
        }
      },
      // 导出模板
      templateDownload() {
        this.downloadFlag = true
        exportTemplate().then(response => {
          let filename = '运单模板'
          this.blobDownload(response, filename)
          this.downloadFlag = false
        }).catch(() => {
          this.downloadFlag = false
        })
      },
      // 上传文件
      UploadImage(param) {
        this.importFile = param.file
      },
      // 导出文件流
      blobDownload(data, name) {
        let m = this;
        var content = data;
        var data = new Blob([content], {
          type: "application/vnd.ms-excel;charset=utf-8"
        });
        var downloadUrl = window.URL.createObjectURL(data);
        var anchor = document.createElement("a");
        anchor.href = downloadUrl;
        anchor.download = name + ".xls";
        anchor.click();
        window.URL.revokeObjectURL(data);
      },
      changeSize(val) {
        this.Pagination.PageSize = val
        this.getList()
      },
      changeCurrent(val) {
        this.Pagination.PageIndex = val
        this.getList()
      },
      // 清空表单
      closeDialog() {
        this.ruleForm = {}
        this.$refs.childRules.resetCheck();
      },
      // 关闭清空表单
      closePopup() {
        this.$refs.sender.resetForm()
        this.$refs.recipients.resetForm()
        this.$refs.childRules.resetCheck()
      }
    }
  }
</script>
<style lang="scss" scoped>
  .card_waybill {
    display: flex;
    border-bottom: 1px solid #E4E7ED;
  }

  .waybill_item {
    width: 50%;
  }

  .card_bulkImport {
    width: 100%;
  }

  ::v-deep .el-upload {
    width: 100%;
  }

  ::v-deep .el-upload-dragger {
    width: 100%;
  }

  .card_customer {
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    span {
      flex: none;
      font-size: 15px;
      margin-right: 8px;
    }
  }
</style>
