<template>
  <!-- 体系模板管理 -->
  <div class="file_manage_wrap">
    <header class="header_wrap">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="体系模板名称" label-width="95px">
          <el-input
            type="text"
            size="mini"
            v-model="searchForm.isoName"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label-width="0">
          <el-button type="primary" size="mini" @click="searchTemplateData"
            >查询</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="24">
        <!-- 模板信息表 -->
        <section class="section_wrap examination">
          <div class="common-title-name section_top">
            <img
              style="width: 25px; height: 25px"
              src="../../../..//assets/img/imgScreen/logo.png"
            />
            <span>模板信息</span>
            <el-button
              icon="el-icon-circle-plus-outline"
              type="primary"
              :loading="addLoading"
              size="mini"
              @click="showFAddDialog"
              >新增</el-button
            >
            <el-button
              icon="el-icon-edit"
              type="primary"
              :loading="editLoading"
              size="mini"
              @click="showFEditDialog"
              >修改</el-button
            >
            <el-button
              icon="el-icon-remove-outline"
              type="danger"
              :loading="dropLoading"
              size="mini"
              @click="deleteFileData"
              >删除</el-button
            >
          </div>
          <el-table
            v-loading="dataLoading"
            ref="templateTable"
            highlight-current-row
            border
            @row-click="templateRowChange"
            @selection-change="templateSelectChange"
            :icore-filter-flag="icoreFilterFlag"
            :height="300"
            :data="templateDataList"
          >
            <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="isoStdNo"
              label="体系编号"
              align="center"
            ></el-table-column>
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="isoName"
              label="体系名称"
              align="center"
            ></el-table-column>
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="isoTypeName"
              label="体系类别"
              align="center"
            ></el-table-column>
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="isoDesc"
              label="体系描述"
              align="center"
            ></el-table-column>
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="companyName"
              label="管理单位"
              align="center"
            ></el-table-column>
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="deptName"
              label="管理车间"
              align="center"
            ></el-table-column>
            <!-- <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="sectionName"
              label="管理班组"
              align="center"
            ></el-table-column> -->
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="startTime"
              label="生效日期"
              align="center"
            ></el-table-column>
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="endTime"
              label="失效日期"
              align="center"
            ></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="filePath"
              label="文件"
              align="center"
            ></el-table-column> -->
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="filePath"
              label="下载/预览"
              align="center"
            ><template slot-scope="scope">
              <el-tooltip
                content="下载"
                placement="bottom"
                effect="light"
              >
                <el-button
                  :disabled="!scope.row.filePath"
                  type="goon"
                  size="mini"
                  icon="el-icon-download"
                  circle
                  @click="
                      imgPreView(
                        scope.row,
                        scope.row.filePath
                      )
                    "
                >
                </el-button>
              </el-tooltip>
              <el-tooltip
                        content="预览"
                        placement="bottom"
                        effect="light"
                      >
                      <el-button
                          :disabled='!scope.row.filePath'
                          type="warning"
                          size="mini"
                          icon="el-icon-view"
                          circle
                          @click="imgPreViewY(scope.row,scope.row.filePath)"
                      >
                      </el-button>
                </el-tooltip>
            </template>
            </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="dataLoading"
              @size-change="templatePageSizeChange"
              @current-change="templatePageCurrentChange"
              :current-page="templatePage.pageIndex"
              :page-sizes="[10, 20, 50, 100, 200]"
              :page-size="templatePage.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="templatePage.totalPage"
              background
            >
            </el-pagination>
          </div>
        </section>
        <!-- 模板节点信息表 -->
        <section class="section_wrap examination">
          <div class="common-title-name section_top">
            <img
              style="width: 25px; height: 25px"
              src="../../../..//assets/img/imgScreen/logo.png"
            />
            <span>模板节点</span>
            <el-button
              icon="el-icon-circle-plus-outline"
              type="primary"
              :loading="addLoading"
              size="mini"
              @click="showARecordDialog"
              >新增</el-button
            >
            <el-button
              icon="el-icon-edit"
              type="primary"
              :loading="editLoading"
              size="mini"
              @click="showERecordDialog"
              >修改</el-button
            >
            <el-button
              icon="el-icon-remove-outline"
              type="danger"
              :loading="dropLoading"
              size="mini"
              @click="deleteRecordData"
              >删除</el-button
            >
          </div>
          <el-table
            v-loading="nodeLoading"
            ref="nodeTable"
            highlight-current-row
            border
            @row-click="nodeRowChange"
            @selection-change="nodeSelectChange"
            :icore-filter-flag="icoreFilterFlag"
            :height="300"
            :data="nodeDataList"
          >
            <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="isoItemName"
              label="项目名称"
              align="center"
            ></el-table-column>
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="dataTypeName"
              label="数据类型"
              align="center"
            ></el-table-column>
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="doOrder"
              label="执行顺序"
              align="center"
            ></el-table-column>
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="optName"
              label="执行岗位"
              align="center"
            ></el-table-column>
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="itemSit"
              label="项目位置"
              align="center"
            ></el-table-column>
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="valueSit"
              label="默认值"
              align="center"
            ></el-table-column>
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="doValue"
              label="签名填入值"
              align="center"
            ></el-table-column>
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="adjustValue"
              label="签名时间填入值"
              align="center"
            ></el-table-column>
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="memo1"
              label="通知人账号"
              align="center"
            ></el-table-column>
            <el-table-column
              sortable
              :show-overflow-tooltip="true"
              min-width="80px"
              prop="filePath"
              label="下载/预览"
              align="center"
            ><template slot-scope="scope">
              <el-tooltip
                content="下载"
                placement="bottom"
                effect="light"
              >
                <el-button
                  :disabled="!scope.row.filePath"
                  type="goon"
                  size="mini"
                  icon="el-icon-download"
                  circle
                  @click="
                      imgPreView(
                        scope.row,
                        scope.row.filePath
                      )
                    "
                >
                </el-button>
              </el-tooltip>
              <el-tooltip
                        content="预览"
                        placement="bottom"
                        effect="light"
                      >
                      <el-button
                          :disabled='!scope.row.filePath'
                          type="warning"
                          size="mini"
                          icon="el-icon-view"
                          circle
                          @click="imgPreViewY(scope.row,scope.row.filePath)"
                      >
                      </el-button>
                </el-tooltip>
            </template>
            </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="nodeLoading"
              @size-change="nodePageSizeChange"
              @current-change="nodePageCurrentChange"
              :current-page="nodePage.pageIndex"
              :page-sizes="[10, 20, 50, 100, 200]"
              :page-size="nodePage.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="nodePage.totalPage"
              background
            >
            </el-pagination>
          </div>
        </section>
      </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>
    <!-- 模板信息编辑弹窗 -->
    <template-alert-components
      :type="templateDialogTitle"
      :templateShowFlag="templateDialogVisible"
      :baseData="selectedData"
      @close="closeDialog('template')"
    >
    </template-alert-components>
    <!-- 模板节点编辑弹窗 -->
    <node-alert-components
      :type="nodeDialogTitle"
      :nodeShowFlag="nodeDialogVisible"
      :recordData="nodeData"
      @close="closeDialog('node')"
    >
    </node-alert-components>
  </div>
</template>

<script>
import templateAlertComponents from './templateAlertComponents.vue'
import nodeAlertComponents from './nodeAlertComponents.vue'
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: {
        isoName: '' // 体系模板名称
      },
      expandList: [],
      expandedKeys: [],
      treeHeight: 500,
      srcUrl: '',
      addLoading: false,
      editLoading: false,
      dropLoading: false,
      addLoading1: false,
      editLoading1: false,
      dropLoding1: false,
      dataLoading: false,
      nodeLoading: false,
      icoreFilterFlag: true,
      nodeDataList: [],
      templateDataList: [],
      selectedData: {},
      nodeData: {},
      templateDialogVisible: false,
      typeData: {
        parentNo: '',
        parentName: '',
        classNo: '',
        className: '',
        memo: ''
      },
      typeDataCache: {
        parentNo: '',
        parentName: '',
        classNo: '',
        className: '',
        memo: ''
      },
      templateDialogTitle: '新增文件信息',
      nodeDialogTitle: '新增文件记录信息',
      nodeDialogVisible: false,
      selectedTemList: [],
      selectedNodeList: [],
      testPostNameType:[],//岗位信息
      activeName: '',
      DialogVisible: false,
      excelSheet: [],
      templatePage: {
        pageIndex: 1,
        pageSize: 50,
        totalPage: 0
      },
      nodePage: {
        pageIndex: 1,
        pageSize: 50,
        totalPage: 0
      },
      tableHeight: 250
    }
  },
  created () {
    this.treeHeight = window.innerHeight - 200
    this.tableHeight = (window.innerHeight - 240) / 2 > 200 ? (window.innerHeight - 240) / 2 : 200
    this.init()
  },
  mounted () {
    this.gettestPostNameTypeList ()
  },
  methods: {
    getCode (code, arr, codeKey, nameKey) {
      if (!code) {
        return '';
      }
      let targetRow = arr.find(item => {
        return item[codeKey] === code;
      });
      return targetRow ? targetRow[nameKey] : '';
    },
    gettestPostNameTypeList () {
          let obj ={
        'object':{validFlag:1},
        'pageIndex':1,
        'pageSize':99999
      }
      this.axios.post('pass/baseManagement/v1/limsbaseposts/queryLimsBasePostPage/',obj, {individualType: 'json'}).then(res => {
        this.testPostNameType = res.data.list;
      })
    },
    // 初始化节点
    init () {
      this.searchTemplateData()
    },
    // 查询模板数据
    async searchTemplateData (isoNo,flag = true) {
      if (flag) {
        this.templatePage.pageIndex = 1
      }
      let param = {
        ...this.templatePage,
        object: {
          isoNo: isoNo
        }
      }
      const data = await this.axios.post(`pass/baseManagement/v1/limsisotmps/queryLimsIsoTmpPage`, param, { individualType: 'json' })
      if (data.status == 'succeed') {
        this.templateDataList = [...data.data.list]
        this.templatePage.totalPage = data.data.total - 0
        this.searchNodeData(this.templateDataList[0].isoNo)
      } else {
        this.templateDataList = []
        this.templatePage.totalPage = 0
      }
    },
    // 查询模板节点数据
    async searchNodeData (isoNo, flag = true) {
      if (flag) {
        this.nodePage.pageIndex = 1
      }
      let param = {
        ...this.nodePage,
        object: {
          isoNo : isoNo
        }
      }
      const data = await this.axios.post(`pass/baseManagement/v1/limsisotmpds/queryLimsIsoTmpDPage`, param, { individualType: 'json' })
      if (data.status == 'succeed') {
        this.nodeDataList = [...data.data.list]
        this.nodeDataList.forEach(res=>{
          res.optName = this.getCode(res.optNo,this.testPostNameType,'postNo','postName')
        })
        this.nodePage.totalPage = data.data.total - 0
      } else {
        this.nodeDataList = []
        this.nodePage.totalPage = 0
      }
    },
    // 数展开
    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) {
      let that = this;
      //  点击时为编辑状态
      this.operateStatus = 'edit';
      this.typeData = { ...item }
    },
    // 显示模板信息新增窗口
    showFAddDialog () {
      this.selectedData = {}
      this.templateDialogTitle = '新增体系模板信息'
      this.templateDialogVisible = true
    },
    // 显示模板信息编辑窗口
    showFEditDialog () {
      // 如果没有选中的数据不允许编辑模板信息
      this.templateDialogTitle = '编辑体系模板信息'
      if (!this.selectedData.isoNo || this.selectedData.isoNo - 0 === 0) {
        return this.$message.warning('请先选择要编辑的模板信息')
      }
      this.templateDialogVisible = true
    },
    // 删除模板信息
    async deleteFileData () {
      if (this.selectedTemList.length === 0) {
        return this.$message.warning('请先选择要进行删除的体系模板数据')
      }
      const confirmResult = await this.MessageBox.confirm('确认要删除选择的体系模板数据吗？').catch(() => 'cancel')
      let ids = []
      this.selectedTemList.forEach(item => {
        ids.push(item.id)
      })
      if (confirmResult !== 'cancel') {
        const deleteResult = await this.axios.post('pass/baseManagement/v1/limsisotmps/delete', ids, { individualType: 'json' })
        if (deleteResult.status == 'succeed') {
          this.$message.success('删除成功')
          this.searchTemplateData()
        } else {
          this.$message.error(data.data)
        }
      }
    },
    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";
      }
    },
    imgPreViewY(row,fileName){
      let aaa = fileName.substr(fileName.indexOf(".")+1);
      this.axios.get('pass/baseManagement/v1/file/download/' + fileName,{responseType: 'blob'},{headers: {'content-type': 'application/x-www-form-urlencoded'}}).then(res => {
        if(aaa == "docx"){
          this.showFlag(true);
          docx.renderAsync(res,this.$refs.file)
        }else if(aaa == "pdf"){
          const binaryData = [];
          binaryData.push(res);
          this.srcUrl = window.URL.createObjectURL(new Blob(binaryData,{ type: 'application/pdf' }))
          window.open(this.srcUrl);
        }else if(aaa == "xlsx"){
          this.excelSheet = [];
          this.showFlag(false);
          let workbook = XLSX.read(new Uint8Array(res), {type:"array"});
          this.tableToHtml(workbook);
        }else{
          return this.$message.error("不支持这个类型的文件展示！")
        }
      }).catch(e => {
        return this.$message.error(e.message)
      })
    },
    imgPreView(row,fileName){
      console.log(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)
      })
    },
    // 显示节点信息新增窗口
    showARecordDialog () {
      // 如果没有选中文件信息不允许新增记录信息
      if (!this.selectedData.id || this.selectedData.id - 0 === '') {
        return this.$message.warning('请先选择要新增节点信息的模板')
      }
      this.recordDialogTitle = '新增模板节点信息'
      this.nodeData = { isoNo: this.selectedData.id }
      this.nodeDialogVisible = true
    },
    // 显示节点信息编辑窗口
    showERecordDialog () {
      this.recordDialogTitle = '编辑模板节点信息'
      if (JSON.stringify(this.nodeData) === '{}') {
        return this.$message.warning('请先选择要进行编辑的记录信息')
      }
      this.nodeDialogVisible = true
    },
    // 删除节点信息
    async deleteRecordData () {
      if (this.selectedNodeList.length === 0) {
        return this.$message.warning('请先选择要进行删除的体系模板数据')
      }
      const confirmResult = await this.MessageBox.confirm('确认要删除选择的体系模板数据吗？').catch(() => 'cancel')
      let ids = []
      this.selectedNodeList.forEach(item => {
        ids.push(item.id)
      })
      if (confirmResult !== 'cancel') {
        const deleteResult = await this.axios.post('pass/baseManagement/v1/limsisotmpds/delete', ids, { individualType: 'json' })
        if (deleteResult.status == 'succeed') {
          this.$message.success('删除成功')
          this.searchNodeData(this.selectedData.isoNo)
        } else {
          this.$message.error(data.data)
        }
      }
    },
    // 模板行点击
    templateRowChange (row) {
      this.selectedData = { ...row }
      // this.$refs.templateTable.toggleRowSelection(row, true);
      this.searchNodeData(row.isoNo)
    },
    // 模板行选中
    templateSelectChange (list) {
      this.selectedTemList = []
      list.forEach(item => {
        this.selectedTemList.push({ ...item })
      })
      if (list.length > 0) {
        this.$refs.templateTable.setCurrentRow(list[list.length - 1], true)
      }
    },
    // 模板行点击
    nodeRowChange (row) {
      this.nodeData = { ...row }
      // this.$refs.nodeTable.toggleRowSelection(row, true);
    },
    // 模板行选中
    nodeSelectChange (list) {
      this.selectedNodeList = []
      list.forEach(item => {
        this.selectedNodeList.push({ ...item })
      })
      if (list.length > 0) {
        this.$refs.nodeTable.setCurrentRow(list[list.length - 1], true)
      }
    },
    // 关闭模板新增弹窗
    closeDialog (dialogFlag) {
      switch (dialogFlag) {
        case 'template':
          // 清空文件编辑弹窗选择数据
          this.templateDialogVisible = false
          this.selectedTemList = []
          this.$refs.templateTable.clearSelection()
          this.searchTemplateData()
          break;
        case 'node':
          // 清空文件编辑弹窗选择数据
          this.nodeData = {}
          this.nodeDialogVisible = false
          this.selectedNodeList = []
          this.searchNodeData(this.selectedData.isoNo)
          this.$refs.nodeTable.clearSelection()
          break
      }
    },
    templatePageSizeChange (size) {
      this.templatePage.pageSize = size;
      this.searchTemplateData();
    },
    templatePageCurrentChange (index) {
      this.filePage.pageIndex = index;
      this.searchTemplateData(this.selectedData.isoNo,false);
    },
    nodePageSizeChange (size) {
      this.filePage.pageSize = size;
      this.searchNodeData(this.selectedData.isoNo);
    },
    nodePageCurrentChange (index) {
      this.filePage.pageIndex = index;
      this.searchNodeData(this.selectedData.isoNo, false);
    }
  },
  computed: {
    //  选中节点数据
    menuItem () {
      return this.store.state.system.functionMain.item;
    }
  },
  components: {
    templateAlertComponents,
    nodeAlertComponents
  }
}
</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;
}

.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;
}
</style>
