<template>
  <div>
    <loading :loading="loading"></loading>
    <div v-if="loading" class="desc">{{desc}}</div>

    <div v-if="clickCopyCancel||clickCopyOK" class="copy" style="margin-top: 50%">
      <Icon :type=copyIcon class="copy-icon" :style="{color:(clickCopyOK?'rgb(25,189,107)':'rgb(238,65,18)')}"/>
    </div>
    <div class="copy" style="font-size: 24px;color: #17233d;font-weight: bold;margin-top: 10px" v-if="clickCopyCancel||clickCopyOK">{{copyResult}}</div>
    <div class="copy" style="color: #808695;margin-top: 10px" v-if="clickCopyCancel||clickCopyOK">{{copyDesc}}</div>

  </div>
</template>

<script>
import {formMixin} from '@/mixins/form'
import {hiprint} from "vue-plugin-hiprint";
import {mapMutations} from "vuex";
// import VConsole from 'vconsole'

export default {
  mixins: [formMixin],
  components: {
    print
  },
  name: 'wx-print',
  data() {
    return {
      templateList: [],
      loading:true,
      uploadSuccess:false,
      desc:'正在打印票据，请稍候…',
      copyIcon:'ios-checkmark-circle',
      copyResult:'操作成功',
      copyDesc:'链接复制成功，请复制链接到手机浏览器进行下载',
      clickCopyOK:false,
      clickCopyCancel:false,
      // docs:{
      //   // 销售订单
      //   'order':{'docName':this.$config.docCode.order},
      //   // 入库单
      //   'entry':{'docName':this.$config.docCode.entry},
      //   // 出库单
      //   'out':{'docName':this.$config.docCode.out},
      //   // 库存调整
      //   'ivt_transfer':{'docName':this.$config.docCode.ivt_transfer},
      //   // 库存冻结
      //   'ivt_freeze':{'docName':this.$config.docCode.ivt_freeze},
      // },
    }
  },
  methods: {
    ...mapMutations(['setSvcCode']),

    dataURLtoFile: (dataurl, filename) => {
      let arr = dataurl.split(',');
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      //转换成file对象
      return new File([u8arr], filename, {type: mime});
    },
    blobToFile(blob, fileName) {
      const file = new File([blob], fileName, { type: blob.type })
      return file
    },
  },
  created() {
  },
  mounted() {
    // const vConsole = new VConsole();
    console.log('this.$route.query',this.$route.query)
    if (!this.$route.query.layout_id) {
      this.$Message.warning('请先选择一个模板再打印')
      return
    }
    if (!this.$route.query.data_id) {
      this.$Message.warning('请先选择一条数据再打印')
      return
    }
    if (!this.$route.query.doc) {
      this.$Message.warning('请先选择单据类型再打印')
      return
    }
    if (!this.$route.query.uuid) {
      this.$Message.warning('请先设置唯一id')
      return
    }
    if (!this.$route.query.svc_code) {
      this.$Message.warning('请先设置svc_code')
      return
    }
    if (!this.$route.query.cp_id) {
      this.$Message.warning('请先设置cp_id')
      return
    }



    this.setSvcCode(this.$route.query.svc_code)
    let doc = this.$route.query.doc;
    let layout = this.excute(this.$service.printLayoutService, this.$service.printLayoutService.selectByCond, { flgValid: true, docName: this.$config.docCode[doc], cpId:this.$route.query.cp_id})
    let data = this.excute(this.$service.printLayoutService,this.$service.printLayoutService.getPrintData,{dataId:this.$route.query.data_id,objectCode:this.$route.query.doc})
    // let header=this.excuteNoParam(this.docs[this.$route.query.doc].service, this.docs[this.$route.query.doc].service.selectById,[this.$route.query.data_id])
    // let detail=this.excuteNoParam(this.docs[this.$route.query.doc].service, this.docs[this.$route.query.doc].service.selectOrderInfoById, [this.$route.query.data_id])
    Promise.all([data,layout])
      .then((results) => {

        // 在这里执行接下来的操作
        if(results?.[0]?.code === this.$config.SUCCESS_CODE){
          let header =results?.[0]?.data
          let detail =results?.[0]?.data.itemList
          let layout =results?.[1]?.data?.list.find(it => it.layoutId == this.$route.query.layout_id)?.layoutData
          this.$set(header, 'table', detail)

          let printData = {...header}

          let hiprintTemplate = new hiprint.PrintTemplate({
            template: layout,
          })
          console.log('data',header)
          console.log('layout',layout)
          console.log('hiprintTemplate',hiprintTemplate)

          // hiprintTemplate.toPdf(printData,'单据打印',{isDownload:false,type:'datauristring'}).then(dataURL=>{
          //   let pdf = this.dataURLtoFile(dataURL, "pdf");
          //   this.pdf=pdf
          //   let formData = new FormData();
          //   formData.append('file', pdf);
          //   this.excute(this.$service.fileService, `upload?folder=pdf&uuid=${this.$route.query.uuid}`,formData).then(res => {
          //     if (res.code === this.$config.SUCCESS_CODE) {
          //       console.log('upload-res',res)
          //     }
          //   })
          // })

          //is_download用于处理ios不兼容情况
          if(this.$route.query.is_download==='true'){
            hiprintTemplate.toPdf(printData, '打印预览pdf');
          }else{
            //Blob
            hiprintTemplate.toPdf(printData,'单据打印',{isDownload:false,type:''}).then(blob=>{
              let pdf =this.blobToFile(blob, 'blob.pdf')
              let formData = new FormData();
              formData.append('file', pdf);
              this.excute(this.$service.fileService, `upload?folder=pdf&uuid=${this.$route.query.uuid}`,formData).then(res => {
                if (res.code === this.$config.SUCCESS_CODE) {
                  console.log('upload-success',res)
                  this.uploadSuccess=true
                  this.desc='已成功生成票据PDF！等待下载…'
                }
              })
            })
            //5秒后弹出提示，引导用户手动下载
            setTimeout(()=>{
              if(!this.uploadSuccess){
                this.$Modal.confirm({
                  title: '打印票据遇到问题？',
                  content: '<p>如页面长时间无响应，请点击【确定】按钮，复制链接到手机浏览器下载票据文件</p>',
                  onOk: () => {
                    this.loading=false

                    this.clickCopyOK=true

                    let baseUrl=this.$config.serviceUrl

                    let url=baseUrl.substring(0,baseUrl.indexOf('/',8),)+'/wx-print?svc_code=' +this.$route.query.svc_code + '&is_download=true'
                      + '&cp_id=' +  this.$route.query.cp_id + '&doc=' + this.$route.query.doc + '&layout_id='
                      + this.$route.query.layout_id + '&data_id=' + this.$route.query.data_id+'&uuid='+this.$route.query.uuid

                    this.$copyText(url).then(function (e) {
                      console.log('复制成功',e);
                    }, function (e) {
                      console.log('复制失败',e);
                      this.copyIcon='ios-close-circle'
                      this.copyResult='操作失败'
                      this.copyDesc='复制链接失败，请联系管理员'
                    })
                  },
                  onCancel: () => {
                    this.loading=false
                    this.clickCopyCancel=true
                    this.copyIcon='ios-close-circle'
                    this.copyResult='操作失败'
                    this.copyDesc='未复制链接，请返回上一页'
                  }
                })
              }
            },10000)
          }
        }else {
          this.$Message.warning(this.$t('W_006'))
        }
      })
  },


}
</script>

<style scoped>

.desc{
  position:absolute;
  top:58%;
  width:100%;
  display:flex;
  justify-content:center;
  font-weight:bold;
  color: black;
}
.copy{
  width: 100%;
  display: flex;
  justify-content: center;
}

.copy-icon{
  font-size: 100px;
}
</style>
