<template>
  <div style="height:100%;" class="flexStar">
    <div class="boxswai" style="width:26%;padding-left:0px;">
      <div class="boxnei" style="display: flex;flex-direction: column;">
        <div class="flex">
          <el-input size="small" placeholder="输入关键字搜索" clearable @clear="allTreeShow = false" v-model="filterText">
          </el-input>
          <el-button size="small" class="mg-l-10" @click="treeFilter">搜索</el-button>
        </div>
        <!-- 树结构 -->
        <div style="overflow: auto;flex:1" v-if="isShowTree">
          <el-tree style="display: inline-block;min-width: 100%;" ref="trees" :loading="loading" :load="treeLoad" lazy
            :data="data" :props="defaultProps" @node-click="nodeClick" node-key="id" :expand-on-click-node="false"
            v-show="!allTreeShow" :default-expanded-keys="expandedKeys" auto-expand-parent>
            <span class="custom-tree-node" slot-scope="{ data ,node }" @mouseover.stop="mouseOver(data)"
              @mouseleave.stop="mouseLeave(data)" style="box-sizing: border-box;padding-right:70px!important;;">
              <div style="width:100%;">
                <span style="text-overflow: ellipsis;"> {{ data.name }} </span>
                <!-- <span> {{ node}} </span> -->
                <!-- 添加 -->
                <span v-show="data.moreShow">
                  <el-link :underline="false">
                    <i class="el-icon-circle-plus-outline" @click.stop="addExcel(data)" v-if="data.fileType != 3"
                      title="新增"></i>
                  </el-link>

                  <!-- 编辑 -->
                  <el-link :underline="false">
                    <i class="el-icon-edit marleft10 " @click.stop="editExcel(data)" v-if="data.fileType != 1"
                      title="编辑"></i>
                  </el-link>


                  <el-link :underline="false">
                    <i class="el-icon-sort marleft10" @click.stop="sortpai(data, node)" v-if="node.level != 1"
                      title="调整排序"></i>
                  </el-link>
                  <el-link :underline="false">
                    <i class="el-icon-upload marleft10" @click.stop="uploadMoudle(data, node)" v-if="data.fileType != 3"
                      title="上传"></i>
                  </el-link>
                  <!-- 删除 -->
                  <i class="el-icon-delete marleft10" @click.stop="deleteExcelM(data, node)" title="删除"></i>
                </span>
              </div>
            </span>
          </el-tree>
          <el-tree style="display: inline-block;min-width: 100%;" ref="treeall" v-loading="treeloading"
            :data="allTreeData" :props="defaultProps" @node-click="nodeClick" node-key="id" :expand-on-click-node="false"
            :filter-node-method="filterNode" v-show="allTreeShow">
            <span class="custom-tree-node" slot-scope="{ data ,node }" @mouseover.stop="mouseOver(data)"
              @mouseleave.stop="mouseLeave(data)" style="box-sizing: border-box;padding-right:70px!important;;">
              <div style="width:100%;">
                <span style="text-overflow: ellipsis;"> {{ data.name }} </span>
                <!-- <span> {{ node}} </span> -->
                <!-- 添加 -->
                <span v-show="data.moreShow">
                  <i class="el-icon-circle-plus-outline marleft10" @click.stop="addExcel(data)"
                    v-if="data.fileType != 3"></i>
                  <!-- 编辑 -->
                  <i class="el-icon-edit marleft10" @click.stop="editExcel(data)" v-if="data.fileType != 1"></i>

                  <el-link :underline="false">
                    <i class="el-icon-sort" @click.stop="sortpai(data, node)" v-if="node.level == 3" title="调整排序"></i>
                  </el-link>
                  <el-link :underline="false">
                    <i class="el-icon-upload marleft10" @click.stop="uploadMoudle(data, node)" v-if="node.level != 1"
                      title="上传"></i>
                  </el-link>
                  <!-- 删除 -->
                  <i class="el-icon-delete marleft10" @click.stop="deleteExcelM(data, node)" title="删除"></i>
                </span>
              </div>
            </span>
          </el-tree>
        </div>
      </div>
    </div>
    <div class="boxswai" style="width:74%;padding-left:0px;padding-right:0px;">
      <div class="boxnei">
        <div class="marleft10" style="height:100%;
          display: flex;flex-direction: column;">
          <!-- 上传、删除、下载操作栏 -->
          <div class="rightHeader" v-show="from.checkd">
            <template v-if="from.fileUrl">
              <div class="excelname">
                <div>{{ from.extension }}</div>
                <i class="el-icon-success marleft10" style="color: rgb(0, 168, 112);"></i>
              </div>
              <el-upload class="marleft10" :auto-upload="false" :show-file-list="false" action="#" :limit="1"
                :file-list='fileList' accept=".xls,.xlsx" :on-change="uploadChange" ref="file1">
                <el-button type="primary" size="mini">重新上传</el-button>
              </el-upload>
              <el-link class="marleft10 colorblue" @click="delectExcelMS">删除</el-link>
              <el-link underline class="marleft10 colorblue" style="text-decoration:underline;"
                @click="downloadExcel()">下载EXCEL</el-link>

            </template>
            <template v-else>
              <el-upload :auto-upload="false" :show-file-list="false" action="#" :limit="1" :file-list='fileList'
                accept=".xls,.xlsx" :on-change="uploadChange" ref="file2">
                <el-button type="primary" size="mini">上传 excel</el-button>
              </el-upload>
            </template>

            <div style="margin-left:50px;position: relative;" class="flex">
              <div class="excelname mg-r-10" v-if="from.templateExtension">
                <div>{{ from.templateExtension }}</div>
                <i class="el-icon-success marleft10" style="color: rgb(0, 168, 112);"></i>
              </div>
              <!-- <el-upload :auto-upload="false" :show-file-list="false" action="#" :limit="1" accept=".xls,.xlsx"
                :on-change="uploadcoverfileExcel" ref="file3">
                <el-button type="primary" size="mini">{{ from.templateExtension ? '重新上传导入模板' : '上传导入模板' }}</el-button>
              </el-upload> -->
             <div>
               <el-link v-if="from.templateExtension" class="marleft10 colorblue" @click="delectExcelMSModel">删除</el-link>
              <el-link v-if="from.templateExtension" underline class="marleft10 colorblue"
                style="text-decoration:underline;" @click="downloadExcelModel()">下载模板</el-link>
               <el-button type="success" size="mini" @click="saveExcelInfo" :loading="saveExcelJsonLoad" style="margin-left: 5px;">保存数据</el-button>
                <el-button type="primary" size="mini" @click="preViewInfoPdf" style="margin-left: 5px;"  :loading="pdfLoad">预览</el-button>
             </div>
              </div>
           
            
             <div style="position: absolute;right:30px;top:65px;">
               <el-button type="primary" size="mini"  @click="fullPage">全屏显示</el-button>
             </div>
          </div>

          <el-empty style="height:80%;" v-show="!from.checkd" description="该目录为根目录没有EXCEL文件"></el-empty>
          <div class="martop10" v-if="from.fileUrl" style="flex:1;">
            <!-- <iframe
              :src="excelSrc"
              style="width:100%;height:100%;"
            ></iframe> -->
            <div v-if='excelshow' style="width:100%;height:100%;" id="fullscreen_content">
              <!-- <vab-only-office :option='exceloption' /> -->
               <lucky-sheet
               v-loading="initLoad"
                ref="luckySheet"
                @data-change="handleDataChange"
                :initialData="initialData"
                :url="from.fileUrl"
              ></lucky-sheet>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 弹出框 -->
    <el-dialog :title="dialogTapType" class="dialogModel" :visible.sync="dialogTap" width="800px" modal-append-to-body
      append-to-body @close="handleClose">
      <div class="dialogBox">
        <el-form ref="excelForm" :model="excelForm" label-width="80px" :rules="rules">
          <div style="display: flex;justify-content: space-between;">
            <el-form-item label="清表名称" style="width: 370px;" size="small" prop="nodeName">
              <el-input v-model="excelForm.nodeName"></el-input>
            </el-form-item>
            <el-form-item label="清表类型" style="width: 370px;" size="small" prop="tabType">
              <el-select v-model="excelForm.tabType" style="width:100%;" placeholder="请选择清表类型">
                <el-option v-for="(val, index) in exceltypeData" :key="index" :label="val.dictValue"
                  :value="val.dictKey"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
        <div class="middle" v-if="wbsmiddle">
          <div class="left">
            <div class="select">
              <el-select placeholder="请选择WBS模板" style="width: 96%;" size="small" @change="wbsmodelchange"
                v-model="excelForm.wbsId">
                <el-option v-for="(val, index) in wbsmodel" :key="index" :label="val.wbsName" :value="val.id"></el-option>
              </el-select>
            </div>
            <div class="treecontent" v-loading="loading">
              <avue-tree :option="option2" :data="wbsdata" @node-click="nodeClickExcel" style="height:450px">
                <span class="el-tree-node__label" slot-scope="{ data }">
                  <div>
                    <span> {{ data.nodeName }} </span>
                  </div>
                </span>
              </avue-tree>
            </div>
          </div>
          <!-- 右侧关联 -->
          <template>
            <el-table :data="tableData" border height="502px" style="width: 100%;margin-left:20px">
              <el-table-column prop="tableName" label="表名">
              </el-table-column>
              <el-table-column label="操作" align="center" width="120">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.isLinkTable != 2" type="info" size="small"
                    @click="relation(scope.$index)">关联</el-button>
                  <el-button v-if="scope.row.isLinkTable == 2" type="warning" size="small"
                    @click="Disassociate(scope.$index)">取消关联</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </div>
      </div>
      <div class="btbox">
        <el-button size="mini" @click="handleClose()">取消</el-button>
        <el-button type="info" style="margin-left: 50px;" size="mini" :loading="saveExcelLoad"
          @click="saveExcel()">确定</el-button>
      </div>
    </el-dialog>
    <!-- 私有wbs树排序弹框 -->
    <el-dialog title="调整排序" :visible.sync="sortTag" width="50%" append-to-body>
      <ManualSorting v-if="sortTag2" @bianhua="bianhua()" :sort="sort" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="(sortTag = false), (sortTag2 = false)">取 消</el-button>
        <el-button type="primary" @click="editSort()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 上传Excel表格 -->
    <el-dialog title="上传Excel表格" :visible.sync="exceldialogVisible" width="40%" append-to-body
      :before-close="cancleexceldialog">
      <span>
        <el-upload accept=".xls, .xlsx" class="upload-demo" action="#" :auto-upload="false" :on-change="excelhandleChange"
          :show-file-list="false" multiple :on-exceed="excelhandleExceed" :file-list="excelfileList"
          ref="excelmoudelupload">
          <el-button size="small" type="primary">选择文件</el-button>
          <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
        </el-upload>
        <el-table class="down" :data="dataList" border stripe style="width: 100%;margin-top: 20px;">
          <el-table-column label="序号" width="150">
            <template slot-scope="scope">
              <i class="el-icon-sort-up marleft10 text-hover" @click="upSortFile(scope.row,scope.$index)"></i>
              <i class="el-icon-sort-down marleft10 text-hover" @click="downSortFile(scope.row,scope.$index)"></i>
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="文件名称">
            <template slot-scope="scope">
              <el-input v-model="scope.row.name" placeholder="请输入内容"></el-input>
            </template>
          </el-table-column>
          <el-table-column width="80" label="操作">
            <template slot-scope="scope">
              <el-button size="small" type="text" @click="deleteHandle(scope.row.uid)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancleexceldialog">取 消</el-button>
        <el-button type="primary" @click="aumbitexcelmoudel">确 定上传</el-button>
      </span>
    </el-dialog>
     <!--  预览pdf -->
            <PdfView
              ref="pdfDrawerExcelRef"
              @save-pdf="saveExcelInfoPdf"
              :saveExcelJsonLoadPdf="saveExcelJsonLoadPdf"
            />
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  detailExcel, excelType, tabLazytree, getWbsTypeList, wbstree, selectByNodeTable, Excelmodify, uploadExcel, deleteExcelshu, deleteExcel, deleteExcelmodel, tabLazytreeAll,
  uploadcoverfileExcel, downExcelFile, downExcelFileModel, exctabSort,batchUploadExcelTab
} from '@/api/exctab/excelmodel';
import ManualSorting from '@/components/WbsTree/ManualSorting'
import VabOnlyOffice from '@/components/online-office/index'
 import PdfView from '@/components/PdfView.vue';
import screenfull from "screenfull";
import LuckySheet from '@/components/lucky-sheet-editor/LuckySheet.vue'
import {getExcelJson,saveExcelJson,getExcelPdf,getTempExcelFileUrl} from '@/api/exctab/exceltab';
export default {
  components: {
    ManualSorting, VabOnlyOffice,LuckySheet,PdfView
  },
  data() {
    return {
      //参考vabOnlyOffice组件参数配置

      excelshow: false,

      expandedKeys: [],//默认展开的节点
      excelId: '',
      treeNode: {},
      //#region 鼠标
      leftTRee: '',//左侧树ID
      threessW: 400,
      //#endregion
      heightss: '',//
      loading: false,//懒加载
      data: [],//清表模板
      filterText: "",//搜索关键字
      allTreeShow: false,//是否显示整棵树
      treeloading: false,
      allTreeData: [],
      defaultProps: {
        children: "children",
        isLeaf: function (data) {
          return !data.hasChildren || (data.isExistForm == 1);
        },
      },
      wbsdata: [],//wbs模板
      //#region 右侧数据
      from: {
        checkd: false,//判断是否可以进行上传、重新上传excel
        id: '',//清表树ID
        extension: '', //文件名称
        fileUrl: '',//文件路径
        import: null,
      },
      fileList: [],//选中的文件
      excelSrc: '',//
      //#endregion

      //#region   弹框
      dialogTapType: '',
      dialogTap: false,
      option2: {
        filter: false,
        lazy: true,
        menu: false,
        treeLoad: (async (node, resolve) => {
          if (node.data.hasChildren) {
            const { data: res } = await wbstree({ parentId: node.data.id, wbsId: this.excelForm.wbsId, wbsType: this.excelForm.wbsType })
            console.log(res);
            if (res.code === 200) {
              if (Array.isArray(res.data)) {
                res.data.forEach((val) => {
                  if (!val.hasChildren) {
                    val.leaf = true
                  }
                })
              }
              return resolve(res.data)
            }
          } else {
            return resolve([])
          }
        }),
      },//弹框里面的wbs树
      excelForm: {
        nodeName: '',//清表名称
        tabType: '',//清表类型
        id: '',//清表Id,编辑时用
        parentId: '',//清表Id，添加时用
        wbsId: '',//WBS模板Id
        wbsType: '',//WBS模板类型
      },
      rules: {
        nodeName: [
          { required: true, message: '请输入清表名称', trigger: 'blur' },
        ],
        tabType: [
          { required: true, message: '请选择清表类型', trigger: 'blur' },
        ],
      },
      wbsform: {
        id: '',
        wbsType: '',
        wbsName: '',
      },//wbs树选中的值
      tableData: [],//右侧表数据
      wbsmiddle: false,//选择wbs模板那块是否有
      tableList: [],//进行处理的wbs关联表
      exceltypeData: [],//清表类型枚举
      wbsmodel: [],//wbs模板名称枚举
      //#endregion

      saveExcelLoad: false,
      sortTag: false,
      sortTag2: false,
      sort: [],
      curTreeData: {},
      defaultExpandKey: [],
      exceldialogVisible: false,
      isShowTree:true,
      uploadId:'',
      excelfileList: [],
      dataList: [],
      fileobj: [],
      initialData: [],
      initLoad: false,
      saveExcelJsonLoad: false,
      pdfLoad: false,
      pdfDrawerExcelRef: null,
      saveExcelJsonLoadPdf: false,
      saveDataInfo: {},
      pdfDataUrl:''
    }
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  methods: {
    fullPage(){
      console.log('全屏显示');
        // 判断是否支持
        if (!screenfull.isEnabled) {
        this.$message({
          message: "浏览器不支持全屏",
          type: "warning"
        });
        return false;
      }
      const element = document.getElementById('fullscreen_content');//指定全屏区域元素
      screenfull.request(element);
      // screenfull.toggle();

s
    },

    getFile() {
      this.excelshow = true

      this.getInitialData()
    },

    //刷新左边树形数据
    refreshTree() {
      console.log(this.curTreeData, 'this.curTreeData111111111');
      //刷新左边树形数据
      if (this.curTreeData.level === 1) {
        const parentId = 0
        tabLazytree({
          parentId: this.curTreeData.parentId,
          modeId: this.$route.params.id
        }).then(res => {
          this.data = res.data.data.data;
          this.$nextTick(() => {
            this.defaultExpandKey.push(this.curTreeData.id);
            this.$refs.trees.setCurrentKey(this.curTreeData.id);

          })

        });
      } else {
        this.updateTreeNewNode()
      }
    },

    updateTreeNewNode() {
      tabLazytree({
        parentId: this.curTreeData.parentId,
        modeId: this.$route.params.id
      }).then((res) => {
        let node = this.$refs.trees.getNode(this.curTreeData.parentId.parentId);
        this.$refs.trees.updateKeyChildren(this.curTreeData.parentId, res.data.data)
        this.$refs.trees.setCurrentKey(this.curTreeData.id);
      })
    },
    //#region  调整排序排序
    async sortpai(data, node) {
      console.log(data, node);
      await this.findWbsTreePrivateSameLevel(node, data)
      this.sortTag = true;
      this.sortTag2 = true;
      this.curTreeData = data
    },
    editSort() {
      this.exctabSort();
    },
    bianhua() {
      this.sortTag2 = false;
      this.$nextTick(() => {
        this.sortTag2 = true;
      });
    },
    async exctabSort() {
      console.log(this.sort, 'this.sort');
      var newArr = this.sort.map((v) => { return v.id })
      newArr = newArr.join(',')
      //清表树手动排序
      const { data: res } = await exctabSort(newArr);

      console.log(res);
      if (res.code == 200) {
        this.sortTag = false;
        this.sortTag2 = false;
        this.updateTreeNewNode();
      }
    },
    async findWbsTreePrivateSameLevel(node, data) {
      const { data: res } = await tabLazytree(
        {
          parentId: data.parentId,
          modeId: this.$route.params.id
        })
      if (res.code == 200) {
        res.data.forEach((item) => {
          item.tableName = item.name
        })
        this.sort = res.data
      }
    },

    async getLazytreessss() {
      const { data: res } = await tabLazytree(
        {
          parentId: 0,
          modeId: this.$route.params.id
        }
      );
      console.log(res);
      if (res.code == 200) {
        this.data = res.data;
        this.allTreeData = res.data
      }
    },
    //#region 接口
    async tabLazytree(parentId, modeId) {//清表树
      const { data: res } = await tabLazytree({ parentId, modeId })
      console.log(res);
      if (res.code === 200) {
        return res.data
      }
    },
    async detailExcel(id) {//获取列表信息

      const { data: res } = await detailExcel({ id })
      console.log(res);
      if (res.code === 200) {
        this.from.id = res.data.id
        this.from.extension = res.data.extension  //文件名称
        this.from.templateExtension = res.data.templateExtension
        this.from.name = res.data.name
        this.from.fileUrl = res.data.fileUrl      //文件路径
        let routeUrl = res.data.fileUrl
        let pSrc = routeUrl + '?r=' + new Date()
        this.excelSrc = 'http://view.officeapps.live.com/op/view.aspx?src=' + encodeURIComponent(pSrc);
        // //导入模板名称
        // this.from.import={}
        this.getFile()
      }
    },
    async getWbsTypeList() {//清表编辑 wbs 下拉框选择
      const { data: res } = await getWbsTypeList({ wbstype: 2 })
      console.log(res);
      if (res.code === 200) {
        this.wbsmodel = res.data
      }
    },
    async excelType() {//清表类型
      const { data: res } = await excelType({ code: 'sys_excltab_type' })
      console.log(res);
      if (res.code === 200) {
        res.data.forEach(element => {
          element.dictKey = Number(element.dictKey)
        });
        this.exceltypeData = res.data
      }
    },
    async wbstree() {//wbs树懒加载
      this.loading = true;
      const { data: res } = await wbstree({ parentId: 0, wbsId: this.excelForm.wbsId, wbsType: this.excelForm.wbsType })
      console.log(res);
      this.loading = false
      if (res.code === 200) {
        res.data.forEach((val) => {
          if (!val.hasChildren) {
            val.leaf = true
          }
        })
        this.wbsdata = res.data
      }
    },
    async selectByNodeTable(id, wbsType, liunxId, projectid) {//wbs树获取表
      const { data: res } = await selectByNodeTable({ id, wbsType, liunxId, projectid })
      console.log(res);
      if (res.code === 200) {
        console.log(Array.isArray(res.data));
        if (Array.isArray(res.data)) {
          this.tableData = res.data
          this.tableData.forEach(val => {
            val.changeTable = val.isLinkTable
          })
        } else {
          this.tableData = []
        }
      }
    },
    async deleteExcelshu(ids) {//删除清表
      // console.log(ids);
      const { data: res } = await deleteExcelshu(ids)
      console.log(res);
      if (res.code === 200) {
        this.$message({
          message: '删除清表树成功',
          type: 'success'
        });
        this.tabLazytree(0, this.$route.params.id)//获取清表树
        this.from = {
          checkd: false,//判断是否可以进行上传、重新上传excel
          id: '',//清表树ID
          extension: '', //文件名称
          fileUrl: '',//文件路径
        }
      }
    },
    async Excelmodify(wbsExclTabParmVO) {//编辑添加清表
      console.log(wbsExclTabParmVO, this.treeNode);
      const { data: res } = await Excelmodify(wbsExclTabParmVO)
      console.log(res);
      if (res.code === 200) {
        this.$message({
          type: 'success',
          message: '保存成功'
        })
        let ids = ''
        if (wbsExclTabParmVO.id) {
          ids = this.treeNode.parentId
        } else {
          ids = wbsExclTabParmVO.parentId
        }
        let das = await this.tabLazytree(ids, this.$route.params.id)//获取清表树
        if (wbsExclTabParmVO.id) {
          this.treeNode.name = wbsExclTabParmVO.nodeName
        } else {
          this.$refs.trees.updateKeyChildren(this.treeNode.id, das)
        }
        let node = this.$refs.trees.getNode(ids);
        node.isLeaf = false;
        node.isLeafByUser = false;
        this.dialogTap = false
      }
    },
    async uploadExcel(data) {//上传清表
      console.log('上传');
      const { data: res } = await uploadExcel(data)
      console.log(res);
      if (res.code === 200) {
        this.$message({
          message: '上传文件成功',
          type: 'success'
        })
        this.detailExcel(this.from.id)
        this.from.checkd = true
      }
      this.fileList = [];



      this.refreshTree()


    },
    async deleteExcel(data) {//删除excel表
      const { data: res } = await deleteExcel(data)
      if (res.code === 200) {
        this.$message({
          message: '删除excel表成功',
          type: 'success'
        })
        this.detailExcel(this.from.id)
        this.refreshTree()



      }
    },
    //#endregion

    //#region 右侧
    async uploadChange(file, fileList) {//选中表后触发

      this.fileList = [file.raw]
      let formData = new FormData()
      formData.append('file', ...this.fileList)
      formData.append('nodeId', this.from.id)
      if (this.from.fileUrl && this.from.fileUrl.length >= 2) {
        formData.append('type', 2)
      } else {
        formData.append('type', 1)
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      try {
        await this.uploadExcel(formData)
        loading.close();
      } catch (error) {
        loading.close();
      }

      if (this.$refs.file1) {
        this.$refs.file1.clearFiles();
      }
      if (this.$refs.file2) {
        this.$refs.file2.clearFiles();
      }
    },
    delectExcelMS() {//删除excel表点击事件、
      let _that = this
      this.$confirm('确认删除该文件?', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _that.deleteExcel({ id: _that.from.id, fileUrl: '' })
      }).catch(() => {
      })
    },
    downloadExcel() {//下载excel表
      //this.downFile(this.from.fileUrl,"123456.xlsx");
      //window.open(this.from.fileUrl,'namexxx')
      const link = document.createElement('a')
      downExcelFile(this.from.id).then((res) => {
        // 创建Blob对象，设置文件类型
        let blob = new Blob([res.data], { type: "application/vnd.ms-excel" })
        let objectUrl = URL.createObjectURL(blob) // 创建URL
        link.href = objectUrl
        link.download = this.from.extension // 自定义文件名
        link.click() // 下载文件
        URL.revokeObjectURL(objectUrl); // 释放内存
      })
    },

    delectExcelMSModel() {//删除excel表点击事件、
      let _that = this
      this.$confirm('确认删除该文件?', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteExcelmodel({ id: _that.from.id, fileUrl: '' }).then((res) => {
          if (res.data.code == 200) {
            _that.from.templateExtension = ''
            this.$forceUpdate()
          }
        })
      }).catch(() => {
      })

    },
    downloadExcelModel() {//下载excel表
      //this.downFile(this.from.fileUrl,"123456.xlsx");
      //window.open(this.from.fileUrl,'namexxx')
      const link = document.createElement('a')
      downExcelFileModel(this.from.id).then((res) => {
        // 创建Blob对象，设置文件类型
        let blob = new Blob([res.data], { type: "application/vnd.ms-excel" })
        let objectUrl = URL.createObjectURL(blob) // 创建URL
        link.href = objectUrl
        link.download = this.from.extension // 自定义文件名
        link.click() // 下载文件
        URL.revokeObjectURL(objectUrl); // 释放内存
      })
    },
    //#endregion

    //#region  外层左侧事件
    mouseLeave(data) {
      if (data.moreShow) {
        this.$set(data, 'moreShow', false)
      }
    },
    mouseOver(data) {
      if (!data.moreShow) {
        this.$set(data, 'moreShow', true)
      }
    },
    async treeLoad(node, resolve) {
      let id = node.data.id
      if (node.level == 0) {
        id = 0
      }
      let das = await this.tabLazytree(id, this.$route.params.id)
      return resolve(das)
    },
    nodeClick(data) {//外层树结构
      this.curTreeData = data;
      this.from.import = ""
      if (data.hasChildren == false) {
        this.from.checkd = true
      } else if (data.fileType == 3) {
        this.from.checkd = true
      } else {
        this.from.checkd = false
      }
      if (this.from.checkd) {
        this.detailExcel(data.id)
      } else {
        this.from = {
          checkd: false,//判断是否可以进行上传、重新上传excel
          id: '',//清表树ID
          extension: '', //文件名称
          fileUrl: '',//文件路径

        }
      }
    },
    async editExcel(data) {//编辑
      this.dialogTapType = '编辑'
      if (data.fileType != 3 && data.hasChildren) {
        this.wbsmiddle = false
      } else {
        this.wbsmiddle = true
        this.getWbsTypeList()//wbs模板名称
      }
      const { data: res } = await detailExcel({ id: data.id })
      console.log(res);
      if (res.code === 200) {
        this.excelForm.id = res.data.id
        this.excelForm.nodeName = res.data.name      //清表名称
        this.excelForm.tabType = res.data.tabType    //清表类型
        this.treeNode = data
        this.dialogTap = true
      }
    },
    async addExcel(data) {//添加
      this.dialogTapType = '新增'
      console.log(data);
      if (data.fileType == 3) {
        this.wbsmiddle = false
      } else {
        this.wbsmiddle = true
        this.getWbsTypeList()//wbs模板名称
      }
      this.excelForm.parentId = data.id
      this.treeNode = data
      this.dialogTap = true
    },
    deleteExcelM(data, node) {//删除
      console.log(node);
      if (data.hasChildren) {
        this.$message({
          type: 'warning',
          message: '该节点下有子节点，无法删除'
        })
        return;
      }

      const _that = this
      this.$confirm('确定将选择数据删除?', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        await _that.deleteExcelshu(data.id)
        _that.$refs.trees.remove(node) //删除界面上的节点
      }).catch(() => {
      });
    },
    //#endregion

    //#region 弹框属性
    handleClose() {//关闭弹框触发事件
      this.excelForm = {
        nodeName: '',//清表名称
        tabType: '',//清表类型
        id: '',//清表Id,编辑时用
        parentId: '',//清表Id，添加时用
        wbsId: '',//WBS模板Id
        wbsType: '',//WBS模板类型
      }
      this.wbsform = {
        id: '',
        wbsType: '',
        wbsName: '',
      }//wbs树选中的值
      this.wbsdata = []  //wbs树数据
      this.tableData = []//弹框table数据
      this.tableList = []//关联取消关联的数据
      this.dialogTap = false
    },
    wbsmodelchange(val) {//wbs模板change事件
      if (val) {
        this.wbsmodel.forEach((da) => {
          if (da.id == val) {
            this.excelForm.wbsType = da.wbsType
          }
        })
      }
      window.setTimeout(() => {
        this.wbstree();
      }, 100)

      this.tableData = [];
      this.tableList = [];
    },
    nodeClickExcel(data) {//wbs树点击事件
      console.log(this.excelId, "xxxxxxxxx");
      console.log(this.excelForm.id, "yyyyyyyy");
      this.wbsform.id = data.id
      this.wbsform.wbsType = data.type
      this.wbsform.wbsName = data.nodeName
      if (this.tableList == '') {
        this.selectByNodeTable(data.id, data.type, this.excelForm.id, this.excelForm.wbsId)
      } else {
        let tag = true
        this.tableList.forEach((val) => {
          if (val.id == data.id) {
            this.tableData = val.arrs
            tag = false
          }
        })
        if (tag) {
          this.selectByNodeTable(data.id, data.type, this.excelForm.id, this.excelForm.wbsId)
        }
      }

    },
    relation(key) {//关联
      this.tableData[key].isLinkTable = 2
      let tap = this.tableList.find((val) => {
        return val.id == this.wbsform.id
      })
      if (!tap) {
        this.tableList.push({
          id: this.wbsform.id,
          wbsType: this.wbsform.wbsType,
          wbsName: this.wbsform.wbsName,
          arrs: this.tableData
        })
      }
    },
    Disassociate(key) {//取消关联
      this.tableData[key].isLinkTable = 1
      const tap = this.tableList.find((val) => {
        return val.id == this.wbsform.id
      })
      if (!tap) {
        this.tableList.push({
          id: this.wbsform.id,
          wbsType: this.wbsform.wbsType,
          wbsName: this.wbsform.wbsName,
          arrs: this.tableData
        })
      }
    },
    saveExcel() {//保存按钮
      this.$refs.excelForm.validate(async (valid) => {
        if (valid) {
          let linkDataInfo = []
          if (this.tableList.length > 0) {
            this.tableList.forEach(val => {
              let linkIds = ''
              val.arrs.forEach(da => {
                if (da.isLinkTable != da.changeTable) {
                  linkIds = `${linkIds}${linkIds != '' ? ',' : ''}${da.pkeyId}_${da.isLinkTable}`
                }
              })
              if (linkIds != '') {
                linkDataInfo.push({
                  id: val.id,
                  linkIds: linkIds,
                  wbsName: val.wbsName,
                  wbsType: val.wbsType
                })
              }
            })
          }

          this.saveExcelLoad = true;
          try {
            if (this.excelForm.parentId && !this.excelForm.id) {
              await this.Excelmodify({
                nodeName: this.excelForm.nodeName,
                tabType: this.excelForm.tabType,
                parentId: this.excelForm.parentId,
                linkDataInfo: linkDataInfo
              })
            } else {
              await this.Excelmodify({
                nodeName: this.excelForm.nodeName,
                tabType: this.excelForm.tabType,
                id: this.excelForm.id,
                linkDataInfo: linkDataInfo
              })
            }
            this.dialogTap = false
          } catch (error) {
            console.log(error)
          }

          this.saveExcelLoad = false;
        }
      });
    },
    //#endregion

    //搜索树
    treeFilter() {
      if (this.filterText) {
        this.allTreeShow = true;
        if (!this.allTreeData.length) {
          this.treeloading = true;
          tabLazytreeAll({
            modeId: this.$route.params.id,
            name: '',
          }).then((res) => {
            this.treeloading = false;
            this.allTreeData = res.data.data;
            this.$nextTick(() => {
              this.$refs.treeall.filter(this.filterText);
            })
          })
        } else {
          this.$refs.treeall.filter(this.filterText);
        }
      } else {
        this.allTreeShow = false;
      }
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    uploadcoverfileExcel(file) {
      console.log('上传导入模板');
      this.from.templateExtension = false
      let formData = new FormData()
      formData.append('file', file.raw)
      formData.append('nodeId', this.from.id)
      this.from.templateExtension = file.raw.name
      // console.log(file.raw)

      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      uploadcoverfileExcel(formData).then(() => {
        this.$message({
          message: '上传文件成功',
          type: 'success'
        })
        // this.detailExcel(this.from.id)
        loading.close();
      }).catch(() => {
        loading.close();
      });

      this.$refs.file3.clearFiles();
      this.$forceUpdate()




    },
    //上传
    uploadMoudle(data) {
      console.log('上传');
      this.uploadId=data.id
      this.curTreeData = data;
      this.exceldialogVisible = true
    },


    excelhandleChange(file, fileList) {
      this.dataList = fileList
    },
    deleteHandle(uid) {
      let arr = this.dataList.filter((item) => {
        return item.uid !== uid
      })
      this.$nextTick(() => {
        this.dataList = arr
      })
    },
    aumbitexcelmoudel() {
      let formData = new FormData()
      this.dataList.forEach((item) => {
        formData.append('file', item.raw,item.name)
      })
      formData.append('id',this.uploadId)
      const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        batchUploadExcelTab(formData).then(() => {
          this.$message({
            message: '上传文件成功',
            type: 'success'
          })
          this.exceldialogVisible=false
          this.refreshTree()

          loading.close();
        }).catch(() => {
          loading.close();
        });
        this.$refs.excelmoudelupload.clearFiles();
        this.cancleexceldialog()

    },
    //更改上传文件顺序
    upSortFile(row,index){
      const data= this.dataList
      if(index!==0){
        const tmp = data.splice(index - 1, 1);
        this.dataList.splice(index, 0, tmp[0]);
      }else{
        this.$message.warning('已经处于置顶，无法上移')
      }

    },
    downSortFile(row,index){
      const indexs = index + 1
      const data = this.dataList
      if (indexs !== data.length) {
          const tmp = data.splice(indexs, 1);
          this.dataList.splice(index, 0, tmp[0]);
      } else {
        this.$message.warning('已经处于置底，无法下移')
      }
    },
    cancleexceldialog(){
      this.exceldialogVisible=false
      this.dataList=[]
      this.excelfileList=[]
    },
      handleDataChange(data) {
      // 处理数据变化
      console.log('表格数据已更新:', data)
      // 可以在这里将数据发送到后端保存
    },
    async getInitialData(){
      this.initLoad=true
        const { data: res } = await getExcelJson(
        {
          url: this.from.fileUrl,
         
        })
         this.initLoad=false
      if (res.code == 200) {
    
        this.initialData = JSON.parse(res.data)
      
        
        
      }else{
        this.$message.error(res.msg)
        this.initialData=[]
      }
    },
    //保存表格数据
async saveExcelInfo() {

      const saveData = await this.$refs.luckySheet.getData();
      this.saveDataInfo = saveData
      this.saveExcelJsonLoad = true; // 开始加载
      try {
      
        const { data: res } = await getTempExcelFileUrl({
          key: this.from.id,
          jsonExcel: JSON.stringify(saveData)
        });
        
        if (res.code === 200) {
          console.log(res.data,'data');
          this.pdfDataUrl = res.data;
          this.saveExcelInfoPdfUrL()

          
        } else {
          this.pdfDataUrl=''
          this.$message.error(res.msg);
        
        }
      } catch (error) {

      } finally {
        // 无论成功还是失败，最终都会执行这里
        this.saveExcelJsonLoad = false;
      }


},
 async saveExcelInfoPdfUrL() { 
    const { data: res } = await getExcelPdf({
          key: this.from.id,
          url: this.pdfDataUrl
        });
        console.log(res.data,'res1');
        
          this.$nextTick(() => {
            this.$refs.pdfDrawerExcelRef.show(res.data,true)
          
          })
},
async saveExcelInfoPdf() {
  this.saveExcelJsonLoadPdf = true; // 开始加载
  console.log(this.saveDataInfo ,'this.saveDataInfo ');
  
  try {
    // const saveData = await this.$refs.luckySheet.getData();
    const { data: res } = await saveExcelJson({
      key: this.from.id,
      jsonExcel: JSON.stringify(this.saveDataInfo )
    });
    
    if (res.code === 200) {
      this.$message({
        message: '保存成功',
        type: 'success'
      });
    } else {
      this.$message.error(res.msg);
      this.getInitialData();
    }
  } catch (error) {

  } finally {
    // 无论成功还是失败，最终都会执行这里
    this.saveExcelJsonLoadPdf = false;
  }
},
//预览pdf
 async preViewInfoPdf(){
  console.log('预览');
  this.pdfLoad = true; // 开始加载

  try {
   
    const { data: res } = await getExcelPdf({
      key: this.from.id,
    
    });
    
    if (res.code === 200) {
      console.log(res.data,'data');

      this.$nextTick(() => {
        this.$refs.pdfDrawerExcelRef.show(res.data,false)
       
      })
      
    } else {
      this.$message.error(res.msg);
     
    }
  } catch (error) {

  } finally {
    // 无论成功还是失败，最终都会执行这里
    this.pdfLoad = false;
  }
  }

  },
  created() {
    this.excelType()//清表类型
  },
  mounted() {
    // this.heightss = this.$refs.rulesss.clientHeight
  }
}
</script>

<style scoped lang="scss">
.marleft10 {
  margin-left: 10px;
}

::v-deep.el-tree-node__expand-icon {
  font-size: 16px;
}

.colorblue {
  color: rgb(0, 82, 217);
}

.treecontent ::v-deep.el-scrollbar {
  height: 100%;
}

.el-scrollbar {
  height: 100%;
}

.rightHeader {
  display: flex;
  justify-content: flex-start;
  align-items: top;
  font-size: 14px;
  background-color: #fff;

  .excelname {
    box-sizing: border-box;
    min-width: 200px;
    height: 28px;
    border: 1px solid rgb(220, 220, 220);
    padding: 0 10px;
    border-radius: 3px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.dialogModel {
  .dialogBox {
    .middle {
      display: flex;

      .left {
        border: 1px solid rgb(220, 220, 220);
        border-radius: 3px;
        height: 500px;
        width: 49%;

        .select {
          box-sizing: border-box;
          display: flex;
          justify-content: center;
          padding: 5px 0;
          border-bottom: 1px solid #e0e0e0;
        }

        .leftscroll {
          height: 450px;
          overflow-y: scroll;
        }
      }

      .right {
        height: auto;
        height: 60px;
        max-height: 500px;
        margin-left: 2%;
        // height: 500px;
        border-radius: 3px;

        td {
          box-sizing: border-box;
          padding: 5px 10px;
          height: 30px;
          line-height: 30px;
        }
      }
    }
  }

  .btbox {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

.rightBox {
  flex: 1;
}

.boxswai {
  height: 100%;
  box-sizing: border-box;
  padding-bottom: 10px;
}
.text-hover{
  cursor: pointer;
  color: #409EFF;
}
</style>
