<template>
  <div class="app-container">
    <h3 class="toolbar">
      <div class="tool">
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="handleDownloadBatch">批量下载</el-button>
        <!-- <el-button type="primary" plain icon="el-icon-download" size="mini" v-print="'print'">一键打印</el-button> -->
        <!-- <button v-print="'#printsArea'"></button> -->
      </div>
    </h3>
    <div id="printArea">
      <el-table v-loading="loading" :data="list" border @selection-change="handleSelectionChange" style="width: 100%" width="100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" type="index" width="50" align="center"></el-table-column>
        <el-table-column label="文件名称" prop="fileName" align="center"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" @click="loadFromUrl(scope.row)">查看</el-button>
            <el-button type="text" @click="handleDownload(scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"/>
    </div>
  </div>
</template>

<script>
  import axios from 'axios'
  import {getEnclosureApi,deleteEnclosureApi,getProjectInfoApi,getProjectInfoCommonApi} from '@/api/enterprise/project/project'
  // 先导入getLodop方法
  import { getLodop } from "@/plugins/lodopFuncs"
  export default {
    props: {
      finEnclosure: {
        type: String
      }
    },
    data() {
      return {
        // 加载状态跟踪
        loading: false,
        dialogVisible: false,
        total: 0,
        enclosureVisible: false,
        list: [],
        id: this.$route.query.id,
        dataId: undefined,
        attachType: 'PROJECT',
        selectionList: [],
        ids: '',
        info: {},
        pdfSrc: 'http://124.232.146.72:7015/api/profile/upload/88a09dbc8e2f4a6096e6ea3dc934ba77.xls',
        queryParams: {
          pageNum: 1,
          pageSize: 10
        },
        print: {
          id: 'printArea',
          popTitle: '', // 打印配置页上方的标题
          extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>,<style> #printMe { height: auto !important; } <style>', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
          preview: true, // 是否启动预览模式，默认是false
          previewTitle: '预览的标题', // 打印预览的标题
          previewPrintBtnLabel: '预览结束，开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
          zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
          // previewBeforeOpenCallback () { console.log('正在加载预览窗口！'); console.log(this.msg) }, // 预览窗口打开之前的callback
          // previewOpenCallback () { console.log('已经加载完预览窗口，预览打开了！') }, // 预览窗口打开时的callback
          // beforeOpenCallback () { console.log('开始打印之前！') }, // 开始打印之前的callback
          // openCallback () { console.log('执行打印了！') }, // 调用打印时的callback
          // closeCallback () { console.log('关闭了打印工具！') }, // 关闭打印的callback(无法区分确认or取消)
          // clickMounted () { console.log('点击v-print绑定的按钮了！') },
          // url: 'http://124.232.146.72:7015/api/profile/upload/88a09dbc8e2f4a6096e6ea3dc934ba77.xls', // 打印指定的URL，确保同源策略相同
          // asyncUrl (reslove) {
          //   setTimeout(() => {
          //     reslove('http://124.232.146.72:7015/api/profile/upload/88a09dbc8e2f4a6096e6ea3dc934ba77.xls')
          //   }, 2000)
          // },
          // standard: '',
          // extarCss: ''
        }
      };
    },
    created() {
      this.id = this.$route.params.id || undefined;
      this.getData()
    },
    methods: {
       // 获取打印机列表
       getPrintList() {
           let LODOP = getLodop();
           if (!LODOP)return
           // 获取打印机个数
           let count = LODOP.GET_PRINTER_COUNT()
           let printValue = LODOP.GET_PRINTER_NAME(-1) //获取默认打印机
           this.printList = Array(count).fill(null).map((...args) => {
               if (printValue === LODOP.GET_PRINTER_NAME(args[1])){
                   this.printDefault = args[1]
               }
               return {
                   value: args[1], // args[1]为数组索引
                   label: LODOP.GET_PRINTER_NAME(args[1]) // 获取打印机名称
               }
           })

       },
      getData() {
        getProjectInfoCommonApi(this.id).then(res => {
          this.info = res.data.finProject || {}
          this.dataId = this.info.id
          this.getList()
        })
      },
      getList() {
        if(this.finEnclosure == 'fin') {
          this.attachType = 'FINACIAL'
        }
        getEnclosureApi(this.attachType,this.dataId).then(res => {
          if(res.code == 200) {
            this.list = res.data.records
            this.total = res.data.total
          }
        })
      },
      handleBatchDelte() {
        if(this.selectionList.length <=0) {
          this.$message.error('请选择要删除的数据');
          return
        }
        this.$confirm('请确认是否删除所选择的数据！', '提示').then(() => {
        	deleteEnclosureApi(this.ids).then(res => {
            if(res.code == 200) {
              this.queryParams.pageNum = 1;
              this.getList();
              this.$modal.msgSuccess("删除成功");
            }
        	})
        })
      },
      handleDelete(row) {
        const id = row.id;
        this.$confirm('是否确认删除该数据?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
            return deleteEnclosureApi(id);
          }).then(() => {
            this.queryParams.pageNum = 1;
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
      },
      handleSelectionChange(val) {
        this.selectionList = val;
        if(this.selectionList.length > 0) {
          let selectionIds = []
          for (let i = 0, len = this.selectionList.length; i < len; i++) {
          	selectionIds.push(this.selectionList[i].id)
          }
          this.ids = selectionIds.join(',')
        }else {
          this.ids = ''
        }
      },
      handlePrint(row) {
        this.getPrintData(row.url)
      },
      // 获取面单信息数组数据
          async getPrintData(url) {
            if(url) {
             this.printUrlList = url.split(';')
             this.printInfo()
            }
          },
          // 打印面单
          async printInfo() {
            for await (const item of this.printUrlList) {
              this.printEveryItem(item)
            }
          },
          // 打印每项
          printEveryItem(item) {
            let self = this;
            let LODOP = getLodop(); //调用getLodop获取LODOP对象
            return new Promise(function (resolve) {
              setTimeout(() => {
               // LODOP.PRINT_INIT("");
               let strStyleCSS = `<style type='text/css' rel='stylesheet'>.img1{display:block;margin:10px;width:360;height:360}</style>`
               let html = `<head>${strStyleCSS}</head><body><div class='print-card'>
                      <img src=${item} class='img1' />
                  </div><body>`
               LODOP.ADD_PRINT_HTM(0,0,380,380,html);
               LODOP.SET_PRINT_PAGESIZE(1,1000,1000,"");
               LODOP.PRINT();
              }, 1000);
            });
          },
      handleDownloadBatch() {
        if(this.selectionList.length <=0) {
          this.$message.error('请选择要下载的数据');
          return
        }
        window.open("http://124.232.146.72:7015/api/common/attach/"+this.ids)
        this.getList();
      },
      handleDownload(row) {
        axios({
          method: 'get',
          responseType: 'blob',
          url: "http://124.232.146.72:7015/api/common/attach/"+row.id
        }).then(({data}) => {
          const blob = new Blob([data])
          let a = document.createElement("a")
          a.href = URL.createObjectURL(blob);
          a.download = row.fileName
          a.style.display = "none"; // 障眼法藏起来a标签
          document.body.appendChild(a); // 将a标签追加到文档对象中
          a.click(); // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
          a.remove();
        })
        // let name = row.fileName;
        // let url = row.url;
        // let suffix = url.substring(url.lastIndexOf("."), url.length);
        // const a = document.createElement('a');
        // a.setAttribute('download', name)
        // a.setAttribute('target', '_blank')
        // a.setAttribute('href', url)
        // a.click()
        // window.open("http://124.232.146.72:7015/api/common/attach/"+row.id)
      },
      // 从url加载
      loadFromUrl(row) {
        let routeUrl = this.$router.resolve({
          path: '/enclosurePreview',
          query: {url: row.url,fileName: row.fileName,id: row.id}
        });
        window.open(routeUrl.href, "_blank");
      }
    }
  };
  </script>

</script>

<style scoped>

</style>
