<template>
    <div>
    <!-- 打印发货单 -->
      <div class="pdfBox">
        <div
          class="page pdfidCalss"
          id="pdfid"
          :index="i"
          v-for="(item,i) in big_arrs"
          :key="i"
        >
          <div class="top_title">
            <img :src="printOrderTitle"/>
          </div>

          <div class="supplier_info">
            <table>
              <tr>
                <td>
                  <img crossorigin="anonymous" :src="orderInfo.brandLogo?orderInfo.brandLogo +'?x-oss-process=image/resize,h_60,w_60&time=' + new Date().valueOf():''" />
                  {{orderInfo.brandName}}发货单</td>
              </tr>
            </table>
          </div>
          <div class="order_info">
            <span class="order_number">订单编号：{{orderInfo.orderCode}}</span>
            <span>订单日期：{{orderInfo.addDate}}</span>
          </div>

          <template v-if="i == 0">
            <div
            class="div_info"
            style="border-bottom:none"
          >
            <div class="left_info">
              <h4>收货方</h4>
              <p>
                <span class="til_span tesu_span">收&nbsp;货&nbsp;人：</span><span class="text_span">{{orderInfo.receiver}}</span>
              </p>
              <p>
                <span class="til_span">收货电话：</span><span class="text_span">{{orderInfo.phone}}</span>
              </p>
              <p><span class="til_span">收货地址：</span><span class="text_span text_span_add">{{orderInfo.address}}</span></p>
            </div>
            <div class="right_info">
              <h4>寄货方</h4>
              <p>
                <span class="til_span">公司名称：</span><span class="text_span">{{comInfo.merCompany}}</span>
              </p>
              <p>
                <span class="til_span">售后电话：</span><span class="text_span">{{comInfo.merMobile1}}</span>
              </p>
              <p><span class="til_span">售后地址：</span><span class="text_span text_span_add">{{comInfo.merAddress}}</span></p>
            </div>
          </div>
          <div
            class="div_info"
            style="border-top:none;padding-bottom:.5cm;"
          >
            <div class="left_info">
              <h4>经销商(市代要求发送物流)</h4>
              <p>
                <span class="til_span">物流公司名称:</span>
                <span class="text_span">{{orderInfo.logisticsCompanyName}}</span>
              </p>
              <p>
                <span class="til_span">物流公司电话:</span>
                <span class="text_span">{{orderInfo.logisticsMobilePhone}}</span>
              </p>
              <p>
                <span class="til_span">物流公司地址:</span>
                <span class="text_span text_span_add text_span_add1">{{orderInfo.logisticsAddress}}</span>
              </p>
              <p>
                <span class="til_span">物流备注:</span>
                <span class="text_span text_span_add">{{orderInfo.logisticsRemarks}}</span>
              </p>
            </div>
            <div class="right_info">
              <h4>供货商实发物流</h4>
              <p>
                <span class="til_span">物流公司:</span>
                <span class="text_span">{{orderInfo.logisticsName}}</span>
              </p>
              <p>
                <span class="til_span">物流单号:</span>
                <span class="text_span">{{orderInfo.invoiceNo}}</span>
              </p>
              <p>
                <span class="til_span">发货件数:</span>
                <span class="text_span">{{orderInfo.deliverQty}}</span>
              </p>
            </div>
          </div>
          </template>

          <div class="table_wrap">
            <table>
              <thead>
                <tr>
                  <th class="t-1">序号</th>
                  <th class="t-2">图片</th>
                  <th class="t-3">商品信息</th>
                  <th class="t-4">商品备注</th>
                  <th class="t-5">数量</th>
                </tr>
              </thead>
              <tbody>
                  <tr
                    v-for="(subItem,index) in item"
                    :key="i+'-'+index"
                  >
                    <td
                      class="t-1"
                      v-text="i<1?(index + 1):((index + 1)+ pageSize + maxPageSize*(i - 1))"
                    ></td>
                    <td class="t-2">
                      <img crossorigin="anonymous" :src="subItem.goodsImg?subItem.goodsImg+'?x-oss-process=image/resize,h_60,w_60' :''" />
                    </td>
                    <td class="t-3">
                      <span v-text="subItem.goodsInfo"></span>
                    </td>
                    <td class="t-4">
                      <span v-text="subItem.goodsRemark"></span>
                    </td>
                    <td class="t-5">
                      <span v-text="subItem.count"></span>
                    </td>
                  </tr>
                  <!-- 补全表单用 -->
                  <!-- <tr
                    v-for="(subItem,index) in (item.length%5==0?0:5-item.length%5)"
                    :key="index"
                  >
                    <td
                      class="t-1"
                      v-text="(index+item.length%5)+1+(5*i)"
                    ></td>
                    <td class="t-2"></td>
                    <td class="t-3">
                      <span></span>
                    </td>
                    <td class="t-4"><span></span></td>
                    <td class="t-5"></td>
                  </tr> -->
                <tr>
                  <td colspan="4">本页小计</td>
                  <td>{{item | orderCounTotal}}</td>
                </tr>
                <tr>
                  <td
                    colspan="5"
                    class="remark"
                  >
                    <em>订单备注：</em>
                    <span>
                      {{orderInfo.remark}}
                    </span>
                  </td>
                </tr>
                <tr>
                  <td
                    colspan="5"
                    class="count"
                  >商品数量合计：<span class="pad_right">{{item | orderCounTotal}}</span>件</td>
                </tr>
              </tbody>
            </table>

          </div>
          <div class="footer_div">
            本页为第<span>{{i + 1}}</span>页<em></em>共<span>{{big_arrs.length>0?big_arrs.length:''}}</span>页
          </div>
        </div>
        <div class="filePreview" v-if="iframeShow">
          <div class="filePreview_center">
            <div class="center_header">
              <div class="header_left">文件预览</div>
              <div class="header_right" @click="filePreviewCancel">关闭</div>
            </div>
            <!-- <div class="center_center"> -->
              <!-- <iframe :src="printUrl" frameborder="0" style="width: 100%; height: 100%"></iframe> -->
              <!-- <object :data="printUrl" type="application/pdf" width="100%" height="100%"></object> -->
            <!-- </div> -->
          </div>
        </div>
        <!-- <div v-show="iframeShow"> -->
          <!-- <object :data="printUrl" type="application/pdf" width="100%" height="100%">This browser does not support PDFs. Please download the PDF to view it: <a :href="printUrl">Download PDF</a></object> -->
          <!-- <iframe :src="printUrl"  width="100%" height="100%">This browser does not support PDFs. Please download the PDF to view it: <a :href="printUrl">Download PDF</a></iframe> -->
        <!-- </div> -->
      </div>
    </div>
</template>
<script>
import html2Canvas from "html2canvas";
import jspdf from "jspdf";
import { _getStorage,_removeStorage } from '@/utils/utils'
export default {
    data(){
        return{
            pageurl:[],
            // userInfo:{},
            printUrl:"",
            iframeShow:false,
            printOrderTitle:_getStorage('printData')['printOrderTitle'],
            orderInfo:_getStorage('printData')['orderData'],
            big_arrs:'',
            allSum:'',
            pageSize:"",
            maxPageSize:'',
            comInfo:_getStorage('info')
        }
    },
    // props:{
    //     big_arrs:{
    //         type:Array,
    //         default:[]
    //     },
    //     orderData:{
    //         type:Object,
    //         default:{}
    //     },
    //     allSum:{
    //         type:Number,
    //         default:0
    //     }
    // },
    mounted(){
      var dataDetails = this.orderInfo.details;
      var len = dataDetails.length
      var big_arrs = [];
      var min_arrs = [];
      var pageSize = len > 5?6:len // 留位置放置订单备注
      var maxPageSize = 12

      for (var i = 0; i < dataDetails.length; i++) {
        // 处理分页
        if(big_arrs.length == 0){
          // 第一页有表头放五个
          min_arrs.push(dataDetails[i]);
          if ((i + 1) % pageSize == 0) {
            big_arrs.push(min_arrs);
            min_arrs = [];
          }
        }else{
          // 第二页没有表头放十个
          min_arrs.push(dataDetails[i]);
          if ((i + 1 - pageSize) % maxPageSize == 0) {
            big_arrs.push(min_arrs);
            min_arrs = [];
          }
        }
      }
      if (min_arrs.length > 0) {
        // 最后一页补充剩余商品
        big_arrs.push(min_arrs);
      }

      // 留出订单备注的位置
      if(big_arrs[big_arrs.length-1].length > (maxPageSize - 2)){
        big_arrs[big_arrs.length] = []
      }

      this.big_arrs = big_arrs;
      this.allSum = dataDetails.length;
      this.pageSize = pageSize;
      this.maxPageSize = maxPageSize;

      this.$nextTick(() => {
        this.makepdf()
      })
    },
    methods:{
      filePreviewCancel(){
        this.iframeShow=false;
      },
      makepdf() {
        // console.log(new jspdf("", "pt", "a4"))
        this.pageurl=[];
        this.$loading({
          lock: true,
          text: '正在加载，如长时间无反应，请刷新重试',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        for (
          var ii = 0;
          ii < document.body.querySelectorAll(".pdfidCalss").length;
          ii++
        ) {
          this.creatImg(document.body.querySelectorAll(".pdfidCalss")[ii], ii);
        }
      },
      creatImg(obj, ii) {
        // console.log(ii)
        var opts = {
          scale: 4,
          // dpi:300,
          useCORS: true
          // logging:true
          // allowTaint:true
        };
        html2Canvas(obj, opts).then(canvas => {
          var orderId = this.orderInfo?this.orderInfo.orderId:'发货单'
          var contentWidth = canvas.width;
          var contentHeight = canvas.height;
          var pageHeight = (contentWidth / 592.28) * 841.89;
          var leftHeight = contentHeight;
          //页面偏移
          var position = 0;
          //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
          var imgWidth = 595.28;
          var imgHeight = (595.28 / contentWidth) * contentHeight;

          var pageData = canvas.toDataURL("image/jpeg", 1.0);

          //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
          //当内容未超过pdf一页显示的范围，无需分页
          // var pdf = new jspdf("", "pt", "a4");
          // if (leftHeight < pageHeight) {
          //   pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
          // } else {
          //   while (leftHeight > 0) {
          //     pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
          //     leftHeight -= pageHeight;
          //     position -= 841.89;
          //     //避免添加空白页
          //     if (leftHeight > 0) {
          //       pdf.addPage();
          //     }
          //   }
          // }

          this.pageurl.push({ pageData: pageData, index: ii });
          // console.log(this.pageurl)
          if (this.pageurl.length ==document.body.querySelectorAll(".pdfidCalss").length) {
            var pdf = new jspdf("", "pt", "a4");

            this.pageurl = this.pageurl.sort(function compare(a, b) {
                return a.index - b.index;
            });
            pdf.internal.scaleFactor = 1.33;

            for (var iii = 0; iii < this.pageurl.length; iii++) {
                pdf.addImage(
                this.pageurl[iii]["pageData"],
                "JPEG",
                0,
                position + 0,
                imgWidth,
                imgHeight
                );
                if (iii < this.pageurl.length - 1) {
                  pdf.addPage();
                }
            }

            // pdf.autoPrint()
            // pdf.save(`${orderId}.pdf`);
            this.printUrl = pdf.output('bloburi');
            // this.iframeShow = true
            // this.iframeShow=true;
            // console.log(this.printUrl)
            // window.open()
            // debugger
            // this.printUrl = this.printUrl.replace('data:','')
            
            var availWidth = window.screen.availWidth;
            if (window.orientation === 180 || window.orientation === 0) { 
              availWidth = Math.min(window.screen.availWidth, window.screen.availHeight);
            };
            if (window.orientation === 90 || window.orientation === -90 ){ 
              availWidth = Math.max(window.screen.availWidth, window.screen.availHeight);
            } 
            window.document.write('<object data="'+ this.printUrl+'" type="application/pdf" width="100%" style="height: -webkit-fill-available">This browser does not support PDFs. Please download the PDF to view it: <a href="'+ this.printUrl+'">Download PDF</a></object>')
            // window.document.write('<iframe src="'+ this.printUrl+'" width="100%" height="100%" style="width:100%"></iframe>')
            this.$loading().close();
            // _removeStorage('printData')
          }
        });
      },
    },
    filters: {
        orderCounTotal: function(arr) {
            var sum = 0;
            for(var i=0;i<arr.length;i++){
            sum+=arr[i]['count'];
            }
        return sum;
        }
    },
}
</script>
<style lang="sass" scoped>
@import "@/assets/styles/printOrder.scss";
</style>
<style scoped lang="scss">
// .iframeBox{
//       position: fixed;
//       top:0;
//       left:0;
//       width: 100%;
//     height: 100%;
//     z-index: 999;
// }
.filePreview{
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 999;
  background: rgba($color: #000000, $alpha: 0.4);
  min-height: 500px;
  overflow: auto;
  .filePreview_center{
    width: 80%;
    height: 100%;
    // left: 25%;
    background: white;
    border-top-right-radius: 3px;
    border-top-left-radius: 3px;
    // position: relative;
    transform: translateY(-50% -50%);
    // padding: 16px;
    margin: 0 auto;
    .center_header{
      padding-bottom: 10px;
      border-bottom: 1px solid #dee2ed;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-radius: 3px;
      padding: 16px;
      .header_left{
        font-weight: bold;
      }
      .header_right{
        cursor: pointer;
        color: #99a1ad;
      }
    }
    .center_center{
      border-radius: 3px;
      width: 100%;
      height: calc(100% - 80px);
    }
  }
}
</style>
