<template>
  <div class="page-view" v-loading="load">
    <div class="tool">
      <el-tooltip class="item" effect="dark" content="刷新" placement="top">
        <el-button icon="el-icon-refresh" size="small" circle @click="getList"></el-button>
      </el-tooltip>
    </div>
    <vxe-table
      size="mini"
      border
      stripe
      ref="table"
      :height="height"
      :row-config="{isCurrent: true,isHover: true}"
      :data="data">
      <vxe-column type="seq" title="序号" width="60"></vxe-column>
      <vxe-column field="deliveryOrderCode" title="订单编号" width="110"> </vxe-column>
      <vxe-column field="remark" title="线上订单号" width="130"> </vxe-column>
      <vxe-column field="orderType" title="出库类型" width="80"> </vxe-column>
      <vxe-column field="deliveryOrderId" title="发货单仓储系统编码" width="150"> </vxe-column>
      <vxe-column field="deliveryCode" title="物流编号" width="130"> </vxe-column>
      <vxe-column field="warehouseCode" title="仓库编码" width="100"> </vxe-column>
      <vxe-column field="orderFlag" title="订单标记" width="120"> </vxe-column>
      <vxe-column field="sourcePlatformCode" title="订单来源平台编码" width="130"> </vxe-column>
      <vxe-column field="shopNick" title="店铺名称" width="170"> </vxe-column>
      <vxe-column field="totalAmount" title="订单总金额" width="120"> </vxe-column>
      <vxe-column field="itemAmount" title="商品总金额(元)" width="120"> </vxe-column>
      <vxe-column field="receiverInfo" title="收件信息" show-overflow show-footer-overflow width="200"> </vxe-column>
      <vxe-column field="senderInfo" title="发件信息" show-overflow show-footer-overflow width="200"> </vxe-column>
      <vxe-column field="createTime" title="创建时间" width="140"> </vxe-column>
      <vxe-column title="操作" width="180" fixed="right" align="center">
      <template #default="{ row }">
        <el-button type="text" size="mini" @click="detailProduct(row)">查看商品</el-button>
        <el-button type="text" size="mini" @click="printClick(row)">打印</el-button>
      </template>
    </vxe-column>
    </vxe-table>
    <div class="page">
      <el-pagination v-if="page.total > 0" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page.pageNo" :page-size="page.pageSize"
        :layout="'total, sizes, prev, pager, next, jumper'" :total="page.total"></el-pagination>
    </div>
    <JstproductModal ref="JstproductModal" />
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import {jstOrderList,printHandle,waybillPrintData} from '@/api/jstOrder'
import JstproductModal from "./jstproductModal.vue";
import axios from 'axios'
@Component({components:{JstproductModal}})
export default class JushuitanOrder extends Vue {
  data:Array<any>=[]
  load:boolean=false
  height=700
  page:any={
    pageNo: 1, //当前页
    pageSize: 20, //每页条数
    total: 0 //总条数
  }
  handleSizeChange(v:number){
    this.page.pageSize = v;
    this.getList()
  }
  handleCurrentChange(v:number){
    this.page.pageNo = v;
    this.getList()
  }
  printClick2(){
    axios.request({ 
      url: 'https://oms.lzlxylsf.com/app-web/open/router/rest.json?method=ds.omni.wms.waybill.third.get&appKey=221280&timestamp=1707045992039&sign=F7FD55CD2DA40B35704FF1A8064DEAD5',
      method: 'POST', 
      headers: { 
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
      }, 
      data: JSON.stringify({ 
        'request': { 'waybillCodes': ['75613880263785'] } 
      })
    }).then((res:any) => {
      if(res.code == 200){
        this.webSocketHandle(res.data)
      }
    }).catch((err:any) => {

    })
  }
  printClick(row:any){
    // this.test();
  //   let res={
  //     "msg": "操作成功",
  //     "code": 200,
  //     "data": {
  //         "flag": true,
  //         "code": "200",
  //         "message": null,
  //         "data": [
  //             {
  //                 "waybillCode": "78769463611163",
  //                 "platformType": "WB_TB",
  //                 "props": "{\"ver\":\"waybill_print_secret_version_1\",\"signature\":\"MD:caoTUnmrO9jYalFWnWLiJQ==\",\"encryptedData\":\"AES:rU904rj6UH2oqfSUb43+Z199vDU2GZtH5/LVIEq0ppUJuwjq7qZ58JRvDHOQ/f2QhqdsWiYYFqp6z96+fPLupxENx4gZUSA/zYJbbdwevCwr/shr2vEh0gSP5TVLhRkf0cs+O/SQI1why/dhaLeykU903ISeYisMbuU8RT158nol7DbBzTBsXpPGc7WGU7iIqZ5aPxpBaIdrmS1Fn0PAr8cLTjeFsLybxgaBVspR/1Dzo5CTIZKxz7R/9Z7hVGU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B/0ViqkBrXbIKRgxiJ8RK4Nfu8t+xmIlWsLHDnbg3T202nYybsMfpX0nShljRB4OhEXSRbbtSeseC+plj+CbpW5GDKBVEtUrodKbx5hf2kaNj750i37xmW6Ron9PP5v9xXzmzlgsH5Edii1hDc8wze+O3camJWXvltBb9Z9VmgcQGmr87KP5mkCTQ8iDR7mKWy9t68cRpF4obvq01FTPjtqy7DpG8pqLwCurT+YxTbp3jwGsxPEEHVrpdFh/KA6ZOVDaxiRPS/i8jearV9aJuq1U9zk+RJUpnYXkKXOZErl03BmCedvMHXdpKfhl+UHsdd/tXA/w1xyv59Y5GBBu0iGc49ySR4mnY9q9YlqSYSeYRtw+kmQTS3k5KvCagwr/Fm40rp0oWNrRPdM386o6aZ3I+zVA327809IyDjWIeWl8D+dRMDvHQAH7fksxJuW9LltWIO6iSC92vt0Plo7iAIQHLrN4yODqSV6Ta+Dk47pAfKaW8CCKAoAqd80zEbbwUHzxCIsiY+0U97ML09o/PQvdJq4sw+RZf90J/pk9p4+JR7iKJMsfbNLWCjPcijnIlxV4PfJFGAD+iKcGzfSQ0q1O0Ucx0CNQPJVYgZE43H+tBjFcX+IFtrgHjEu+WR5ggDgUiHCdS//z91HLj+EJWsLqkc5djj5Fo8R2CAAALsH7K9i3B/di+DCWCAhQ3Bg0L6vtPgGv+ncJf6/vtiBDQTFjqk5R7O9/FokzTcZjdoH33rCJMJ1mZ9EXkceB6G0/VRz3nyLLwVO2i7SUsDxWGsu7I4pjCR1KbeNTwdXHPElr6qi21DgeHO9B/DCjfrcl5xtXpbgWVGYtburcyMf7N/tTtLj497/aAYiDJp/US+gFLpCPQGnGnnFqn9OPMjUzejGDnr4wLcucm2PrR4gj5ad2uiH+m08YHWE7XIw76Hu9G4hKEx4jv1zoRR9ardUZ05QRrUuhJInKVEZwKrQqTFjK6RuWu96dniZq+M54BgZAXlAKrk96i+\",\"realCpCode\":\"ZTO\",\"templateURL\":\"http://cloudprint.cainiao.com/template/standard/300336\"}"
  //             }
  //         ]
  //     }
  // }
  //   this.tbWebSocketHandle(res)

    let data:any = {
      deliveryOrderCode:row.deliveryOrderCode
    }
    if(row.sourcePlatformCode == 'JD'){
      data.expressCode = 'JD_ZTO'
    }else if(row.sourcePlatformCode == 'TB'){
      data.expressCode = 'TB_ZTO'
      data.templateUrl = 'https://cloudprint.cainiao.com/template/standard/300336/82'
    }else{
      this.$message("不支持打印");
      return
    }
    this.load = true;
    printHandle(data).then((res:any) => {
      if(res.data.data[0].errorMsg){
        this.load = false;
        this.$message({
          message: res.data.data[0].errorMsg,
          type:'error'
        })
        return
      }
      if(!res.data.data[0].waybillCode){
        this.load = false;
        this.$message({
          message:'面单号为空，请检查！',
          type:'error'
        })
        return
      }
      row.deliveryCode = res.data.data[0].waybillCode;
      this.$forceUpdate();
      this.d2PrintHandle(res.data.data[0],row.sourcePlatformCode)
    }).catch(()=>{
      this.load = false;
    })
  }
  d2PrintHandle(data:any,type:string){
    waybillPrintData({waybillCode:data.waybillCode}).then((res:any) => {
      if(type == 'JD'){
        this.webSocketHandle(res)
      }else if(type == 'TB'){
        this.tbWebSocketHandle(res)
      }else{
        this.load = false;
      }
    }).catch(()=>{
      this.load = false;
    })
    // axios.request({ 
    //   url: 'https://oms.lzlxylsf.com/app-web/open/router/rest.json?method='+data.method+'&appKey='+data.appKey+'&timestamp='+data.timestamp+'&sign=' + data.sign, 
    //   method: 'POST', 
    //   headers: { 
    //     'Content-Type': 'application/json; charset=UTF-8;'
    //   }, 
    //   data: JSON.stringify({ 
    //     'request': { 'waybillCodes': [data.response.data[0].waybillCode] } 
    //   })
    // }).then((res:any) => {
    //   if(res.code == 200){
    //     this.webSocketHandle(res.data)
    //   }else{
    //     this.load = false;
    //   }
    // }).catch((err:any) => {
    //   this.load = false;
    // })
    
  }
  getUuid(){
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  test(){
    let source:any = new WebSocket('ws://127.0.0.1:9113')
    let that:any = this;
    source.onopen = function () {
      that.load = false;
      console.log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fAjUCgz3v/uXtm031s7VWXRznMl8+4H3oASmOBU+mQVlAl8l1kjvKTYeAvuHy+mjvAbixNOGC15hRL+IOquADDtG8gPt1gbEeKkCnn3NGpSnMJTRKL2ScwCES0S8zqmHv1FgUSwe05+9sM2gZPhZMatwQrmp41r1zOFnm5Ykos/DU3sjzkWQFgkTadxgNYkGUDGiE+lbjwur9ADd2werK0NbE+FP2loD2luhBEMkk8w22uzotXUrVVBWOufAjurckIMCGPbHCdEpfzoTKDzUKbVcHKp0TMmS7i08h7BOCoyOLfEFt9LkeYbTEStOUIIb3XBG43AZZN6l8UHvMjT+nGLdppMxjgtyf494ViOSrP8cIl8WrFx4m9MCl2IDehEMoIBysycpFs0f3br3b+BgGKsuE2wEP/Elj4kwa4iJCfPNJgMTggzn2rFMdaGkfhzUj++fpDMTyI9Brf0XvWdIoyesr2/7tsMGLSZTDN9/dt17P5Uq1UCkcyts1OuiMKiQQ2rFUYtc9ehzGPtq9R1UWKsR66NcVgsx2Cforag+fTlDnHqHWF3kD+BgBmji0Rf9jiKQU9Bp5uUV4YoUgNh6n5Il+ASm6E7ayIGp0C0/Pdms8ar6e06zJ3Q=='
      const data = {
        orderType:'PRINT',
        key: new Date().getTime() + that.getUuid(),
        parameters:{
          tempUrl:'https://template-content.jd.com/template-oss?tempCode=ztokd76x130',
          printData:[d]
        }
      }
      const jsonString = JSON.stringify(data)
      source.send(jsonString)
       that.$message({
          message:'打印成功！',
          type:'success'
        })
    }

    source.addEventListener('finish', function(e:any) {
      console.log(e.data)
      source.close()
      console.log('关闭连接')
    })
    source.addEventListener('error', function(e:any) {
      that.load = false;
      if (e.readyState === EventSource.CLOSED) {
        console.log('WebSocket连接已关闭')
      } else {
        that.$message("请检查打印组件是否已打开！")
        console.error('连接错误：', e)
      }
    })
    source.addEventListener('message', function(e:any) {
      console.log('接收到的数据：', e)
      let data = JSON.parse(e.data)
      console.log(data)
    })
  }
  //菜鸟打印
  tbWebSocketHandle(parms:any){
    let source:any = new WebSocket('ws://127.0.0.1:13528')
    let that:any = this;
    this.load = false;
    source.onopen = function () {
      console.log('开始连接...')
      let data:any = {
        "cmd": "print",
        "requestID": new Date().getTime() + that.getUuid(),
        "version": "1.0",
      }
      let task:any = {
        "taskID": new Date().getTime() + that.getUuid(),
        "preview": false,
        documents: []
      }
      try{
        let newData = JSON.parse(parms.data.data[0].props)
        // const data:any = {
        //   orderType:'PRINT',
        //   key: new Date().getTime() + that.getUuid(),
        //   parameters:{
        //     tempUrl:'https://template-content.jd.com/template-oss?tempCode=ztokd76x130',
        //     printData:[newData.yunPrintData.perPrintData]
        //   }
        // }
        let obj = {
          documentID:parms.data.data[0].waybillCode,
          contents:[{
            encryptedData:newData.encryptedData,
            signature:newData.signature,
            templateURL:newData.templateURL
          }]
        }
        task.documents.push(obj)
        data.task = task;

        const jsonString = JSON.stringify(data)
        source.send(jsonString);
        that.$message({
          message:'打印成功！',
          type:'success'
        })
      }catch(e){
        that.$message({
          message:'数据格式出错，打印失败！',
          type:'error'
        })
      }
      
    }

    source.addEventListener('finish', function(e:any) {
      console.log(e.data)
      source.close()
      console.log('关闭连接')
    })
    source.addEventListener('error', function(e:any) {
      that.$message({
        message:'打印失败！',
        type:'error'
      })
      if (e.readyState === EventSource.CLOSED) {
        console.log('WebSocket连接已关闭')
      } 
      // else {
      //   that.$message("请检查打印组件是否已打开！")
      //   console.error('连接错误：', e)
      // }
    })
    source.addEventListener('message', function(e:any) {
      console.log('接收到的数据：', e)
      let data = JSON.parse(e.data)
      console.log(data)
    })
  }
  //京东打印
  webSocketHandle(parms?:any){
    let source:any = new WebSocket('ws://127.0.0.1:9113')
    let that:any = this;
    this.load = false;
    source.onopen = function () {
      console.log('开始连接...')
      try{
        let newData = JSON.parse(parms.data.data[0].props)
        const data = {
          orderType:'PRINT',
          key: new Date().getTime() + that.getUuid(),
          parameters:{
            tempUrl:'https://template-content.jd.com/template-oss?tempCode=ztokd76x130',
            printData:[newData.yunPrintData.perPrintData]
          }
        }
        const jsonString = JSON.stringify(data)
        source.send(jsonString);
        that.$message({
          message:'打印成功！',
          type:'success'
        })
      }catch(e){
        that.$message({
          message:'数据格式出错，打印失败！',
          type:'error'
        })
      }
     
    }

    source.addEventListener('finish', function(e:any) {
      console.log(e.data)
      source.close()
      console.log('关闭连接')
    })
    source.addEventListener('error', function(e:any) {
      that.$message({
        message:'打印失败！',
        type:'error'
      })
      if (e.readyState === EventSource.CLOSED) {
        console.log('WebSocket连接已关闭')
      }
      //  else {
      //   that.$message("请检查打印组件是否已打开！")
      //   console.error('连接错误：', e)
      // }
    })
    source.addEventListener('message', function(e:any) {
      console.log('接收到的数据：', e)
      let data = JSON.parse(e.data)
      console.log(data)
    })
  }
  getList(){
    let data:any={}
    data.pageNo = this.page.pageNo;
    data.pageSize = this.page.pageSize;
    this.load = true
    jstOrderList(data).then((res:any) => {
      this.load = false
      this.data = res.data.records;
      this.page.total = res.data.total
    }).catch(()=>{
      this.load = false
    })
  }
  detailProduct(row:any){
    if(this.$refs.JstproductModal){
      (this.$refs.JstproductModal as any).setShow(true);
      (this.$refs.JstproductModal as any).setType('sg');
      (this.$refs.JstproductModal as any).setValue(row);
    }
  }
  mounted() {
    // console.log('打印')
    this.getList()
    this.$nextTick(() => {
      this.height = (this as any).$el.offsetHeight;
      if(this.height > 200) {
        this.height = this.height - 50 - 50
      }
    })
  }
}
</script>

<style lang="scss" scoped>
.page-view{
  height: 100%;
  width: 100%;
  .page{
    height: 50px;
    display: flex;
    justify-content: flex-end;
    align-items: flex-end;
  }
  .tool{
    padding: 8px 16px;
    box-sizing: border-box;
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
}
</style>