<template>
  <!-- 运单管理 -->
  <div class="waybill_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="800px" :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>
      <el-dialog width="60%" title="地址簿" :visible.sync="innerVisible" append-to-body>
        <div class="space_between_in" style="margin-bottom: 15px;">
          <div style="display: flex;align-items: center;">
            <h3 style="margin-left: 10px;flex: none;">搜索：</h3>
            <el-input v-model="bookInput" style="width: 260px;" placeholder="请输入姓名、电话、地址快速查找"></el-input>
          </div>
          <el-radio-group v-model="tabPosition" @input="handleClick">
            <el-radio-button label="my">我的</el-radio-button>
            <el-radio-button label="all">全部</el-radio-button>
          </el-radio-group>
        </div>
        <div class="card_book_list">
          <!-- 表单 -->
          <tables :suspension="true" :tableList="bookTableList" :tableData="bookTableData" @cellClick="cellClick"
            @buttonData="buttonData">
          </tables>
          <!-- 分页 -->
          <div v-if="bookTotal">
            <pagination :total="bookTotal" :currentPage="bookPagination.PageIndex" @changeSize="bookChangeSize"
              @changeCurrent="bookChangeCurrent">
            </pagination>
          </div>
        </div>
      </el-dialog>
      <el-dialog width="700px" :visible.sync="innerVisibleTime" append-to-body :close-on-click-modal="false"
        @close="closePopup1">
        <div style="display: flex;margin-bottom: 10px;" v-if="humitureList.length > 0">
          <div class="flex1_time_title"></div>
          <el-col :span="12">
            <div class="flex1_time center_in">开始时间</div>
          </el-col>
          <el-col :span="12">
            <div class="flex1_time center_in">结束时间</div>
          </el-col>
        </div>
        <div style="display: flex;flex-direction: column;" v-if="humitureList.length > 0">
          <el-form :model="timeRuleForm" :rules="rules" ref="timeRuleForm" label-width="170px" label-position="left"
            class="demo-ruleForm">
            <el-form-item :label="item.title" required v-for="(item,index) in humitureList" :key="index">
              <el-col :span="12">
                <el-form-item prop="date1">
                  <el-date-picker style="width: calc(100% - 20px);margin:0px 10px;" v-model="item.startTime"
                    type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" placeholder="开始时间"
                    @change="timeChange"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="date2">
                  <el-date-picker style="width: calc(100% - 20px);margin:0px 10px;" v-model="item.endTime"
                    type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" placeholder="结束时间"
                    @change="timeChangeil"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-form>
        </div>
        <el-empty description="暂无数据" v-else></el-empty>
        <span slot="footer" class="dialog-footer">
          <el-button plain @click="innerVisibleTime = false">取 消</el-button>
          <el-button type="primary" :loading="timeLoading" @click="taskTime">提 交</el-button>
        </span>
      </el-dialog>
      <el-dialog width="700px" :visible.sync="logisticsVisibleTime" append-to-body :close-on-click-modal="false"
        @close="closePopup2">
        <div v-if="activitiesList.length > 0">
          <el-timeline>
            <el-timeline-item :type="item.field" v-for="(item, index) in activitiesList" :key="index">
              {{item.content}}<br/>
              <slot name="timestamp">
                <el-date-picker style="margin-top: 6px;" v-model="item.createdAt" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss" placeholder="开始时间"></el-date-picker>
              </slot>
            </el-timeline-item>
          </el-timeline>
        </div>
        <el-empty description="暂无数据" v-else></el-empty>
        <span slot="footer" class="dialog-footer">
          <el-button plain @click="logisticsVisibleTime = false">取 消</el-button>
          <el-button type="primary" :loading="timeLoading" @click="logisticsTaskTime">提 交</el-button>
        </span>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <div class="space_between_in">
          <div style="display: flex;">
            <el-button v-if="userList.type == 1" type="success" plain @click="missionTime">编辑任务时间</el-button>
            <el-button v-if="userList.type == 1" type="warning" plain @click="logisticsTime">编辑物流时间</el-button>
          </div>
          <div style="display: flex;align-items: center;">
            <el-button plain @click="staffDialogVisible = false">取 消</el-button>
            <el-button type="primary" :loading="confirmLoading" @click="handleAdd">确 定</el-button>
          </div>
        </div>
      </span>
    </el-dialog>
    <el-dialog title="派单" :visible.sync="sendDialogVisible" width="500px" :close-on-click-modal="false"
      @close="closeDialog">
      <forms ref="sendRules" :formNewList="sendRuleList" :ruleForm="sendRuleForm" labelWidth="80px"
        @radioInput="radioInput" @remoteMethod="remoteMethod">
      </forms>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="sendDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="sendConfirmLoading" @click="sendHandleAdd">确 定</el-button>
      </span>
    </el-dialog>
    <orderDetails ref="order" :waybillData="waybillData"></orderDetails>
    <el-dialog title="批量导入" :visible.sync="bulkImportVisible" width="600px">
      <div class="card_customer">
        <span>下单客户</span>
        <el-input v-model="orderCustomer" placeholder="请输入内容"></el-input>
      </div>
      <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>
        <div class="card_printWay">
          <span>{{waybillNo}}</span>
        </div>
        <!--  <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" :loading="pdfFlag" @click="downloadPdf(waybillNo)">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="打印运单" :close-on-click-modal="false" :visible.sync="printWaybillVisible" width="400px"
      @close="printClose">
      <div style="display: flex;align-items: flex-start;margin-right: 20px;">
        <span style="font-size: 14px;margin-right: 8px;">运单号：</span>
        <div style="display: flex;flex-direction: column;">
          <div class="same_row_in card_printWay" v-for="(item,index) in printData" :key="index">
            <span>{{item}}</span>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="printWaybillVisible = false">取 消</el-button>
        <el-button size="medium" type="primary" :loading="definitFlag" @click="definitePrint()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    PDFDocument
  } from 'pdf-lib'
  import axios from 'axios'
  import Buffer from 'vue-buffer'
  import {
    getWaybill,
    addWaybill,
    putWaybill,
    delWaybill,
    waybillDelivery,
    waybillImport,
    exportTemplate,
    getTemperature,
    getWaybillPdf
  } from '@/api/waybill'
  import {
    getAddress,
    getAddressDetails,
    addAddress,
    putAddress,
    delAddress
  } from '@/api/address'
  import {
    getWarehouse
  } from '@/api/warehouse.js'
  import {
    getCar
  } from '@/api/vehicle.js'
  import {
    getCoolerBox
  } from '@/api/incubator.js'
  import {
    getUser
  } from '@/api/user.js'
  import {
    getLogisticsWaybill,
    getWaybillTask,
    putWaybillTask,
    putWaybillLogistics
  } from '@/api/waybillLogistics'
  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,
    addressBook,
    sendList,
    employee1
  } from "./waybill.js";
  import {
    WaybillStatus
  } from '@/assets/js/blockSort'
  import {
    regionData,
    CodeToText
  } from 'element-china-area-data'
  export default {
    name: 'WaybillManagement',
    components: {
      actionBar,
      tables,
      pagination,
      waybillForm,
      forms,
      orderDetails
    },
    data() {
      return {
        operateList: [{
          type: 'printWaybill',
          title: '批量打印运单',
          colour: 'success',
          icon: 'el-icon-printer',
        }, {
          type: 'print',
          title: '批量打印PDF',
          colour: 'success',
          icon: 'el-icon-printer',
        }, {
          type: 'sends',
          title: '批量派单',
          colour: 'success'
        }, {
          type: 'import',
          title: '批量导入',
          colour: 'warning'
        }, {
          type: 'add',
          title: '添加运单',
          icon: 'el-icon-plus',
        }],
        formList: [{
          type: 'input',
          label: '运单号',
          field: 'waybillNo',
          placeholder: '请输入运单号',
        }, {
          type: 'select',
          label: '状态',
          field: 'status',
          placeholder: '请选择状态',
          options: WaybillStatus(),
        }, {
          type: 'picker',
          label: '下单时间',
          field: 'time',
          placeholder: '下单时间',
        }],
        searchRuleForm: {
          waybillNo: '',
          status: null,
          time: [],
        },
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        Total: 0,
        tableData: [],
        operationType: '',
        tableList: employee(),
        bookTableData: [],
        bookPagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        bookTotal: 0,
        confirmLoading: false,
        staffTitle: '添加',
        staffDialogVisible: false,
        innerVisible: false,
        senderForm: {
          name: '',
          phone: '',
          region: '',
          address: '',
        },
        recipientsForm: {
          name: '',
          phone: '',
          region: '',
          address: '',
        },
        tabPosition: 'my',
        bookInput: '',
        bookTableList: [],
        bookList: {
          field: 'action',
          label: '操作',
          align: 'center',
          labelButton: [{
            type: 'edit',
            label: '编辑',
            icon: 'el-icon-edit',
            style: 'primary',
          }, {
            type: 'del',
            label: '删除',
            icon: 'el-icon-delete',
            style: 'danger',
          }]
        },
        ruleForm: {
          temperatureInterval: '',
          deliveryCondition: '',
          cargoType: '',
          customerName: '',
          remark: '',
          quantity: '',
        },
        formRuleList: [],
        bookType: '',
        sendDialogVisible: false,
        sendRuleList: sendList(),
        sendRuleForm: {
          type: 2,
          printUserId: null,
          coolerBoxId: null,
        },
        sendConfirmLoading: false,
        orderId: null,
        waybillIdList: [],
        waybillData: {},
        bulkImportVisible: false,
        importFlag: false,
        downloadFlag: false,
        importFile: null,
        orderCustomer: '',
        staffName: '',
        sendOrdersId: 2,
        searchValue: {},
        bulkPrintVisible: false,
        tableList1: employee1(),
        tableData1: [],
        printIdList: [],
        peintFlag: false,
        humidity: true,
        pdfDialogVisible: false,
        humidityil: false,
        waybillNo: '',
        // 运单
        printWaybillVisible: false,
        printData: [],
        definitFlag: false,
        pdfFlag: false,
        userList: {},
        innerVisibleTime: false,
        humitureList: [],
        timeLoading: false,
        timeRuleForm: {
          date1: '',
          date2: '',
        },
        rules: {
          date1: [{
            required: true,
            message: '请选择开始时间',
            trigger: 'change'
          }],
          date2: [{
            required: true,
            message: '请选择结束时间',
            trigger: 'change'
          }],
        },
        logisticsVisibleTime: false,
        statusList: WaybillStatus(),
        activitiesList: [],
      }
    },
    mounted() {
      const dataList = formRules();
      this.formRuleList = dataList;
      this.getList()
      const arr = localStorage.getItem('userList')
      const userArr = JSON.parse(arr)
      this.userList = userArr
    },
    methods: {
      // 搜索
      searchProtocol(value) {
        this.Pagination.PageIndex = 1
        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
          }
        })
      },
      // 获取地址簿
      getAddressBook(type) {
        this.bookType = type
        this.innerVisible = true
        getAddress({
          page: this.Pagination.PageIndex,
          pageSize: this.Pagination.PageSize,
          name: this.bookInput,
          addressType: this.bookType,
          dataType: this.tabPosition,
        }).then(res => {
          if (res.code == 200) {
            this.bookTableData = res.data.list
            this.bookTotal = 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('表单信息不完整，请继续填写完整');
        }
        // console.log(this.ruleForm,86)
        // console.log(this.senderForm, this.recipientsForm, 665)
      },
      // 修改任务时间
      missionTime() {
        this.innerVisibleTime = true
        this.getTask()
      },
      // 编辑物流时间
      logisticsTime() {
        this.logisticsVisibleTime = true
        this.getlogisticsTimeList()
      },
      getlogisticsTimeList() {
        getLogisticsWaybill({
          waybillNo: this.waybillNo,
        }).then((res) => {
          if (res.code == 200) {
            var arrList = []
            if (res.data.list) {
              arrList = res.data.list
            }
            if (arrList.length > 0) {
              arrList.forEach(async (item) => {
                item.content = ''
                let arr = this.statusList.filter((i) => {
                  return item.status == i.value;
                });
                let yonTitle = ''
                let phone = ''
                if (item.car.id && item.user) {
                  yonTitle = item.car.carNo
                  phone = item.user.phone
                } else if (item.warehouse.id && item.user) {
                  yonTitle = item.warehouse.name
                  phone = item.user.phone
                } else if (item.coolerBox.id && item.user) {
                  yonTitle = item.coolerBox.name
                  phone = item.user.phone
                }
                let travelType = ''
                if (arr[0].label) {
                  travelType = arr[0].label
                }
                item.content = item.address + '【' + yonTitle + '】' + phone + '  ' + '您的货物' + travelType
              })
              // this.activitiesList = arrList
              this.activitiesList = arrList.reverse()
              this.activitiesList[this.activitiesList.length - 1].field = 'primary'
            }
            this.$forceUpdate()
          }
        })
      },
      // 获取运单列表
      async getTask() {
        getWaybillTask({
          waybillNo: this.waybillNo,
        }).then(res => {
          if (res.code == 200) {
            let arrlist = res.data.list
            let arrData = []
            arrlist.forEach(item => {
              let arril = {
                id: null,
                title: '',
                startTime: '',
                endTime: '',
              }
              if (item.car.id) {
                arril.title = item.car.carNo
              } else if (item.warehouse.id) {
                arril.title = item.warehouse.name
              } else if (item.coolerBox.id) {
                arril.title = item.coolerBox.name
              }
              arril.id = item.id
              arril.startTime = item.startTime
              arril.endTime = item.endTime
              this.timeRuleForm.date1 = item.startTime
              this.timeRuleForm.date2 = item.endTime
              arrData.push(arril)
            })
            this.humitureList = arrData
          }
        })
      },
      // 修改运单任务时间
      taskTime() {
        this.$refs['timeRuleForm'].validate((valid) => {
          if (valid) {
            let arr = JSON.parse(JSON.stringify(this.humitureList))
            arr.forEach(item => {
              delete item.title
            })
            this.timeLoading = true
            putWaybillTask({
              waybillTaskList: arr,
            }).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: res.msg,
                  type: 'success'
                });
              }
              this.innerVisibleTime = false
              this.timeLoading = false
            }).catch(() => {
              this.timeLoading = false
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 修改物流时间
      logisticsTaskTime() {
        const arr = []
        this.activitiesList.forEach(item => {
          let timeArr = {
            id: item.id,
            time: item.createdAt,
          }
          arr.push(timeArr)
        })
        this.timeLoading = true
        putWaybillLogistics({
          waybillLogistics: arr,
        }).then(res => {
          if (res.code == 200) {
            this.$message({
              message: res.msg,
              type: 'success'
            });
            this.logisticsVisibleTime = false
          }
          this.timeLoading = false
        }).catch(() => {
          this.timeLoading = false
        })
      },
      // 选择开始结束时间
      timeChange(value) {
        this.timeRuleForm.date1 = value
      },
      // 选择开始结束时间
      timeChangeil(value) {
        this.timeRuleForm.date2 = value
      },
      // 添加寄件人
      getSender(value) {
        return new Promise((resolve, reject) => {
          var params = {
            addressType: 'sender',
            ...value
          }
          params.provinceId = value.regionCode[0]
          params.cityId = value.regionCode[1]
          params.regionId = value.regionCode[2]
          const regionArr = value.region.split('/')
          params.provinceName = regionArr[0]
          params.cityName = regionArr[1]
          params.regionName = regionArr[2]
          delete params.regionCode
          delete params.region
          addAddress(params).then(res => {
            if (res.code == 200) {
              const orderID = res.data
              resolve(orderID);
            }
          }).catch((error) => {
            reject(error)
          })
        });
      },
      // 添加收件人
      getRecipients(value) {
        return new Promise((resolve, reject) => {
          var params = {
            addressType: 'consignee',
            ...value
          }
          params.provinceId = value.regionCode[0]
          params.cityId = value.regionCode[1]
          params.regionId = value.regionCode[2]
          const regionArr = value.region.split('/')
          params.provinceName = regionArr[0]
          params.cityName = regionArr[1]
          params.regionName = regionArr[2]
          delete params.regionCode
          delete params.region
          addAddress(params).then(res => {
            if (res.code == 200) {
              const orderID = res.data
              resolve(orderID);
            }
          }).catch((error) => {
            reject(error)
          })
        });
      },
      // 选择table其中某一项
      cellClick(row) {
        this.innerVisible = false
        const param = {
          ...row
        }
        const arrAddress = []
        if (param.provinceId) {
          arrAddress.push(param.provinceId)
        }
        if (param.provinceId) {
          arrAddress.push(param.cityId)
        }
        if (param.provinceId) {
          arrAddress.push(param.regionId)
        }
        param.regionCode = arrAddress
        param.region = this.getCodeToText(param.regionCode)
        delete param.createBy
        delete param.createdAt
        delete param.deptId
        delete param.isDefault
        delete param.updateBy
        delete param.updatedAt
        if (this.bookType == 'sender') {
          this.senderForm = param
          this.$nextTick(() => {
            this.$refs['sender'].validateForm();
          })
        } else {
          this.recipientsForm = param
          this.$nextTick(() => {
            this.$refs['recipients'].validateForm();
          })
        }
      },
      buttonData(row, type) {
        this.operationType = type
        this.orderId = row.id
        if (type == 'logs') {
          this.$refs.order.staffDialogVisible = true
          this.waybillData = row
          this.waybillData.nickName = row.printUser.nickName
        } else if (type == 'edit') {
          this.waybillNo = row.waybillNo
          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 == 'send') {
          this.sendDialogVisible = true
          this.getUserList(2)
        } else if (type == 'del') {
          this.deleteUser(row.id)
        } else if (type == 'pdf') {
          this.pdfDialogVisible = true
          this.waybillNo = row.waybillNo
          // this.downloadPdf(row)
        } else if (type == 'print') {
          this.printWaybillVisible = true
          this.printData.push(row.waybillNo)
        }
      },
      // 批量打印运单
      async definitePrint() {
        this.definitFlag = true
        try {
          let resulr = []
          for (let i = 0; i < this.printData.length; i++) {
            let urlimg = await this.waybillPdf(this.printData[i])
            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.definitFlag = false
          this.printWaybillVisible = false
        } catch (error) {
          this.definitFlag = false
          throw new Error('请求错误，终止请求');
        }
      },
      // 下载运单pdf
      waybillPdf(value) {
        return new Promise((resolve) => {
          getWaybillPdf({
            waybillNo: value,
          }).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);
              }
            } else {
              this.$message.error('未获取到文件名');
            }
          })
        });
      },
      // 下载pdf
      downloadPdf(value) {
        this.pdfFlag = true
        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('未获取到文件名');
          }
          this.pdfFlag = false
        }).catch(() => {
          this.pdfFlag = false
        })
      },
      // 获取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);
              }
            }
          })
        });
      },
      // 订单派单
      sendHandleAdd() {
        let flag = this.$refs['sendRules'].validateForm();
        if (flag) {
          this.sendConfirmLoading = true
          let arrID = []
          if (this.operationType == 'send') {
            arrID.push(this.orderId)
          } else if (this.operationType == 'sends') {
            arrID = this.waybillIdList
          }
          const param = {
            waybillIds: arrID,
            type: Number(this.sendRuleForm.type),
            printUserId: Number(this.sendRuleForm.printUserId),
            coolerBoxId: Number(this.sendRuleForm.coolerBoxId),
          }
          waybillDelivery(param).then(res => {
            if (res.code == 200) {
              this.$message({
                message: res.msg,
                type: 'success'
              });
              this.getList()
            }
            this.sendDialogVisible = false
            this.sendConfirmLoading = false
          }).catch(() => {
            this.sendConfirmLoading = false
          })
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      // 删除用户
      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(() => {});
      },
      // 单选选择
      radioInput(type) {
        this.sendOrdersId = type
        this.resetSelect()
        this.getUserList(type)
      },
      // 重置选择员工
      resetSelect() {
        this.sendRuleList.forEach(item => {
          if (item.type == 'searchSelect') {
            item.options = []
          } else if (item.type == 'searchSelect1') {
            item.options = []
          }
        })
        this.staffName = ''
        this.sendRuleForm.printUserId = null
        this.sendRuleForm.coolerBoxId = null
      },
      // 搜索
      remoteMethod(value) {
        this.resetSelect()
        this.staffName = value
        this.getUserList(this.sendOrdersId)
      },
      // 获取用户列表
      getUserList(type) {
        let params = {
          page: 1,
          pageSize: 100,
          name: this.staffName,
          isBind: true,
        }
        let arrList = []
        if (type == 2) {
          getWarehouse(params).then(res => {
            if (res.code == 200) {
              const arr = res.data.list
              arr.forEach((item, index) => {
                const commodity = {
                  label: '【' + item.name + '】' + item.user.nickName,
                  value: item.user.id,
                }
                arrList.push(commodity)
              })
            }
          })
        } else if (type == 3) {
          getCar(params).then(res => {
            if (res.code == 200) {
              const arr = res.data.list
              arr.forEach((item, index) => {
                const commodity = {
                  label: '【' + item.carNo + '】' + item.user.nickName,
                  value: item.user.id,
                }
                arrList.push(commodity)
              })
            }
          })
        } else if (type == 4) {
          getCoolerBox(params).then(res => {
            if (res.code == 200) {
              const arr = res.data.list
              let arrData = []
              arr.forEach((item, index) => {
                const commodity = {
                  label: item.name,
                  value: item.id,
                }
                arrData.push(commodity)
              })
              this.optionMatching(arrData, 'coolerBoxId')
            }
          })
          getUser(params).then(res => {
            if (res.code == 200) {
              const arr = res.data.list
              arr.forEach((item, index) => {
                const commodity = {
                  label: item.nickName,
                  value: item.id,
                }
                arrList.push(commodity)
              })
            }
          })
        }
        this.optionMatching(arrList, 'printUserId')
      },
      // 选项赋值
      optionMatching(value, field) {
        this.sendRuleList.forEach((item, index) => {
          if (item.field == field) {
            item.options = value
          }
        })
      },
      openModel(type) {
        // console.log(this.$refs.refWaybill.selectionList,333)
        this.operationType = type
        if (type == 'add') {
          this.tableBook()
          this.staffTitle = '添加运单'
          this.staffDialogVisible = true
        } else if (type == 'sends') {
          const arrID = this.$refs.refWaybill.waybillIds
          if (arrID.length != 0) {
            let arr2 = []
            arrID.forEach(item => {
              if (item.status == 1 || item.status == 2 || item.status == 3) {
                arr2.push(item.id)
              }
            })
            this.waybillIdList = arr2
            if (arr2.length > 0) {
              this.sendDialogVisible = true
              this.getUserList(2)
            } else {
              this.$message({
                message: '请选择未派单的运单',
                type: 'warning'
              });
            }
          } else {
            this.$message({
              message: '请先选择需要批量操作的运单',
              type: 'warning'
            });
          }
          // console.log(type, arrID, '批量派单')
        } 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'
            });
          }
        } else if (type == 'printWaybill') {
          const arrID = this.$refs.refWaybill.waybillIds
          if (arrID.length != 0) {
            let arr3 = []
            arrID.forEach(item => {
              if (item.status == 2 || item.status == 3 || item.status == 9) {
                arr3.push(item.waybillNo)
              }
            })
            this.printData = arr3
            if (arr3.length > 0) {
              this.printWaybillVisible = true
            } else {
              this.$message({
                message: '请选择需要打印的运单',
                type: 'warning'
              });
            }
          } else {
            this.$message({
              message: '请先选择需要批量打印的运单',
              type: 'warning'
            });
          }
        }
      },
      // 导入
      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 arrList = response.fileName.split('.')
          let fixedStr = decodeURIComponent(arrList[0]);
          let filename = fixedStr + '.' + arrList[1]
          // this.blobDownload(response, filename)
          this.blobDownload(response.data, filename)
          this.downloadFlag = false
        }).catch(() => {
          this.downloadFlag = false
        })
      },
      // 批量打印
      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) {
          this.peintFlag = false
          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]))
        })
      },
      // 上传文件
      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;
        anchor.click();
        window.URL.revokeObjectURL(data);
      },
      // tab选择
      handleClick(tab) {
        this.tableBook()
        this.getAddressBook(this.bookType)
      },
      // tab不同table列表
      tableBook() {
        this.bookTableList = []
        const arr = addressBook()
        if (this.tabPosition == 'my') {
          this.bookTableList = arr
          this.bookTableList.push(this.bookList)
        } else {
          this.bookTableList = arr
        }
      },
      getCodeToText(codeArray) {
        let area = "";
        switch (codeArray.length) {
          case 1:
            area += CodeToText[codeArray[0]];
            break;
          case 2:
            area += CodeToText[codeArray[0]] + "/" + CodeToText[codeArray[1]];
            break;
          case 3:
            area +=
              CodeToText[codeArray[0]] +
              "/" +
              CodeToText[codeArray[1]] +
              "/" +
              CodeToText[codeArray[2]];
            break;
          default:
            break;
        }
        return area
      },
      changeSize(val) {
        this.Pagination.PageSize = val
        this.getList()
      },
      changeCurrent(val) {
        this.Pagination.PageIndex = val
        this.getList()
      },
      bookChangeSize(val) {
        this.bookPagination.PageSize = val
        this.getList()
      },
      bookChangeCurrent(val) {
        this.bookPagination.PageIndex = val
        this.getList()
      },
      // 清空表单
      closeDialog() {
        this.$refs.sendRules.resetCheck();
      },
      // 关闭清空表单
      closePopup() {
        this.$refs.sender.resetForm()
        this.$refs.recipients.resetForm()
        this.$refs.childRules.resetCheck()
      },
      closePopup1() {
        this.humitureList = []
      },
      closePopup2() {
        this.activitiesList = []
      },
      printClose() {
        this.printData = []
      }
    }
  }
</script>

<style lang="scss" scoped>
  .waybill_home ::v-deep .el-dialog__body {
    padding: 0px 20px 30px 20px;
  }

  .waybil_form ::v-deep .el-cascader {
    width: 100% !important;
  }

  .card_waybill {
    display: flex;
    border-bottom: 1px solid #E4E7ED;
  }

  .waybill_item {
    width: 50%;
  }

  .card_book_list {
    border: 1px solid #DCDFE6;
  }

  .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;
    }
  }

  .card_printWay {
    display: flex;

    span {
      font-size: 15px;
      font-weight: bold;
    }
  }

  .card_time_waybilltask {
    display: flex;
    align-items: center;
    margin: 10px 0px;
  }

  .flex1_time_title {
    width: 170px;
    flex: none;
  }

  .flex1_time {
    font-size: 16px;
    flex: 1;
    padding: 0px 10px;
  }
</style>
