<template>
  <!-- 体系文件管理 -->
  <div class="file_manage_wrap">
    <header class="header_wrap">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="文件名称" label-width="65px">
          <el-input type="text" size="mini" v-model="searchForm.fileName" clearable></el-input>
        </el-form-item>
        <!-- <el-form-item label="文件时间">
          <el-date-picker v-model="searchForm.time" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" size="small" style="width: 300px" format="yyyy-MM-dd" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label-width="0">
          <el-button type="primary" size="mini" @click="fileDataSearch">查询</el-button>
          <el-button type="primary" size="mini">重置</el-button>
        </el-form-item>
      </el-form>
    </header>
    <el-row :gutter="24" class="main_container">
      <el-col :span="4">
        <aside class="aside_wrap examination" :style="{ height: treeHeight + 'px' }">
          <div class="common-title-name">
            <img style="width: 25px; height: 25px" src="../../../../assets/img/imgScreen/logo.png" />
            <span>文件分类</span>
          </div>
          <el-tree ref="menuTree" :data="menuTree" :props="defaultProps" node-key="id" class="tree_wrap"
            v-loading="treeLoading" :default-expanded-keys="expandedKeys" @node-expand="expandNode"
            @node-collapse="expandCollapse" :expand-on-click-node="true" @node-click="nodeClick"
            :style="{ height: treeHeight + 'px' }">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span :style="data.status === '0' || node.parent.data.status === '0'
                ? 'color: #a09e9e;'
                : ''
                ">{{ node.label }}</span>
              <!-- <span class="nodeOperate contextmenu">
                <el-dropdown @command="handleCommand" :hide-on-click="false">
                  <span class="el-dropdown-link">
                    <i
                      class="el-icon-arrow-down icore-icon-size"
                      style="color: #111; background-color: #61f06e"
                    ></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-row>
                      <el-dropdown-item
                        :command="{ str: 'add', node: node, data: data }"
                        class="el-icon-plus addMenuPr"
                        >添加</el-dropdown-item
                      >
                    </el-row>
                    <el-row>
                      <el-dropdown-item
                        :command="{ str: 'edit', node: node, data: data }"
                        class="el-icon-edit editMenuPr"
                        >修改</el-dropdown-item
                      >
                    </el-row>
                    <el-row>
                      <el-dropdown-item
                        :command="{ str: 'delete', node: node, data: data }"
                        class="el-icon-delete delMenuPr"
                        >删除</el-dropdown-item
                      >
                    </el-row>
                  </el-dropdown-menu>
                </el-dropdown>
              </span> -->
            </span>
          </el-tree>
        </aside>
      </el-col>
      <el-col :span="20">
        <div class="common-title-name section_top">
          <img style="width: 25px; height: 25px" src="../../../..//assets/img/imgScreen/logo.png" />
          <span style="font-size: 18px">记录信息</span>
        </div>
        <el-table v-loading="recordDataLoading" ref="recordTable" highlight-current-row border
          :icore-filter-flag="icoreFilterFlag" :height="tableHeight" :data="recordDataList">
          <el-table-column type="index" label="NO" align="center"></el-table-column>
          <!-- <el-table-column type="selection" align="center"></el-table-column> -->
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="fileDate" label="文件日期"
            align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="fileName" label="文件名称"
            align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="filePath01" label="附件"
            align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="filePath01" label="下载/预览"
            align="center"><template slot-scope="scope">
              <el-tooltip content="下载" placement="bottom" effect="light">
                <el-button :disabled="!scope.row.filePath01" type="goon" size="mini" icon="el-icon-download" circle
                  @click="
                    imgPreViewAll(
                      scope.row,
                      scope.row.filePath01
                    )
                    ">
                </el-button>
              </el-tooltip>
              <el-tooltip content="预览" placement="bottom" effect="light">
                <el-button :disabled='!scope.row.filePath01' type="warning" size="mini" icon="el-icon-view" circle
                  @click="imgPreViewYAll(scope.row, scope.row.filePath01)">
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="memo" label="备注"
            align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="createTime" label="创建日期"
            align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="createMan" label="创建人"
            align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="updateTime" label="修改时间"
            align="center"></el-table-column>
          <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="updateMan" label="修改人"
            align="center"></el-table-column>
        </el-table>
        <div class="common-foot-style">
          <el-pagination v-loading="recordDataLoading" @size-change="recordPageSizeChange"
            @current-change="recordPageCurrentChange" :current-page="recordPage.pageIndex"
            :page-sizes="[10, 20, 50, 100, 200]" :page-size="recordPage.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="recordPage.tableTotal" background>
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <div id="docx">
      <div ref="file"></div>
    </div>
    <div id="xlsx">
      <el-tabs v-model="activeName" v-if="DialogVisible" type="border-card">
        <el-tab-pane v-for="(item, index) in excelSheet" :key="index" :label="item.name" :name="item.name">
          <div class="table" v-html="item.innerHTML"></div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { formatDate, getCookie } from '@/utils/util.js';
import { cookieUserId, cookieUserName } from '@/config/config.js';
import pdf from 'vue-pdf'
import XLSX from 'xlsx';
let docx = require("docx-preview");
export default {
  data() {
    return {
      searchForm: {
        fileName: '',
        time: []
      },
      defaultProps: {
        children: 'children',
        label: 'className'
      },
      srcUrl: '',
      pdfPages: null,
      menuTree: [], // 分类数据
      treeLoading: false,
      expandList: [],
      expandedKeys: [],
      icoreFilterFlag: true,
      treeHeight: 500,
      // tableau: '',
      DialogVisible: false,
      excelSheet: [],
      activeName: '',

      recordDataLoading: false,
      recordDataList: [],
      recordPage: {
        pageIndex: 1,
        pageSize: 50,
        tableTotal: 0
      },
      imgPreViews: '',
      action_prod: window.location.protocol + '//' + window.location.host,
    }
  },
  created() {
    this.treeHeight = window.innerHeight - 200
    this.tableHeight = window.innerHeight - 110
    // this.searchForm.time = [this.getYNM(new Date()) , this.getYNM(new Date())]
    this.init()
  },
  mounted() {

  },
  methods: {
    getYNM(date) {
      let year = date.getFullYear().toString();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      return `${year}-${month}-${day}`;
    },
    // 初始化节点
    init() {
      this.searchTypeData()
    },
    // 重新查询节点数据
    async searchTypeData() {
      let param = {
        pageNum: '1',
        pageSize: 10000,
        object: {
          className: ''
        }
      }
      const data = await this.axios.post(`pass/baseManagement/v1/limsisoclasss/queryLimsClassPage`, {}, { individualType: 'json' })
      const list = this.getTypeList(data.data.list, { id: 'classNo', parentId: 'parentNo' })
      if (data.data.list.length > 0) {
        this.recordDataSearch(data.data.list[0].classNo);
      }
      this.menuTree = [...list]
    },
    // 文件记录信息查询
    async recordDataSearch(classNo, flag = true) {
      if (flag) {
        this.recordPage.pageIndex = 1
      }
      let startTime = ''
      let endTime = ''
      // if (!this.searchForm.time) {
      //   startTime = ''
      //   endTime = ''
      // } else {
      //   startTime = formatDate(this.searchForm.time[0], "yyyy-MM-dd") + ' 00:00:00'
      //   endTime = formatDate(this.searchForm.time[1], "yyyy-MM-dd") + ' 23:59:59'
      // }
      let param = {
        ...this.recordPage,
        classNo: classNo,
        startTime: startTime,
        endTime: endTime,
        fileName: this.searchForm.fileName,
        tenantNo: '2'
      }
      this.recordDataLoading = true;
      const data = await this.axios.post(`pass/baseManagement/v1/limsisofileds/queryLimsIsoFileDByClassNoPage`, param, { individualType: 'json' })
      if (data.status == 'succeed') {
        this.recordDataLoading = false;
        this.recordDataList = [...data.data.list]
        this.recordPage.tableTotal = data.data.total
      } else {
        this.recordDataLoading = false;
        this.recordDataList = []
      }
    },
    // 数展开
    expandNode(data, node, item) {
      if (this.expandList.indexOf(data.id) === -1) {
        this.expandList.push(data.id)
      }
    },
    expandCollapse(data, node, item) {
      let index = this.expandList.indexOf(data.id)
      if (index !== -1) {
        this.expandList.splice(index, 1)
      }
    },
    //  点击树事件
    nodeClick(item, el) {
      //  点击时为编辑状态
      this.operateStatus = 'edit';
      // 记录点击节点id
      this.selectedNode = { ...item }
      // 查询该节点下方的子节点
      this.recordDataSearch(item.classNo)
    },
    treeObj(o) {
      let obj = {};

      for (let key in o) {
        var val = o[key];
        // 排除为null的数据的干扰
        val = val === null ? '' : val
        obj[key] = typeof val === 'object' ? this.treeObj(val) : val;
      }
      //对象新增children键值，用于存放子树
      obj.children = [];
      return obj;
    },
    // 迭代将分类数据组成树形结构
    getTypeList(list, attributes) {
      let that = this
      let paramList = [...list]
      let topList = []
      for (let i = 0; i < paramList.length; i++) {
        if (paramList[i][attributes.parentId] === '' || paramList[i][attributes.parentId] === null) {
          topList.push(this.treeObj(paramList[i]))
          paramList.splice(i, 1);
          i--
        }
      }
      for (let i = 0; i < topList.length - 1; i++) {
        for (let j = 0; j < topList.length - i - 1; j++) {
          if (topList[j].dspOrder > topList[j + 1].dspOrder) {
            let arr = topList[j + 1];
            topList[j + 1] = topList[j];
            topList[j] = arr;
          }
        }
      }
      run(topList);
      //找寻子树
      function run(chiArr) {
        if (paramList.length !== 0) {
          for (let i = 0; i < chiArr.length; i++) {
            for (let j = 0; j < paramList.length; j++) {
              if (chiArr[i][attributes.id] === paramList[j][attributes.parentId]) {
                let obj = that.treeObj(paramList[j]);
                chiArr[i].children.push(obj);
                paramList.splice(j, 1);
                j--;
              }
            }
            run(chiArr[i].children);
          }
        }
      }
      topList.forEach(item => {
        for (let t in item) {
          if (t !== 'children' && typeof item[t] === 'object') {
            item[t] = ''
          }
        }
      })
      return topList;
    },
    imgPreView(row, fileName) {
      this.axios.get('pass/baseManagement/v1/file/download/' + fileName, { responseType: 'blob' }, { headers: { 'content-type': 'application/x-www-form-urlencoded' } }).then(res => {
        let blob = new Blob([res]);
        let elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.target = "_blank";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL对象
        document.body.removeChild(elink);
      }).catch(e => {
        return this.$message.error(e.message)
      })
    },
    imgPreViewAll(row, fileName) {
      this.axios.get('pass/baseManagement/v1/file/downloadAll?coverFileName=' + row.memo3 + "&contentFileName=" + row.filePath01, { responseType: 'blob' }, { headers: { 'content-type': 'application/x-www-form-urlencoded' } }).then(res => {
        let blob = new Blob([res]);
        let elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.target = "_blank";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL对象
        document.body.removeChild(elink);
      }).catch(e => {
        return this.$message.error(e.message)
      })
    },
    imgPreViewY(row, fileName) {
      let aaa = fileName.substr(fileName.indexOf(".") + 1);
      if (aaa == "docx") {
        this.axios.get('pass/baseManagement/v1/file/download/' + fileName, { responseType: 'blob' }, { headers: { 'content-type': 'application/x-www-form-urlencoded' } }).then(res => {
          this.showFlag(true);
          docx.renderAsync(res, this.$refs.file)
        }).catch(e => {
          return this.$message.error(e.message)
        })
      } else if (aaa == "pdf") {
        this.axios.get('pass/baseManagement/v1/file/download/' + fileName, { responseType: 'blob' }, { headers: { 'content-type': 'application/x-www-form-urlencoded' } }).then(res => {
          const binaryData = [];
          binaryData.push(res);
          this.srcUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }))
          window.open(this.srcUrl);
        }).catch(e => {
          return this.$message.error(e.message)
        })
      } else if (aaa == "xlsx") {
        this.axios.get('pass/baseManagement/v1/file/download/' + fileName, { responseType: 'arraybuffer' }, { headers: { 'content-type': 'application/x-www-form-urlencoded' } }).then(res => {
          this.excelSheet = [];
          this.showFlag(false);
          let workbook = XLSX.read(new Uint8Array(res), { type: "array" });
          this.tableToHtml(workbook);
        }).catch(e => {
          return this.$message.error(e.message)
        })
      } else {
        docx.renderAsync(new Blob(), this.$refs.file)
        return this.$message.error("不支持这个类型的文件展示！")
      }
    },
    imgPreViewYAll(row, fileName) {
      let aaa = fileName.substr(fileName.indexOf(".") + 1);
      if (aaa == "docx") {
        this.axios.get('pass/baseManagement/v1/file/downloadAll?coverFileName=' + row.memo3 + "&contentFileName=" + row.filePath01, { responseType: 'blob' }, { headers: { 'content-type': 'application/x-www-form-urlencoded' } }).then(res => {
          this.showFlag(true);
          docx.renderAsync(res, this.$refs.file)
        }).catch(e => {
          return this.$message.error(e.message)
        })
      } else if (aaa == "pdf") {
        this.axios.get('pass/baseManagement/v1/file/downloadAll?coverFileName=' + row.memo3 + "&contentFileName=" + row.filePath01, { responseType: 'blob' }, { headers: { 'content-type': 'application/x-www-form-urlencoded' } }).then(res => {
          const binaryData = [];
          binaryData.push(res);
          this.srcUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }))
          window.open(this.srcUrl);
        }).catch(e => {
          return this.$message.error(e.message)
        })
      } else if (aaa == "xlsx") {
        this.axios.get('pass/baseManagement/v1/file/downloadAll?coverFileName=' + row.memo3 + "&contentFileName=" + row.filePath01, { responseType: 'arraybuffer' }, { headers: { 'content-type': 'application/x-www-form-urlencoded' } }).then(res => {
          this.excelSheet = [];
          this.showFlag(false);
          let workbook = XLSX.read(new Uint8Array(res), { type: "array" });
          this.tableToHtml(workbook);
        }).catch(e => {
          return this.$message.error(e.message)
        })
      } else {
        docx.renderAsync(new Blob(), this.$refs.file)
        return this.$message.error("不支持这个类型的文件展示！")
      }
    },
    tableToHtml(workbook) {
      const sheetList = workbook.SheetNames.filter(v => v.indexOf('数据源') === -1);
      this.activeName = sheetList[0];
      sheetList.forEach(sheet => {
        const worksheet = workbook.Sheets[sheet];
        if (worksheet) {
          const innerHTML = XLSX.utils.sheet_to_html(worksheet);
          this.excelSheet.push({
            name: sheet,
            innerHTML: innerHTML
          });
        } else {
          this.excelSheet.push({
            name: sheet,
            innerHTML: '暂无数据',
          });
        }
      });
      this.DialogVisible = true;
    },
    //查询
    fileDataSearch() {
      this.searchTypeData();
    },
    // 上下文菜单命令选择
    handleCommand(command) {
      let that = this,
        str = command.str,
        node = command.node,
        data = command.data;
      this.selectedNode = { ...data }
      switch (str) {
        case 'add':
          that.showTypeDialog('add');
          break;
        case 'delete':
          that.deleteTypeData(node, data);
          break;
        case 'edit':
          that.showTypeDialog('edit');
          break;
      }
    },
    showFlag(docx) {
      if (docx) {
        document.getElementById("docx").style.display = "block";
        document.getElementById("xlsx").style.display = "none";
      } else {
        document.getElementById("docx").style.display = "none";
        document.getElementById("xlsx").style.display = "block";
      }
    },
    recordPageSizeChange(size) {
      this.recordPage.pageSize = size;
      this.recordDataSearch(this.selectedNode.classNo);
    },
    recordPageCurrentChange(index) {
      this.recordPage.pageIndex = index;
      this.recordDataSearch(this.selectedNode.classNo, false);
    }
  }
}
</script>

<style>
.file_manage_wrap {
  padding: 5px 10px;
  height: inherit;
}

.header_wrap {
  padding: 5px 10px 0px 40px;
  border-bottom: 1px solid #efefef;
}

.main_container {
  padding: 12px 5px 0 10px;
  height: inherit;
}

.tree_wrap {
  padding-top: 15px;
}

.section_wrap .section_top {
  padding: 10px 5px;
}

.aside_wrap {
  padding: 10px 5px;
}

.custom-tree-node {
  -webkit-box-flex: 1;
  display: flex;
  -webkit-box-align: center;
  align-items: center;
  -webkit-box-pack: justify;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  flex: 1 1 0%;
}

.type_dialog_wrap {
  width: 520px !important;
}

.file_manage_wrap .el-dialog__header {
  height: 56px;
  background: rgb(64, 158, 255);
  border-radius: 4px 4px 0 0;
  color: #fff;
  padding: 14px 24px !important;
}

.file_manage_wrap .el-dialog__footer {
  text-align: center;
}

.file_manage_wrap .el-icon-date {
  display: none;
}

.file_manage_wrap .el-input__inner {
  padding: 2px 7px !important;
}
</style>
