<template>
  <div>
    <div class="divborder newSearchDiv">
      <div class="filter">
        <label>{{$t('5500291')}}：</label>
        <Input class="searchInput MaxWidth" type="text" v-model="qrcode"/>
      </div>
      <div class="filter">
        <label>{{$t('5500274')}}：</label>
        <Select v-model="labeltype" label-in-value clearable class="searchSelect">
          <Option
            v-for="(item,index) in labeltypes"
            :value="item.dkey"
            :key="index"
          >{{item.dval}}</Option>
        </Select>
      </div>
      <div class="searchBtn">
        <Button type="primary" class="twoWord" icon="ios-search" @click="search()">{{$t('1001')}}</Button>
        <Button type="warning" class="twoWord" icon="ios-print-outline" @click="goprint()">{{$t('100077')}}</Button>
      </div>
    </div>
    <div class="divborder newTableDiv">
      <Table
          class="tableClass"
          @on-current-change="handleRowChange"
          @on-selection-change="handleSelectRow"
          highlight-row
          :data="tableData1"
          :columns="tableColumns1"
      ></Table>
      <div class="pageDiv">
          <div class="pageDirection">
          <Page
              :total="total"
              :current="page"
              :page-size="pagesize"
              @on-change="changePage"
              show-elevator
              show-sizer
              show-total
              @on-page-size-change="handlePageSize"
              :page-size-opts="[10,20,30,40,100]"
          ></Page>
          </div>
        </div>
    </div>

    <!-- 打印插件 -->
    <Modal
      class="newModalClass"
      :title="$t('5500098')"
      v-model="downloadexe"
      :styles="{width:'700px'}"
    >
      <div class="modal_body" style="width:700px!important;padding:0 20px;">
        <div style="width:660px;padding-left:5px;">
          <div>
            <div class="filter">
              <a
                href="/static/lodop/CLodop_Setup_for_Win32NT.exe"
              >{{$t('5500099')}}:CLodop_Setup_for_Win32NT.exe</a>
              <br />
              <a href="/static/lodop/install_lodop32.exe">{{$t('5500099')}}:install_lodop32.exe</a>
              <br />
              <a href="/static/lodop/install_lodop64.exe">{{$t('5500099')}}:install_lodop64.exe</a>
            </div>
          </div>
        </div>
      </div>
    </Modal>

    <!-- 打印弹窗 -->
    <Modal
      class="newModalClass"
      :title="$t('100077')"
      v-model="printModal"
      :styles="{width:'500px'}"
    >
      <div class="modal_body" style="width:500px!important;padding:0 20px;">
        <div style="width:500px;padding-left:5px;">
          <div>
            <div class="filter">
              <label>{{$t('5500285')}}：</label>
              <Select v-model="printmechine" label-in-value clearable class="searchSelect" @on-change="getPrint">
                <Option
                v-for="(item,index) in printmechines"
                :value="item.name"
                :key="index"
              >{{item.name}}</Option>
              </Select>
            </div>
            <!-- <Button type="primary" icon="ios-print-outline" @click="doprint()">打印</Button> -->
          </div>
          <div>

          </div>
        </div>
      </div>
      <div slot="footer">
          <Button type="text" size="large" @click="printModal=false">{{$t('1033')}}</Button>
          <Button type="primary" size="large" @click="doprint()">{{$t('100077')}}</Button>
      </div>
    </Modal>
    

  </div>
</template>
<script>
import axios from "@/libs/api.request";
import { getLodop } from '../../../static/Clodop/LodopFuncs';
export default {
  data(){
    return {
      downloadexe:false,
      printModal:false,
      printmechine:'',

      qrcode:'',
      labeltype:0,
      labeltypes:[],
      page:1,
      pagesize:10,
      total:0,
      tableData1:[],
      tableColumns1:[
        {
          type:'selection',
          key:''
        },
        {
          title:this.$t('1008'),
          key:'index',
          render:(h,params)=>{
            return h('span',
              params.index + (this.page - 1)*this.pagesize + 1
            )
          }
        },
        {
          title:this.$t('100089'),
          key:'product_code'
        },
        {
          title:this.$t('100088'),
          key:'product_name'
        },
        // {
        //   title:'物料编号',
        //   key:'pn'
        // },
        // {
        //   title:'物料名称',
        //   key:'name'
        // },
        {
          title:this.$t('100392'),
          key:'spec'
        },
        {
          title:this.$t('5500271'),
          key:'printtype',
          render:(h,params)=>{
            let printtype = ''
            if(params.row.printtype===1){
              printtype = this.$t('5500272')
            }else if(params.row.printtype===2){
              printtype = this.$t('5500273')
            }
            return h('span',printtype)
          }
        },
        {
          title:this.$t('5500274'),
          key:'lable_value'
        },
        {
          title:this.$t('950253'),
          key:'fileName',
          render:(h,params)=>{
            return h('span',
            {
              style:{
                color:'#57a3f3',
                cursor:'pointer'
              },
              on:{
                click:()=>{
                  let fileurl = params.row.filePath
                  if(fileurl===""||fileurl===null||fileurl===undefined){
                    return false;
                  }else{
                    let filetype = fileurl.split('.')[1];
                    if(filetype==='xlsx'||filetype==='xls'){
                      this.getExcelfile(params.row)
                    }
                    else if(filetype==='txt'){
                      this.getTxtfile(params.row)
                    }
                  }
                }
              }
            },params.row.fileName)
          }
        },
        {
          title:this.$t('920139'),
          key:'uid'
        },
        {
          title:this.$t('920138'),
          key:'transDateTime'
        }
      ],
      printmechines:[], //打印机列表
      selections:[]
    }
  },
  created(){
    this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1)
    this.getlabeltypes()
    this.search()
  },
  methods:{
    getTxtfile(file){
      axios
        .request({
          url: "/config/Download/DownloadFile?file_url=" + file.filePath,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret === 1) {
            var info = res.data.data;
            var content = info.content;
            // 创建隐藏的可下载链接
            var eleLink = document.createElement("a");
            eleLink.download = file.fileName;
            eleLink.style.display = "none";
            // 字符内容转变成blob地址
            var blob = new Blob([content]);
            eleLink.href = URL.createObjectURL(blob);
            // 触发点击
            document.body.appendChild(eleLink);
            eleLink.click();
            // 然后移除
            document.body.removeChild(eleLink);

          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    getExcelfile(item){
      var data = {
        productCode:item.product_code,
        section:item.line,
        result:'',
        sn:item.sn,
        id:item.productId, //产品id
        wo:item.wo,
        file_url:item.filePath
      }
      axios
        .request({
          url: "/acc/PrintLabelFile/TrackingDetail",
          data,
          method: "post",
        })
        .then((res) => {
          if (res.data.ret === 1) {
              window.location.href = axios.publicPath + '' + res.data.data;
          } else {
              this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    getlabeltypes(){
      axios
        .request({
          url: "/config/Dict/GetDictByCat?cat=labeltype",
          method: "get",
        })
        .then((res) => {
          this.labeltypes = []
          if (res.data.ret === 1 && res.data.data.length > 0) {
            this.labeltypes = res.data.data;
          }
        });
    },
    search(){
      this.page = 1
      this.pagesize = 10
      this.tosearch()
    },
    tosearch(){
      var data = {
        SN: this.qrcode,
        labeltype: this.labeltype,
        page:this.page,
        pagesize:this.pagesize
      };
      axios
        .request({
          url: "/acc/PrintLabelFile/GetCertificateList",
          data,
          method: "post",
        })
        .then((res) => {
          this.tableData1 = []
          this.total = 0
          if (res.data.ret === 1 &&res.data.data!=null&&res.data.data!=undefined&& res.data.data.length > 0) {
            this.tableData1 = res.data.data
            this.total = res.data.total
          }
        });
    },
    goprint(){
      //首先判断有没有装插件
      let LODOP = getLodop();
      if(LODOP === undefined){
        //请先安装打印插件
        this.downloadexe = true;
      }
      else
      {
        if(this.selections===null||this.selections===undefined||this.selections.length===0){
          this.$Message.error(this.$t('1017'))
          return false;
        }
        this.getPrintMachines()
        this.printModal = true
      }
    },
    doprint(){
      if(this.printmechine===""||this.printmechine===null||this.printmechine===undefined){
        this.$Message.error(this.$t('5500289'))
        return false;
      }
      if(this.selections.length > 0){
        let arr_e = []
        let arr_t = []
        let productcode = ''
        let sn = ''
        let ModelList = []
        this.selections.forEach((item,index)=>{
          productcode = item.product_code
          sn = item.sn
          let fileurl = item.filePath
          if(fileurl!=''||fileurl!=null||fileurl!=undefined){
            let filetype = fileurl.split('.')[1];
            let arr = {}
            if(filetype==='txt'){
              arr.labletype = item.labeltype
              arr.printtype = item.printtype
              ModelList.push(arr)
            }else if(filetype==='xlsx'||filetype==='xls'){
              arr_e.push(item)
            }
          }
        })
        //下载execl
        if(arr_e.length > 0){
          for(var i in arr_e){
            this.getExcelfile(arr_e[i])
          }
        }

        //打印txt
        var data = {
          productcode:productcode,
          sn:sn,
          ModelList:ModelList
        }
        axios
        .request({
          url: "/acc/PrintRelation/PrintCertificateLable",
          data,
          method: "post",
        })
        .then((res) => {
          let dataArr = res.data.data
          if (res.data.ret === 1 && dataArr!=null&&dataArr!=undefined&& dataArr.length >0) {
            LODOP.PRINT_INIT('打印');
            for (var i = 0; i < dataArr.length; i++) {
              LODOP.NewPage();
              let strData = dataArr[i];
//                 let strData = `CT~~CD,~CC^~CT~
// ^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^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d7+D0dz4Yh7hfBvnj/Y55FzOOdZ7jAl5wK3tc2jSe9X5eJvZru7ao37o51FkC2XbFynWs1kTSnaKP5epsTlnQV7SxziqBp9+5tTc3YHpti+8f/kUpf6z3oFNI8wng==:A748
// ^PQ1,0,1,Y^XZ
// `;
              LODOP.SET_PRINT_MODE("SEND_RAW_DATA_ENCODE","UTF-8");//UTF-8 UTF-7 UNICODE ANSI UTF-16 UTF-16BE GBK BIG5 EUC-JP
              LODOP.SEND_PRINT_RAWDATA(strData);
            }
          }else{
            // this.$Message.error(this.$t(res.data.msg));
          }
        });
      }
    },
    getPrintMachines(){
      let LODOP = getLodop();
      //获取本地打印机的个数
      let printnum = LODOP.GET_PRINTER_COUNT();
      if(printnum > 0){
        for(let i=0;i<9;i++){
          let name = LODOP.GET_PRINTER_NAME(i);
          this.printmechines.push({
            index:i,
            name:name
          })
        }
      }
      //获取默认打印机
      let pname = LODOP.GET_PRINTER_NAME(-1);
      this.printmechine = pname
    },
    getPrint(info){
      //设置默认打印机
      let pname = info.value;
      LODOP.SET_PRINT_MODE("WINDOW_DEFPRINTER",pname);
    },
    handleRowChange(currentRow, oldCurrentRow) {
        this.detailobj = currentRow;
    },
    handleSelectRow: function (data) {
        this.selections = data;
    },
    changePage(value) {
        this.page = value;
        this.search();
    },
    handlePageSize(value) {
        this.pagesize = value;
        this.search();
    },
  }
}
</script>
<style>

</style>
