<template>
  <el-dialog
    title="波次详情"
    :close-on-click-modal="false"
    :visible.sync="visible"
    v-if="visible"
    :fullscreen="true"
    @close="dialogClose">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" class="search-form" ref="searchForm" :model="searchForm" label-width="auto" size="small">
        <div class="input-row">
          <el-form-item label="订单编号" class="search-form-item">
            <el-input v-model="searchForm.orderNumber" placeholder="请输入订单编号" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="收件人" class="search-form-item">
            <el-input type="text" v-model="searchForm.receiverName" placeholder="请输入收件人" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="运单号" class="search-form-item">
            <el-input type="text" v-model="searchForm.deliveryNo" placeholder="请输入运单号" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="PDF生成状态" class="search-form-item">
            <el-select type="text" v-model="searchForm.workStatus" placeholder="请选择PDF生成状态" :clearable="true">
              <el-option label="未生成" value="0"></el-option>
              <el-option label="已生成" value="2"></el-option>
              <el-option label="失败" value="11"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <div class="default-btn primary-btn" @click="searchChange(true)">{{$t('crud.searchBtn')}}</div>
            <div class="default-btn" @click="resetSearchForm()">{{$t('shop.resetMap')}}</div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="mod-order-order">
      <div class="main">
        <div class="content">
          <div style="margin-bottom: 20px">
            <div style="margin: 0px 20px 20px 0">
              <span>波次号</span><span style="margin-left: 30px; font-weight: bold;font-size: 20px;color: red">{{wave.waveNo}}</span>
              <span style="margin-left: 100px">订单数量</span><span style="margin-left: 20px; font-weight: bold;font-size: 20px;color: red">{{wave.orderNum}}</span>
              <span v-if="wave.printChannel === 'KuaiYin'" style="margin-left: 100px">总张数</span>
              <span v-if="wave.printChannel === 'WoNiu'" style="margin-left: 100px">总张数(含识别页)</span>
              <span v-if="wave.printChannel === 'KuaiYin'" style="margin-left: 20px; font-weight: bold;font-size: 20px;color: red">{{wave.sheets}}</span>
              <span v-if="wave.printChannel === 'WoNiu'" style="margin-left: 20px; font-weight: bold;font-size: 20px;color: red">{{wave.sheets + wave.orderNum}}</span>
              <span style="margin-left: 100px" v-if="wave.printChannel === 'KuaiYin'">消耗纸张(按72张大纸)约</span><span v-if="wave.printChannel === 'KuaiYin'" style="margin-left: 20px; font-weight: bold;font-size: 20px;color: red">
              {{((wave.sheets + wave.sheets / 10) / 72).toFixed(2) }}</span>
              <span style="margin-left: 100px" v-if="wave.printChannel === 'WoNiu'">消耗纸张(按64张大纸)约</span><span v-if="wave.printChannel === 'WoNiu'" style="margin-left: 20px; font-weight: bold;font-size: 20px;color: red">
              {{((wave.sheets + wave.orderNum) / 64).toFixed(2) }}</span>
              <span style="margin-left: 100px">生成时间</span><span style="margin-left: 30px">{{wave.createTime}}</span>
              <span style="margin-left: 100px" >更新时间</span>
              <span style="margin-left: 30px" v-if="!wave.updateTime">-</span>
              <span style="margin-left: 30px" v-if="wave.updateTime">{{wave.updateTime}}</span>
            </div>
            <el-button size="small" @click="generatePdfCombinationBatch" :disabled="wave.productionStatus == 0" :loading="wavePrintOrderPdfDownloadLoading">批量生成PDF</el-button>
            <el-button size="small" v-if="wave.printChannel === 'WoNiu'" @click="downloadPdfBatch" :disabled="wave.productionStatus == 0" :loading="wavePrintOrderPdfDownloadLoading">批量下载ZIP</el-button>
            <el-button size="small" v-if="wave.printChannel === 'Lightning'" @click="downloadPdfBatch" :disabled="wave.productionStatus == 0" :loading="wavePrintOrderPdfDownloadLoading">批量下载ZIP</el-button>
            <el-button size="small" v-if="wave.printChannel === 'KuaiYin'"@click="mergeAndDownloadPDF" :disabled="wave.productionStatus == 0" :loading="wavePrintOrderPdfDownloadLoading">合并PDF并下载</el-button>
<!--            <el-button size="small" @click="downloadPrintOrderPdfZip" :disabled="wave.productionStatus == 0" :loading="wavePrintOrderPdfDownloadLoading">批量下载PDF</el-button>-->
            <el-button v-if="shopId != 66" size="small" :loading="wavePrintOrderInfoDownloadLoading" @click="downloadWavePrintOrderInfo" :disabled="wave.productionStatus == 0">下载订单信息</el-button>
            <el-button size="small"  @click="openScanDialog" :disabled="wave.productionStatus == 0">扫描发货</el-button>
            <el-button size="small" @click="onKeyDelivery" v-if="wave.productionStatus === 1 && shopId != 66" :loading="onKeyDeliveryLoading">一键发货</el-button>
            <el-divider direction="vertical" content-position="center"/>
            <el-button size="small" @click="productionLockConfirm" v-if="wave.productionStatus === 0">生产锁定</el-button>
            <el-button size="small" @click="productionLockCancel" v-if="wave.productionStatus === 1">取消锁定</el-button>
            <el-button size="small" v-if="shopId != 66" @click.stop="getUpload()" :disabled="wave.expressBillStatus === 1 || wave.productionStatus === 0">导入运单号</el-button>
            <el-divider direction="vertical" content-position="center"/>
            <el-button type="text" v-if="shopId != 66" @click="deleteWave" :disabled="wave.expressBillStatus == 1 || wave.productionStatus == 1 || wave.scanStatus == 1">删除波次</el-button>
            <el-button type="text" icon="el-icon-refresh-left" @click="getDataList(page, null, false)" >刷新</el-button>
          </div>
          <!-- 表格 -->
          <div class="table-con transport-table">
            <el-table
              border
              ref="transportTable"
              :data="dataList"
              header-cell-class-name="table-header"
              row-class-name="table-row-low"
              @selection-change="selectionChangeHandle"
              @expand-change="handleTableExpandChange"
              style="width: 100%">
              <!--<el-table-column type="expand">
                <template slot-scope="props">
                  <el-form label-position="left">
                    <el-form-item label="收件地址">
                      <span class="expand-detail">{{ props.row.userAddrOrder.province }} </span>
                      <span class="expand-detail">{{ props.row.userAddrOrder.city }} </span>
                      <span class="expand-detail">{{ props.row.userAddrOrder.area }} </span>
                      <span class="expand-detail">{{ props.row.userAddrOrder.addr }} </span>
                      <span class="expand-detail">{{ props.row.userAddrOrder.receiverName }} </span>
                      <span class="expand-detail">{{ props.row.userAddrOrder.receiverMobile }} </span>
                    </el-form-item>
                  </el-form>
                </template>
              </el-table-column>-->
<!--              <el-table-column-->
<!--                type="selection">-->
<!--              </el-table-column>-->
              <el-table-column
                align="center"
                prop="serialNo"
                width="65"
                label="序号">
                <template slot-scope="scope">
                  <span class="table-cell-text">{{ scope.row.serialNo }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="订单号"
                width="180"
                align="center"
                prop="orderNumber">
                <template slot-scope="scope">
                  <span>{{scope.row.orderNumber }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="第三方单号"
                width="100"
                align="center"
                prop="orderNo">
                <template slot-scope="scope">
                  <span>{{scope.row.orderNo }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="下单时间"
                align="center"
                prop="orderTime">
                <template slot-scope="scope">
                  <span>{{scope.row.orderTime }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="收件人"
                align="center"
                prop="receiverName">
                <template slot-scope="scope">
                  <div>
                    <el-tooltip placement="top">
                      <div slot="content" style="font-size: 8px">
                        <span>{{scope.row.userAddrOrder.province }}</span>
                        <span>{{scope.row.userAddrOrder.city }}</span>
                        <span>{{scope.row.userAddrOrder.area }}</span>
                        <span>{{scope.row.userAddrOrder.street }}</span>
                        <span>{{scope.row.userAddrOrder.addr }}</span>
                      </div>
                      <div>
                        <span>{{scope.row.userAddrOrder.receiver }}</span>
                        <br/>
                        <span>{{scope.row.userAddrOrder.mobile }}</span>
                      </div>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="产品名"
                width="300"
                align="center"
                prop="prodName">
                <template slot-scope="scope">
                  <span>{{scope.row.prodName }}</span>
                  <!--<el-tooltip placement="top">
                    <div
                      slot="content"
                      style="font-size: 8px"
                      v-for="orderItem in scope.row.orderItemList"
                      :key="orderItem.orderItemId">
                      <div>{{orderItem.prodName}}</div>
                    </div>
                    <span v-if="scope.row.orderItemList.length > 1">{{scope.row.orderItemList[0].prodName}} <br/>......</span>
                    <span v-else>{{scope.row.orderItemList[0].prodName}}</span>
                  </el-tooltip>-->
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="prodNums"
                width="65"
                label="数量">
                <template slot-scope="scope">
                  <span>{{scope.row.prodNums }}</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="isMerge"
                width="65"
                label="合单">
                <template slot-scope="scope">
                  <el-tag type="info" effect="dark" v-if="scope.row.isMerge == 1">否</el-tag>
                  <el-tag type="danger" effect="dark" v-if="scope.row.isMerge == 2">是</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="deliveryName"
                width="110"
                label="快递">
                <template slot-scope="scope">
                  <span>{{scope.row.deliveryName }}</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="快递单号"
                prop="deliveryNo">
                <template slot-scope="scope">
                  <span>{{scope.row.deliveryNo }}</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="expressBillTime"
                label="运单号时间">
                <template slot-scope="scope">
                  <span>{{scope.row.expressBillTime }}</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="scanTime"
                label="发货时间">
                <template slot-scope="scope">
                  <span>{{scope.row.deliveryTime }}</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="status"
                width="90"
                label="状态">
                <template slot-scope="scope">
                  <span v-if="scope.row.status == 1">待打印</span>
                  <span v-if="scope.row.status == 2">待发货</span>
                  <span v-if="scope.row.status == 3">已发货</span>
                  <span v-if="scope.row.status == 11">已取消</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="workStatus"
                width="80"
                label="生成状态">
                <template slot-scope="scope">
                  <el-tooltip placement="top" v-if="scope.row.remark">
                    <div slot="content" style="font-size: 8px" >
                      <span>{{scope.row.remark }}</span>
                    </div>
                    <div>
                      <el-tag type="success" v-if="scope.row.workStatus == 2" effect="dark">已生成</el-tag>
                      <el-tag type="info" v-if="scope.row.workStatus == 0" effect="dark">未生成</el-tag>
                      <el-tag type="danger" v-if="scope.row.workStatus == 3" effect="dark">失败</el-tag>
                    </div>
                  </el-tooltip>
                  <div v-else>
                    <el-tag type="success" v-if="scope.row.workStatus == 2" effect="dark">已生成</el-tag>
                    <el-tag type="info" v-if="scope.row.workStatus == 0" effect="dark">未生成</el-tag>
                    <el-tag type="danger" v-if="scope.row.workStatus == 3" effect="dark">失败</el-tag>
                  </div>
                </template>
              </el-table-column>
              <!--<el-table-column
                align="center"
                prop="status"
                width="90"
                label="pdf次数">
                <template slot-scope="scope">
                  <span>{{scope.row.pdfDownloadTimes}}</span>
                </template>
              </el-table-column>-->
              <el-table-column
                align="center"
                :label="$t('crud.menu')"
                width="300"
              >
                <template slot-scope="scope">
                  <div style="display: inline-block;float: left;">
                    <el-button v-if="scope.row.workStatus === 0 || scope.row.workStatus == 3" size="mini" @click="generatePdfCombination(scope.row)" :disabled="wave.productionStatus == 0">生成PDF</el-button>
                    <el-button size="mini" @click="openModifyExpressBillDialog(scope.row)">修改运单号</el-button>
                    <el-button key="removeFromWaveBtn" size="mini" type="text" v-if="wave.productionStatus == 0 || scope.row.status != 3" :disabled="wave.productionStatus == 1" @click="removeFromWave(scope.row)">移出波次</el-button>
                    <el-button size="mini" type="text" v-if="scope.row.status == 3" @click="cancelDelivery(scope.row)">取消发货</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分页 -->
          <el-pagination
            v-if="dataList.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.currentPage"
            :page-sizes="[61, 200, 400, 600]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total">
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog
      :append-to-body="true"
      title="修改运单号"
      :visible.sync="modifyExpressBillVisible"
      width="30%"
      left
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="wave" label-position="right">
        <el-form-item label="">
          <span autocomplete="off">订单号：{{printOrder.orderNumber}}</span>
          <span autocomplete="off" style="margin-left: 30px">旧运单号：{{printOrder.oldDeliveryNo}}</span>
        </el-form-item>
        <el-form-item label="快递公司" label-width="70px">
          <el-input v-model="printOrder.deliveryName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="公司代号" label-width="70px">
          <el-input v-model="printOrder.deliveryCode" autocomplete="off" placeholder="比如中通：zto"></el-input>
        </el-form-item>
        <el-form-item label="新运单号" label-width="70px">
          <el-input v-model="printOrder.deliveryNo" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="modifyExpressBill(wave.waveId, printOrder)">确认</el-button>
      </div>
    </el-dialog>
    <order-scan-delivery ref="orderScanDelivery" @refreshDataList="getDataList(page, null, false)"></order-scan-delivery>
    <express-bill-upload
      v-if="uploadVisible"
      ref="expressBillUpload"
      @refreshDataList="getWaitingConsignmentExcel">
    </express-bill-upload>
  </el-dialog>

</template>

<script>
  import {PDFDocument}  from 'pdf-lib';
  import ProdPic from '@/components/prod-pic';
  import InputNumberRange from '@/components/input-number-range';
  import ExpressBillUpload from './express-bill-upload';
  import OrderScanDelivery from '@/components/order-scan-delivery';
  import moment from 'moment';
  import {downloadPdf} from "@/utils/pdf";
  import {downloadXls} from "@/utils/excel";
  import {downloadZip} from "@/utils/zip";
  import { saveAs } from 'file-saver';
  import JSzip from 'jszip';
  import axios from 'axios'

  export default {
    data () {
      return {
        // 是否全选
        selectAll: false,
        showHeadScroll: false, // 修改物流相关
        logVisible: false,
        radio: '1',
        logisticsInfo: [],  // 包裹列表
        logDataForm: {
          dvyId: '', // 当前物流公司id
          dvyFlowId: '',  // 物流单号
          dvyNames: []  // 物流公司列表
        },
        shopId: this.$store.state.user.shopId,
        searchForm: {},
        uploadVisible: false,
        lang: localStorage.getItem('lang'),
        errorNum: 0,
        // 确认修改弹窗
        isReviseLog: true,  // 是否正在修改物流信息
        confirmList: [],  // 确认修改信息
        dataForm: {},
        sts: 0,
        dateRange: [],
        productNumsRange:[],
        status: null,
        options: [
          {
          value: 1,
          label: "待打印"
          },
          {
            value: 2,
            label: "待发货"
          },
          {
            value: 3,
            label: "待收货"
          },
          {
            value: 4,
            label: "交易完成"
          }
          ],
        refund: [
          {
          value: 0,
          label: this.$i18n.t('order.noAfterSales')},
          {
            value: 1,
            label: this.$i18n.t('order.requestARefund')
          },
          {
            value: 2,
            label: this.$i18n.t('order.refundsuccessfully')
          },
          {
            value: 3,
            label: this.$i18n.t('order.partialRefundSucc')
          },
          {
            value: 4,
            label: this.$i18n.t('order.refundFailed')
          }],
        resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
        dataList: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 61 // 每页显示多少条
        },
        dataListLoading: false,
        dataListSelections: new Set(),
        generateWaveDialogVisible: false,
        timeActive: null,
        priceWidth: '109px',
        infoWidth: '400px',
        newWaveNo: null,
        visible: false,
        wave:{},
        printChannel: "WoNiu",
        addToWaveDialogVisible: false,
        wavePrintOrderInfoDownloadLoading:false,
        onKeyDeliveryLoading: false,
        operDisabled: false,
        productionLockDisabled: false,
        wavePrintOrderPdfDownloadLoading: false,
        modifyExpressBillVisible: false,
        printOrder:{},
        expandRowDetail:{}
      }
    },
    components: {
      ProdPic,
      InputNumberRange,
      ExpressBillUpload,
      OrderScanDelivery
    },
    computed: {

    },
    created () {

      // 请求物流公司
      // this.getLogisticsList()
    },
    activated () {
      // 携带参数查询
      var query = this.$route.query
      if (Object.keys(query).length > 0) {
        this.getDataList(this.page, query)
      }
    },
    mounted () {
      // 监听页面滚动
      // window.addEventListener('scroll', this.scrollToTop)
    },
    watch: {

    },
    methods: {
      onKeyDelivery(){
        this.$confirm('确定要一键发货吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.onKeyDeliveryLoading = true;
          this.$http({
            url: this.$http.adornUrl(`/printOrder/printOrder/onKeyDelivery`),
            method: 'POST',
            data: this.$http.adornData(this.wave)
          }).then(({data}) => {
            this.onKeyDeliveryLoading = false;
            this.$message({
              message: "发货成功",
              type: 'success'
            })
            this.getDataList(this.page, null, true)
          }).catch((e) => {
            this.onKeyDeliveryLoading = false;
            this.$message({
              message: "发货失败",
              type: 'error'
            })
          })
        });

      },
      openAndQueryPrintOrder(params){
        this.visible = true;
        this.$nextTick(() =>{
          this.getWave(params.waveId);
          this.searchForm.orderNumber = params.orderNumber;
          this.getDataList(this.page, false, null);
        })

      },
      init (wave) {
        this.wave = wave;
        this.visible = true;
        this.getWave(this.wave.waveId);
        // 携带参数查询
        this.getDataList(this.page, null, true)
      },
      getWave(waveId){
        // 修改
        this.$http({
          url: this.$http.adornUrl(`/wave/wave/findWave/${waveId}`),
          method: 'GET',
          params: this.$http.adornParams()
        }).then(({ data }) => {
          this.wave = data
        })
      },
      deleteWave(){
        this.$confirm('确定要删除波次吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl(`/wave/wave/deleteWave`),
            method: 'POST',
            data: this.$http.adornData(this.wave)
          }).then(({data}) => {
            if(data){
              this.$message({
                message: "删除成功",
                type: 'success'
              })
              this.$emit('refressWaveList', null);
              this.dialogClose();
            }else{
              this.$message({
                message: "删除失败",
                type: 'error'
              })
            }
          })
        })
      },
      openGenerateWaveDialog(){
        if(this.dataListSelections.size == 0){
          this.$message.error("请至少选择一个订单");
          return ;
        }
        this.$http({
          url: this.$http.adornUrl(`/wave/wave/getLatestWaveNo`),
          method: 'GET',
          params: this.$http.adornParams({printChannel:this.printChannel})
        }).then(({data}) => {
          if(data.status == "success"){
            this.generateWaveDialogVisible = true;
            this.wave.waveNo = data.result;
            this.wave.orderNum = data
          }
        })
      },
      openAddToWaveDialog(){
        if(this.dataListSelections.size == 0){
          this.$message.error("请至少选择一个订单");
          return ;
        }
        this.$http({
          url: this.$http.adornUrl(`/wave/wave/getLatestWave`),
          method: 'GET',
          params: this.$http.adornParams({printChannel:this.printChannel, queryLimit: 30})
        }).then(({data}) => {
          if(data.status == "success"){
            this.addToWaveDialogVisible = true;
            this.wave.latestWaveList = data.result;
          }
        })
      },
      openScanDialog(){
        this.$refs.orderScanDelivery.init(this.wave);
      },
      handleWaveChange(val){
        this.wave.latestWaveList.forEach(item =>{
          if(item.waveId == val){
            this.wave.orderNum = item.orderNum;
            return;
          }
        })
      },
      handleAddToWaveDialogClose(){
        this.wave.selectWaveId = null;
        this.wave.orderNum = 0;
      },
      handleScanDialogClose(){
        this.theData = null;
        this.dataList = [];
        this.scanOrderNumber = null;
        this.waitScan = {};
        this.matchPrintOrder = {};
      },
      createWave(){
        let dataBody = {waveName: this.wave.waveName, "orderNumberList": [...this.dataListSelections], "printChannel": this.printChannel};
        this.$http({
          url: this.$http.adornUrl(`/wave/wave/create`),
          method: 'POST',
          data: this.$http.adornData(dataBody)
        }).then(({data}) => {
          if(data.status == "success"){
            this.generateWaveDialogVisible = false;
            this.$message({
              message: data.msg,
              type: 'success'
            })
            this.getDataList(this.page);
          }else{
            this.$message({
              message: data.msg,
              type: 'error'
            })
          }
        })
      },
      handleTableExpandChange(row){
        // this.expandRowDetail = {};
        // 修改
        this.$http({
          url: this.$http.adornUrl(`/printOrder/printOrder/findWavePrintOrderAddr`),
          method: 'GET',
          params: this.$http.adornParams({waveId: row.waveId, orderNumber: row.orderNumber})
        }).then(({ data }) => {
          // this.expandRowDetail = data;
        })
      },
      removeFromWave(row){
        this.$confirm('确定要移出波次吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl(`/wave/wave/removeFromWave`),
            method: 'POST',
            data: this.$http.adornData(row)
          }).then(({data}) => {
            if(data.status == "success"){
              this.$message({
                message: data.msg,
                type: 'success'
              })
              this.getWave(this.wave.waveId);
              this.getDataList(this.page);
            }else{
              this.$message({
                message: data.msg,
                type: 'error'
              })
            }
          })
        });
      },
      //批量下载订单信息
      downloadWavePrintOrderInfo(){
        this.wavePrintOrderInfoDownloadLoading = true;
        this.$http({
          url: this.$http.adornUrl('/wave/wave/downloadWavePrintOrderInfo'),
          method: 'get',
          params: this.$http.adornParams({waveId: this.wave.waveId, printChannel: this.printChannel }),
          responseType: 'blob'
        }).then(({data}) => {
          this.wavePrintOrderInfoDownloadLoading = false;
          let fileName = this.wave.waveNo + "_" + this.wave.waveName + "_订单信息";
          downloadXls(data, fileName + ".xlsx");
        }).catch((error) => {
          this.wavePrintOrderInfoDownloadLoading = false;
        })
      },
      generatePdfCombination(row){
        this.$http({
          url: this.$http.adornUrl('/printOrder/printOrder/generatePdfCombination'),
          method: 'post',
          data: this.$http.adornParams(row),
        }).then(({data}) => {
          this.$message({
            message: "开始生成PDF，请刷新等待结果",
            type: 'success'
          })
        }).catch((error) => {
          this.$message({
            message: "生成PDF失败",
            type: 'error'
          })
        })
      },
      generatePdfCombinationBatch(){
        // if(this.dataListSelections.size == 0){
        //   this.$message.error("请至少选择一个订单");
        //   return ;
        // }
        this.$confirm('确定要批量生成PDF吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.wavePrintOrderPdfDownloadLoading = true;
          // let orderNumberList = this.dataListSelections.map(item=>item['orderNumber'])
          // let dataBody = {"printChannel": this.printChannel, "waveId": this.wave.waveId, orderNumberList: orderNumberList};
          let dataBody = {"printChannel": this.printChannel, "waveId": this.wave.waveId};
          this.$http({
            url: this.$http.adornUrl('/printOrder/printOrder/generatePdfCombinationBatch'),
            method: 'post',
            data: this.$http.adornParams(dataBody),
          }).then(({data}) => {
            this.wavePrintOrderPdfDownloadLoading = false;
            this.$message({
              message: "批量生成PDF启动，请刷新等待结果",
              type: 'success'
            })
          }).catch((error) => {
            this.wavePrintOrderPdfDownloadLoading = false;
            this.$message({
              message: "批量生成PDF启动失败",
              type: 'error'
            })
          })
        });
      },
      downloadPrintOrderPdfZip(){
        this.wavePrintOrderPdfDownloadLoading = true;
        let orderNumberList = this.dataListSelections.map(item=>item['orderNumber'])
        let dataBody = {"printChannel": this.printChannel, "waveId": this.wave.waveId, orderNumberList: orderNumberList};
        this.$http({
          url: this.$http.adornUrl('/wave/wave/downloadWavePrintOrderPdf'),
          method: 'get',
          params: this.$http.adornParams(dataBody),
          responseType: 'blob'
        }).then(({data}) => {
          this.wavePrintOrderPdfDownloadLoading = false;
          let fileName = this.wave.waveNo + "_" + this.wave.waveName + ".zip";
          const blob = new Blob([data], {
            type: 'application/zip'
          })
          saveAs(blob, fileName)
        }).catch((error) => {
          this.wavePrintOrderPdfDownloadLoading = false;
        })
      },
      getPdfStream (url) {
        return new Promise((resolve, reject) => {
          let xmlhttp = new XMLHttpRequest();
          xmlhttp.open("GET", url, true);
          xmlhttp.responseType = "blob";
          xmlhttp.onload = function () {
            if (this.status == 200) {
              resolve(this.response);
            }else{
              reject(this.status);
            }
          }
          xmlhttp.send();
        });
      },
      getPdfFile (url) {
        return new Promise((resolve, reject) => {
          let xmlhttp = new XMLHttpRequest();
          xmlhttp.open("GET", url, true);
          xmlhttp.responseType = "blob";
          xmlhttp.onload = function () {
            if (this.status == 200) {
              resolve(this.response);
            }else{
              reject(this.status);
            }
          }
          xmlhttp.send();
        });
      },
      getPdfFile2 (url) {
        return new Promise((resolve, reject) => {
          try {
            let xmlhttp = new XMLHttpRequest();
            xmlhttp.open("GET", url, true);
            xmlhttp.responseType = "arraybuffer";
            xmlhttp.onload = function () {
              if (this.status == 200) {
                resolve(this.response);
              }else{
                reject(this.status);
              }
            }
            xmlhttp.send();
          } catch (ignored) {}
        });
      },
      downloadPdfBatch () {
        // if(this.dataListSelections.size == 0){
        //   this.$message.error("请至少选择一个订单");
        //   return ;
        // }
        this.wavePrintOrderPdfDownloadLoading = true;
        // 获取pdf链接集合
        // let orderNumberList = this.dataListSelections.map(item=>item['orderNumber'])
        this.$http({
          url: this.$http.adornUrl(`/printOrder/printOrder/getPrintPdfBatch`),
          method: 'POST',
          // data: this.$http.adornData({printChannel: this.wave.printChannel, waveId: this.wave.waveId, orderNumberList: orderNumberList})
          data: this.$http.adornData({printChannel: this.wave.printChannel, waveId: this.wave.waveId})
        }).then(({ data }) => {
          let printOrderList = data;
          // const arr = [{fileDownUrl:'地址', fileDownName:'文件名'}] // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径
          const zip = new JSzip()
          const cache = {}
          const promises = []
          printOrderList.forEach((printOrder, i) => {
            let pdfList = printOrder.pdfList;
            pdfList.forEach((pdf, j) => {
              let randomStr = Math.floor(Math.random()*100000).toString();
              const promise = this.getPdfFile(this.resourcesUrl + pdf.pdfUrl + "?a="+randomStr).then(data => {
                // 下载文件, 并存成blob对象
                const fileName = pdf.pdfFolderName + "/" + pdf.pdfName; // 获取文件名，一定要包含文件的后缀名(因为重复的文件名只会下载一个，故需要加入下标 不同名)
                // zip.folder(pdf.pdfFolderName).file(pdf.pdfName, data);
                zip.file(pdf.pdfName, data);
                cache[fileName] = data
              })
              promises.push(promise)
            });
          });
          Promise.all(promises).then(() => {
            zip.generateAsync({ type: "blob" }).then(content => {
              // 生成二进制流   然后保存文件（如果这个下载不了 也可以将下方这一行换成a标签下载逻辑）
              saveAs(content, this.wave.waveNo + "_" + this.wave.waveName + ".zip") // 利用file-saver保存文件  自定义文件名
              this.wavePrintOrderPdfDownloadLoading = false;
            })
          })
        });
      },

      /*//合并并下载PDF
      async mergeAndDownloadPDF(){ // urlList 单个PDF文件的URL
        try{
          this.wavePrintOrderPdfDownloadLoading = true;
          // 获取pdf链接集合
          this.getPrintPdfBatch().then(async (list)=>{
            let pdfUrlList = [];
            for(let i=0 ; i <list.length; i++){
              let pdfList = list[i].pdfList;
              for(let j=0 ; j <pdfList.length; j++){
                pdfUrlList.push(this.resourcesUrl + pdfList[j].pdfUrl);
              }
            }
            let promises = [];
            pdfUrlList.forEach(url =>{
              let promise = this.getPdfFile2(url);
              promises.push(promise);
            })
            let pdfBuffers = await Promise.all(promises);
            let newPdf = await PDFDocument.create();
            for (let k=0 ; k<pdfBuffers.length; k++) {
              let pdfDocument = await PDFDocument.load(pdfBuffers[k]);
              let contentPages = await newPdf.copyPages(pdfDocument, pdfDocument.getPageIndices());
              for (let l=0; l<contentPages.length; l++) {
                newPdf.addPage(contentPages[l]);
              }
            }
            let uint8Array = await newPdf.save();
            let mergeBuffer = Buffer.from(uint8Array);
            downloadPdf(mergeBuffer, this.wave.waveNo + "_" + this.wave.waveName + ".pdf");
            this.wavePrintOrderPdfDownloadLoading = false;
          });
        }catch (error) {
          this.wavePrintOrderPdfDownloadLoading = false;
        }

      },*/

      //合并并下载PDF
      async mergeAndDownloadPDF(){ // urlList 单个PDF文件的URL
        try{
          this.wavePrintOrderPdfDownloadLoading = true;
          // 获取pdf链接集合
          this.getPrintPdfBatch().then(async (list)=>{
            let newPdf = await PDFDocument.create();
            let pageWidth = 0;
            let pageHeight = 0;
            for(let i=0 ; i <list.length; i++){
              let pdfList = list[i].pdfList;
              for(let j=0 ; j <pdfList.length; j++){
                let randomStr = Math.floor(Math.random()*100000).toString();
                let pdfBuffer = await this.getPdfFile2(this.resourcesUrl + pdfList[j].pdfUrl+"?u="+randomStr);
                let pdfDocument = await PDFDocument.load(pdfBuffer);
                let contentPages = await newPdf.copyPages(pdfDocument, pdfDocument.getPageIndices());
                for (let l=0; l<contentPages.length; l++) {
                  newPdf.addPage(contentPages[l]);
                  if(pageWidth == 0){
                    pageWidth = contentPages[l].getWidth();
                    pageHeight = contentPages[l].getHeight();
                  }
                }
              }
            }
            //如果是圆角，就补充空白页
            if(this.wave.printChannel === "KuaiYin"){
              if(this.wave.waveName.indexOf("圆角") != -1){
                let allPageSize = newPdf.getPageCount();
                let mod = allPageSize % 144;
                if(mod != 0){
                  let diff = 144 - mod;
                  for(let i = 1; i <= diff; i++){
                    newPdf.addPage([pageWidth, pageHeight]);
                  }
                }
              }
            }
            let uint8Array = await newPdf.save();
            let mergeBuffer = Buffer.from(uint8Array);
            downloadPdf(mergeBuffer, this.wave.waveNo + "_" + this.wave.waveName
              + ".pdf");
            this.wavePrintOrderPdfDownloadLoading = false;
          });
        }catch (error) {
          this.wavePrintOrderPdfDownloadLoading = false;
        }

      },

      /**
       *  获取打印订单的所有PDF文件
       */
      getPrintPdfBatch(){
        // if(this.dataListSelections.size == 0){
        //   this.$message.error("请至少选择一个订单");
        //   return ;
        // }
        return new Promise((resolve, reject) => {
          // 获取pdf链接集合
          // let orderNumberList = this.dataListSelections.map(item=>item['orderNumber'])
          this.$http({
            url: this.$http.adornUrl(`/printOrder/printOrder/getPrintPdfBatch`),
            method: 'POST',
            // data: this.$http.adornData({printChannel: this.wave.printChannel, waveId: this.wave.waveId, orderNumberList: orderNumberList})
            data: this.$http.adornData({printChannel: this.wave.printChannel, waveId: this.wave.waveId})
          }).then(({ data }) => {
            resolve(data);
          });
        })

      },

      // 跳转至导入选择
      getUpload () {
        this.uploadVisible = true
        this.$nextTick(() => {
          this.$refs.expressBillUpload.init(this.wave.waveId)
        })
      },
      // 刷新数据
      getWaitingConsignmentExcel () {
        this.getDataList(this.page);
        // 修改
        this.$http({
          url: this.$http.adornUrl(`/wave/wave/info/${this.wave.waveId}`),
          method: 'GET',
          params: this.$http.adornParams()
        }).then(({ data }) => {
          this.wave = data
        })
      },
      productionLockConfirm(){
        this.$confirm('你确定要锁定并转为生产中吗？一旦锁定将无法增删订单', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl(`/wave/wave/confirmProductionLock`),
            method: 'POST',
            data: this.$http.adornData({waveId: this.wave.waveId, printChannel: this.printChannel})
          }).then(({data}) => {
            if(data.status == "success"){
              this.$message({
                message: data.msg,
                type: 'success'
              })
              this.getWave(this.wave.waveId);
              this.getDataList(this.page);
            }else{
              this.$message({
                message: data.msg,
                type: 'error'
              })
            }
          })
        }).catch(() => {

        });
      },
      productionLockCancel(){
        this.$confirm('你确定要取消锁定吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl(`/wave/wave/cancelProductionLock`),
            method: 'POST',
            data: this.$http.adornData({waveId: this.wave.waveId, printChannel: this.printChannel})
          }).then(({data}) => {
            if(data){
              this.$message({
                message: "取消成功",
                type: 'success'
              })
              this.getWave(this.wave.waveId);
              this.getDataList(this.page, null, false);
            }else{
              this.$message({
                message: "取消失败",
                type: 'error'
              })
            }
          })
        }).catch(() => {

        });
      },
      downloadPrintOrderPdf(printOrder){
        this.wavePrintOrderPdfDownloadLoading = true;
        let dataBody = {printChannel: printOrder.printChannel, orderNumber: printOrder.orderNumber, waveId: printOrder.waveId};
        this.$http({
          url: this.$http.adornUrl('/printOrder/printOrder/downloadPrintOrderPdf'),
          method: 'get',
          params: this.$http.adornParams(dataBody),
          responseType: 'blob'
        }).then(({data}) => {
          this.wavePrintOrderPdfDownloadLoading = false;
          let pdfName = printOrder.orderNumber + "_" + printOrder.receiverName + "_" + printOrder.prodName + ".pdf";
          // downloadPdf(data, pdfName + ".pdf");
          const blob = new Blob([data], {
            type: 'application/pdf'
          })
          saveAs(blob, pdfName);
        }).catch((error) => {
          this.wavePrintOrderPdfDownloadLoading = false;
        })
      },
      openModifyExpressBillDialog(row){
        this.printOrder.waveId = row.waveId;
        this.printOrder.orderNumber = row.orderNumber;
        this.printOrder.oldDeliveryNo = row.deliveryNo;
        this.modifyExpressBillVisible = true;
      },
      modifyExpressBill(waveId, printOrder){
        let dataBody = {waveId: waveId, orderNumber: printOrder.orderNumber,
          deliveryNo: printOrder.deliveryNo,
          deliveryName: printOrder.deliveryName,
          deliveryCode: printOrder.deliveryCode};
        this.$http({
          url: this.$http.adornUrl(`/printOrder/printOrder/modifyExpressBill`),
          method: 'POST',
          data: this.$http.adornData(dataBody)
        }).then(({data}) => {
          if(data){
            this.modifyExpressBillVisible = false;
            this.$message({
              message: "修改成功",
              type: 'success'
            })
            this.getDataList(this.page);
          }else{
            this.$message({
              message: "修改失败",
              type: 'error'
            })
          }
        })
      },
      /**
       * 页面滚动事件
       */
      scrollToTop () {
        let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
        this.showHeadScroll = scrollTop > 400
      },

      dialogClose(){
        this.wave = {},
        this.visible = false
        this.theData = null;
        this.dataList = [];
        this.visible = false;
        this.dataForm = {};
        this.page = {
          total: 0, // 总页数
            currentPage: 1, // 当前页数
            pageSize: 61 // 每页显示多少条
        },
        this.$emit("refressWaveList", null);
      },
      resetSearchForm(){
        this.searchForm = {};
      },

      /**
       * 获取数据列表
       */
      getDataList (page, params, newData = false) {
        page = (page === undefined ? this.page : page)
        this.dataListLoading = true
        if (newData || !this.theData) {
          this.theData = {
            current: page == null ? this.page.currentPage : page.currentPage,
            size: page == null ? this.page.pageSize : page.pageSize,
            'orderNumber': this.searchForm.orderNumber,
            'receiverName': this.searchForm.receiverName,
            'deliveryNo': this.searchForm.deliveryNo,
            'waveId': this.wave.waveId,
            'workStatus': this.searchForm.workStatus
          }
        } else {
          this.theData.current = page == null ? this.page.currentPage : page.currentPage
          this.theData.size = page == null ? this.page.pageSize : page.pageSize
          this.theData.status = this.status
        }
        this.$http({
          url: this.$http.adornUrl('/printOrder/printOrder/page'),
          method: 'get',
          params: this.$http.adornParams(
            Object.assign(this.theData, params
            ), false
          )
        }).then(({ data }) => {
          this.dataList = data.records
          this.page.total = data.total
          this.sts = !this.status ? 0 : this.status
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.page.pageSize = val
        this.page.currentPage = 1
        this.getDataList(this.page)
      },

      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },

      /**
       * 根据选项设置时间
       * 1:今天 2:昨天 3: 近七天 4:近30天 5:近60天
       */
      setDateRange (val) {
        this.timeActive = val
        var startDay = null
        var endDay = null
        if (val === 1) {
          startDay = 0
          endDay = 0
        } else if (val === 2) {
          startDay = -1
          endDay = -1
        } else if (val === 3) {
          startDay = -7
          endDay = -1
        } else if (val === 4) {
          startDay = -30
          endDay = -1
        } else {
          return
        }
        // 开始时间
        let startTime = moment().add(startDay, 'days').startOf('days').format('LL')
        // 结束时间
        let endTime = moment().add(endDay, 'days').endOf('days').format('LL')
        this.dateRange = [startTime, endTime]
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.orderId
        })
        this.$confirm(`${this.$i18n.t('sys.makeSure')}[${id ? this.$i18n.t('text.delBtn') : this.$i18n.t('sys.batchDelete')}]${this.$i18n.t('text.menu')}?`, this.$i18n.t('text.tips'), {
          confirmButtonText: this.$i18n.t('crud.filter.submitBtn'),
          cancelButtonText: this.$i18n.t('crud.filter.cancelBtn'),
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl(`/prod/spec/${ids}`),
            method: 'delete',
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            this.$message({
              message: this.$i18n.t('publics.operation'),
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList(this.page)
              }
            })
          })
        }).catch(() => { })
      },
      // 清空按钮
      clear () {
        this.dataForm = {}
        this.dateRange = []
        this.status = null
        this.timeActive = null
      },
      // 搜索查询
      searchChange (newData = false) {
        this.page.currentPage = 1
        this.getDataList(this.page, null, newData)
      },
      handleCurrentChange (val) {
        this.page.currentPage = val
        this.getDataList()
      },
      handleSizeChange (val) {
        this.page.pageSize = val
        this.getDataList()
      },
      cancelDelivery(row) {
        this.$confirm('确定取消发货吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl(`/printOrder/printOrder/cancelDelivery/` + row.printOrderId),
            method: 'POST',
            data: this.$http.adornData()
          }).then(({data}) => {
            if (data) {
              this.getDataList(this.page, false);
              this.$message({
                message: "取消发货成功",
                type: 'success'
              })
            } else {
              this.$message({
                message: "取消发货失败",
                type: 'error'
              })
            }
          }).catch(() => {
          })
        })
      },
    },
    destroyed () {
      // 页面销毁时移除监听
      window.removeEventListener('scroll', this.handleScroll)
    },
  }
</script>
<style lang="scss" scoped>
  .expand-detail{
    font-size: 18px;
  }
  expand-detail-title{
    font-size: 18px;
    font-weight: bold;
  }
  .el-divider--vertical {
    display: inline-block;
    width: 1px;
    height: 30px;
    margin: 0 16px;
    vertical-align: middle;
    position: relative;
  }
</style>
