<template>
  <div class="dataSheet-container" v-if="showData">
    <span
      class="slide-icon slide-right"
      @click="isSlideLeft = !isSlideLeft"
      v-show="isSlideLeft"
    >
      <i class="el-icon-d-arrow-right"></i>
    </span>
    <div class="data-sheet-main" id="box">
      <div class="main-left left" id="left" v-show="!isSlideLeft">
        <div class="datasheet_top">
          <el-button v-if="permissionBtn.checkPermissionBtn(permissionBtn.etaTablePermission.etaTable_excel)&&sourceMap[$route.path]===1" type="primary" style="margin-right:20px" @click="goAddSheetHandle"
          >{{$t('OnlineExcelPage.add_excel_btn')}}</el-button >

          <el-button v-if="permissionBtn.checkPermissionBtn(permissionBtn.etaTablePermission.etaTable_customize_data_sheetAdd)&&sourceMap[$route.path]===2" type="primary" style="margin-right:20px" @click="goAddSheetHandle">{{$t('OnlineExcelPage.add_timeline_table_btn')}}</el-button >

          <el-button v-if="permissionBtn.checkPermissionBtn(permissionBtn.etaTablePermission.etaTable_customize_mix_sheetAdd)&&sourceMap[$route.path]===3" type="primary" @click="goAddSheetHandle">{{$t('OnlineExcelPage.add_mixed_table_btn')}}</el-button >
          <el-button v-if="permissionBtn.checkPermissionBtn(permissionBtn.etaTablePermission.etaTable_customize_balance_sheetAdd)&&sourceMap[$route.path]===5" type="primary" @click="showAddBalanceTable=true">{{$t('OnlineExcelPage.add_balance_table_btn')}}</el-button >

          <el-checkbox 
            v-if="!showOnlyMeDefault"
            v-model="isShowMe"
            style="margin-left:20px"
            @change="() => { getTreeData();getPublicList() }"
          >{{sourceMap[$route.path]===5?$t('BalanceSheet.only_edit'):$t('Chart.only_see_mine')}}</el-checkbox>

        </div>
        <div class="search-cont">
          <el-select
            v-model="search_txt"
            ref="searchRef"
            :filterable="!search_txt"
            remote
            clearable
            :placeholder="$t('OnlineExcelPage.excel_name_ipt')"
            style="width: 100%"
            :remote-method="searchHandle"
            @focus="searchHandle('')"
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
            <el-option
              v-for="item in searchOptions"
              :key="item.ExcelInfoId"
              :label="item.ExcelName"
              :value="item.ExcelInfoId"
            >
              <div>
                <img 
                  :src="$icons.lock_ico2" 
                  width="18" 
                  height="18" 
                  style="vertical-align:middle" 
                  v-if="!item.HaveOperaAuth"
                />
                {{item.ExcelName}}
              </div>
            </el-option>
          </el-select>
        </div>
        <div class="tree-cont">
          <el-tree
            ref="treeRef"
            class="target_tree"
            :data="treeData"
            node-key="UniqueCode"
            :props="defaultProp"
            :allow-drag="canDragHandle"
            :allow-drop="canDropHandle"
            :current-node-key="select_node"
            :default-expanded-keys="defaultShowNodes"
            draggable
            :expand-on-click-node="false"
            check-strictly
            :empty-text="$t('Common.no_classify_msg')"
            @node-expand="handleNodeExpand"
            @node-collapse="handleNodeCollapse"
            @current-change="nodeChange"
            @node-drop="dropOverHandle"
            @node-drag-end="dropMouseLeave"
            @node-drag-leave="dropMouseLeave"
            @node-drag-enter="dropMouseOver"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <el-input
                ref="editVal"
                style="width: 90px"
                :placeholder="$t('OnlineExcelPage.please_value_ipt')"
                class="label-input"
                v-model="new_label"
                v-if="data.isEdit&&isSheetBtnShow('classifyOpt_edit')"
                @blur="changeValue(data)"
              />
              <span
                @dblclick.stop="editNodeLabel(data)"
                v-else
                class="text_oneLine node_label"
                :style="`width:${
                  (select_node === data.UniqueCode && node.Nodewidth) || ''
                }`"
              >
                <img 
                  :src="$icons.lock_ico2" 
                  width="18" 
                  height="18" 
                  style="vertical-align:middle" 
                  v-if="!data.HaveOperaAuth&&data.ExcelInfoId"
                />
                <span>{{ data.ExcelClassifyName }}</span>
              </span>
              <span
                style="display: flex; align-items: center"
                v-if="select_node === data.UniqueCode && data.HaveOperaAuth"
              >
                <img
                  src="~@/assets/img/data_m/move_ico.png"
                  alt=""
                  style="width: 14px; height: 14px; margin-right: 8px"
                />
                <!-- 添加子 -->
								<img
									src="~@/assets/img/set_m/add.png"
									alt=""
									style="width: 14px; height: 14px; margin-right: 8px"
									@click.stop="addNode(node,data)"
									v-if="!data.ExcelInfoId&&isSheetBtnShow('classifyOpt_edit')&&node.level<3"
								/>
                <img
                  src="~@/assets/img/set_m/edit.png"
                  alt=""
                  style="width: 15px; height: 14px; margin-right: 8px"
                  @click.stop="editNode(node, data)"
                  v-if="!data.ExcelInfoId&&isSheetBtnShow('classifyOpt_edit')"
                />
                <img
                  slot="reference"
                  src="~@/assets/img/set_m/del.png"
                  alt=""
                  style="width: 14px; height: 14px"
                  @click.stop="removeNode(node, data)"
                  v-if="!data.ExcelInfoId&&isSheetBtnShow('classifyOpt_delete')"
                />
              </span>
            </span>
          </el-tree>
          <div class="noDepart" @click="addLevelOneHandle" v-if="isSheetBtnShow('classifyOpt_edit')">
            <img
              src="~@/assets/img/set_m/add_ico.png"
              alt=""
              style="width: 16px; height: 16px; margin-right: 10px"
            />
            <span>{{$t('OnlineExcelPage.add_category_table_btn')}}</span>
          </div>
        </div>
        <span
          class="move-btn resize"
          v-drag
          id="resize"
          @mousemove="dynamicNode && resetNodeStyle(dynamicNode)"
        ></span>
        <span class="slide-icon slide-left" @click="isSlideLeft = !isSlideLeft">
          <i class="el-icon-d-arrow-left"></i>
        </span>
      </div>

      <!-- 平衡表列表 -->
      <div
        class="main-right"
        id="right"
        :style="isSlideLeft ? 'width:100%' : 'width:80%'"
        v-if="sourceMap[$route.path]===5"
      >
        <BalanceSheetList 
          :total="sheet_total" 
          :list="sheetList"
          :finished="!publicHaveMove"
          :loading="sheetLoading"
          @loadMoreHandle="loadMoreHandle"
          @delSheetHandle="delSheetHandle"
          @downloadExcel="downloadExcel"
          @updateEdit="balanceSheetUpdateEdit"
        />
      </div>

      <div
        v-else
        class="main-right"
        id="right"
        :style="isSlideLeft ? 'width:100%' : 'width:80%'"
      >
        <!-- 表格详情 -->
        <div class="sheet-detail-wrapper" v-if="select_id">

          <!-- 有权限 -->
          <template v-if="sheetDetailInfo.HaveOperaAuth">
            <div class="detail-top">
              <el-input
                ref="sheetEditTitRef"
                style="width: 400px"
                :placeholder="$t('OnlineExcelPage.please_table_name_ipt')"
                class="label-input"
                v-model="sheet_title"
                v-if="sheetDetailInfo.isEditTit"
                @blur="changeValue(sheetDetailInfo, 'edit-tit')"
              />
              <span
                class="sheet-name"
                @click="editExcelName(sheetDetailInfo, 'edit-tit')"
                v-else
              >
                {{ sheetDetailInfo.ExcelName }}
                <i class="el-icon-edit" v-if="sheetDetailInfo.Source === 1 && onlineExcelEditing" />
              </span>

              <div class="sheet-anothor-info">
                <span class="author">{{$t('OnlineExcelPage.author_info')}}{{ sheetDetailInfo.SysUserRealName }}</span>
                <ul class="action-ul">
                  <li style="color:#999999 ;">{{$t('OnlineExcelPage.recent_save_time_info')}}{{ saveTime }}</li>
                  <li
                    class="editsty"
                    @click="goEditHandle"
                    v-if="(sheetDetailInfo.Button && sheetDetailInfo.Button.OpButton&&isSheetBtnShow('edit') && (!onlineExcelEditing))"
                  >
                    <img src="~@/assets/img/icons/edit_blue_new.png" v-if="!editButtonText"/>
                    <span>{{ editButtonText?editButtonText:$t('ETable.Btn.edit_btn') }}</span> 
                  </li>
                  <li
                    class="editsty"
                    @click="saveHandle"
                    v-if="(sheetDetailInfo.Button && sheetDetailInfo.Button.OpButton&&isSheetBtnShow('save') && onlineExcelEditing)"
                  >
                    <img src="~@/assets/img/icons/save_blue_new.png"/>
                    <span>{{$t('ETable.Btn.save_btn')}}</span> 
                  </li>
                  <template v-if="[2, 3].includes(sheetDetailInfo.Source)">
                    <li
                      class="editsty"
                      @click="refreshSheetEdb"
                      v-if="sheetDetailInfo.Button.RefreshButton&&isSheetBtnShow('refresh')"
                    >
                    <img src="~@/assets/img/icons/refresh_blue_new.png"/>
                      <span>{{sheetRefreshing?$t('ETable.Btn.refreshing_btn'):$t('ETable.Btn.refresh_btn')}}</span>
                    </li>
                    <li
                      class="editsty"
                      @click="saveOtherHandle"
                      v-if="sheetDetailInfo.Button.CopyButton&&isSheetBtnShow('otherSave')"
                    >
                      <img src="~@/assets/img/icons/save_as_blue_new.png"/>
                      <span>{{$t('ETable.Btn.save_as')}}</span>
                    </li>
                  </template>
                  <li v-if="isSheetBtnShow('download')"
                    class="editsty" @click="downloadExcel(sheetDetailInfo)">
                    <img src="~@/assets/img/icons/download_blue.png"/>
                    <span>{{$t('ETable.Btn.download_btn')}}</span>
                  </li>
                  <li
                    class="deletesty"
                    v-if="(sheetDetailInfo.Button && sheetDetailInfo.Button.DeleteButton
                      &&isSheetBtnShow('del'))
                    "
                    @click="delSheetHandle({cell:sheetDetailInfo, type:'del'})"
                  >
                    <img src="~@/assets/img/icons/delete-red.png"/>
                    <span>{{$t('ETable.Btn.delete_btn')}}</span>
                  </li>
                </ul>
              </div>

            </div>

            <!-- 表格 -->
            <div class="sheet-wrap">
              <Sheet
                ref="sheetRef"
                v-if="sheetDetailInfo.Source === 1&&sheetDetailInfo.ExcelInfoId"
                :option="{
                  data: [{
                    ...JSON.parse(sheetDetailInfo.Content),
                    scrollTop: 0,
                    scrollLeft: 0
                  }]
                }"
                :sheetInfo="{
                  ExcelInfoId: sheetDetailInfo.ExcelInfoId,
                  ExcelName: sheetDetailInfo.ExcelName,
                  ExcelClassifyId: sheetDetailInfo.ExcelClassifyId,
                  Source: sheetDetailInfo.Source
                }"
                :limit="limit"
                @updated="autoSaveFun"
              />

              <!-- 自定义表格  -->
              <CustomTable
                v-else-if="sheetDetailInfo.Source === 2"
                :sheetType="sheetDetailInfo.ExcelType"
                :disabled="true"
                ref="customTableRef"
              />

              <MixedTable
                v-else-if="sheetDetailInfo.Source === 3"
                :disabled="true"
                ref="mixedTableRef"
              />
              <div class="chart-source">
                <span
                  v-if="[2,3].includes(sheetDetailInfo.Source) && sheetDetailInfo.SourcesFrom && JSON.parse(sheetDetailInfo.SourcesFrom).isShow"
                  :style="`
                  color: ${JSON.parse(sheetDetailInfo.SourcesFrom).color};
                  font-size: ${ JSON.parse(sheetDetailInfo.SourcesFrom).fontSize }px;
                `"
                ><!-- 数据来源 -->{{$t('ETable.Common.source')}}:{{ JSON.parse(sheetDetailInfo.SourcesFrom).text}}</span>
              </div>
            </div>
          </template>

          <noDataAuth v-if="sheetDetailInfo.HaveOperaAuth===false" :text="$t('MsgPrompt.no_sheet_auth')"/>
        </div>

         <!-- 列表 -->
        <sheetListWrap
          v-else
          :total="sheet_total" 
          :list="sheetList" 
          @loadMoreHandle="loadMoreHandle"
          @detailShowHandle="detailShowHandle"
          @delSheetHandle="delSheetHandle"
          @downloadExcel="downloadExcel"
          ref="sheetListWrap"
        />
      </div>
    </div>

    <!-- 分类弹窗 -->
    <classify-dia
      :isOpenDialog.sync="classifyDia"
      :title="dialog_title"
      :form="classifyForm"
      @successCallback="getTreeData"
    />

    <!-- 表格另存 -->
    <m-dialog
      :show.sync="isSaveOther"
      width="650px"
      :title="$t('ETable.Btn.save_as')"
      @close="cancelSaveOther"
    >
      <div style="padding-left: 80px">
        <el-form
          ref="formRef"
          label-position="left"
          hide-required-asterisk
          label-width="80px"
          :model="saveOtherForm"
          :rules="saveOtherFormRule"
        >
          <el-form-item :label="$t('OnlineExcelPage.excel_name_ipt')" prop="name">
            <el-input
              v-model="saveOtherForm.name"
              style="width: 80%"
              :placeholder="$t('OnlineExcelPage.please_table_name_ipt')"
            />
          </el-form-item>
          <el-form-item :label="$t('OnlineExcelPage.table_classification_label')" prop="classify">
            <el-cascader
              v-model="saveOtherForm.classify"
              :options="classifyOptions"
              :props="{
                label: 'ExcelClassifyName',
                value: 'ExcelClassifyId',
                children: 'Children',
                emitPath: false,
                checkStrictly: true,
              }"
              style="width: 80%"
              :placeholder="$t('OnlineExcelPage.select_appropriate_category_lable')"
              class="sheet-classify-cascader"
            />
          </el-form-item>
        </el-form>
      </div>
      <div style="display: flex; justify-content: center; margin-top: 30px">
        <el-button
          type="primary"
          style="margin-right: 60px"
          @click="saveCopyOther"
          >{{$t('Dialog.confirm_save_btn')}}</el-button
        >
        <el-button type="primary" plain @click="cancelSaveOther"
          >{{$t('Dialog.cancel_btn')}}</el-button
        >
      </div>
    </m-dialog>

    <!-- 新增平衡表弹窗 -->
    <m-dialog
      :show.sync="showAddBalanceTable"
      width="650px"
      :title="$t('OnlineExcelPage.add_balance_table_btn')"
      @close="showAddBalanceTable=false"
    >
      <el-form 
        :model="balanceTableForm" 
        :rules="balanceTableFormRule" 
        ref="addBalanceForm" 
        label-width="140px" 
        class="add-balance-wrap"
      >
        <el-form-item :label="$t('OnlineExcelPage.excel_name_ipt')" prop="name">
          <el-input 
            v-model="balanceTableForm.name" 
            :placeholder="$t('OnlineExcelPage.please_table_name_ipt')"
            style="width:350px"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('SteelChemicalPage.label_edb_classify')" prop="classify">
          <el-cascader
            v-model="balanceTableForm.classify"
            :options="balanceClassifyOpts"
            :props="{
              label: 'ExcelClassifyName',
              value: 'ExcelClassifyId',
              children: 'Children',
              emitPath: false,
              checkStrictly: true,
            }"
            clearable
            :placeholder="$t('OnlineExcelPage.select_table_category')"
            style="width:350px"
          />
        </el-form-item>
      </el-form>

      <div style="display: flex; justify-content: center; margin-top: 30px">
        <el-button
          type="primary"
          style="margin-right: 60px"
          @click="handleConfirmAddBalanceTable"
          >{{$t('Dialog.confirm_save_btn')}}</el-button
        >
        <el-button type="primary" plain @click="showAddBalanceTable=false"
          >{{$t('Dialog.cancel_btn')}}</el-button
        >
      </div>
    </m-dialog>
  </div>
</template>

<script>
import * as sheetInterface from "@/api/modules/sheetApi.js";
import leftMixin from "./mixins/classifyMixin";
import mDialog from "@/components/mDialog.vue";
import classifyDia from "./components/sheetClassifyDia.vue";
import Sheet from "./components/SheetExcel.vue";
import { getSheetImage } from "./common/option";
import CustomTable from "./components/CustomTable.vue";
import MixedTable from "./components/MixedTable.vue";
import sheetListWrap from "./components/sheetListWrap.vue"
import BalanceSheetList from './components/BalanceSheetList.vue';

export default {
  name: "",
  components: { mDialog, classifyDia, Sheet, CustomTable, MixedTable,sheetListWrap,BalanceSheetList },
  mixins: [leftMixin],
  beforeRouteLeave(to,from,next){
    if(from.path=='/sheetList'){
      this.markFinishStatus()
    }
    next()
  },
  computed: {
    downExcelFileUrl() {
      let url = `${
        process.env.VUE_APP_API_ROOT
      }/datamanage/excel_info/table/download?${localStorage.getItem("auth")}`;
      return url;
    },
    classifyOptions() {
      return this.balanceClassifyOpts;
    },
    saveOtherFormRule(){
      return {
        name: [
          { required: true, message: this.$t('OnlineExcelPage.table_name_empty_msg') , trigger: "blur" },
        ],
        classify: [
          { required: true, message: this.$t('OnlineExcelPage.cannot_be_empty_table') , trigger: "blur" },
        ],
      }
    },
    /* 是否默认只看我的 */
    showOnlyMeDefault() {
      return ['/sheetTimeList','/sheetMixedList'].includes(this.$route.path)
    }
  },
  data() {
    return {
      showData: false,
      search_txt: "",
      searchOptions: [],
      isSlideLeft: false, //左侧分类收起

      select_node: "", //节点唯一标识code
      select_classify: "",
      new_label: "", //双击修改的value
      treeData: [], //分类数据
      defaultShowNodes: [], //展开节点
      defaultProp: {
        label: "ExcelClassifyName",
        children: "Children",
      }, //树结构配置项
      dynamicNode: null,

      /* 分类弹窗 */
      dialog_title: "",
      classifyDia: false, //
      classifyForm: {},

      select_id: "", //选中的表格id
      sheetDetailInfo: {},
      sheet_title: "", //表格标题 双击标题修改时来存储最新值

      /* 表格列表 */
      publicHaveMove: true, //是否还有列表数据
      sheetList: [],
      sheet_total: 0,
      sheet_page: 1,
      sheet_pages_size: this.$route.path==='/sheetBalanceList'?30:16,
      sheetLoading:false,

      /* 另存为 */
      isSaveOther: false,
      saveOtherForm: {
        name: '',
				classify: ''
      },

      sourceMap: {
        '/sheetList': 1,
        '/sheetTimeList': 2,
        '/sheetMixedList': 3,
        '/sheetBalanceList': 5,
      },
      saveTime:"",
      editButtonText:"",
      onlineExcelEditing:false,
      limit:{
        disabled:true
      },
      autoSaveType:'',//自动保存类型，有的自动保存后需要其他操作
      cancelAutoSave:false, //自动保存时延迟的

      isShowMe: this.showOnlyMeDefault?true:false,//只看我的

      sheetRefreshing:false,//表格刷新状态

      showAddBalanceTable:false,//创建平衡表弹窗
      balanceTableForm:{
        name:'',
        classify:''
      },
      balanceTableFormRule:{
        name:[{ required: true, message: '请输入表格名称', trigger: 'blur' },],
        classify:[{ required: true, message: '请选择分类', trigger: 'change' },]
      },
      balanceClassifyOpts:[],//平衡表分类数据

    };
  },
  watch: {
    /* 设置动态右侧区域宽度 */
    isSlideLeft(newval) {
      this.select_id && this.$refs.sheetRef && this.$refs.sheetRef.init();
      this.$nextTick(() => {
        this.reloadRightWid();
      });
    },
    /* 表格id */
    select_id(newval,oldVlue) {
      if(newval){
        this.sheetDetailInfo = {}
        this.getDetailHandle()
      }
      this.markFinishStatus(oldVlue)
    },

    select_classify(newval) {
      if (this.$refs.sheetListWrap) this.$refs.sheetListWrap.$refs.listRef.scrollTop = 0;
      if (newval) {
        this.sheet_page = 1;
        this.getPublicList();
      }
    },

    /* 搜索关键词 */
    search_txt(newval) {
      if (newval) {
        let search_obj = this.searchOptions.find(
          (_) => _.ExcelInfoId === newval
        );
        let deep_arr = _.cloneDeep(this.treeData);
        // 查找图表的分类父级id
        let arr = this.findParentNodeHandle(deep_arr, search_obj.UniqueCode)
          .slice(1)
          .reverse(); // 父的父的父-父的父-父
        this.defaultShowNodes = arr;
        this.select_node = search_obj.UniqueCode;
        this.$refs.treeRef.setCurrentKey(this.select_node);
        // 重置筛选状态
        this.select_id = newval;
      }
    },
    onlineExcelEditing(value){
      // console.log(value);
      this.limit.disabled = !value
    },
    'sheetDetailInfo.ExcelName':{
      handler:function(newValue,oldValue){
        if(newValue && oldValue){
          this.autoSaveType = 'nameEdit'
          this.autoSaveFun()
        }
      }
    }
  },
  methods: {
    // 获取平衡表分类
    getBalanceClassifyOpts(){
      sheetInterface.excelClassifyOne({ Source: this.sourceMap[this.$route.path] }).then(res => {
        if (res.Ret !== 200) return

        this.balanceClassifyOpts = res.Data.AllNodes || [];
      })
    },
    //确认新增平衡表
    handleConfirmAddBalanceTable(){
      this.$refs.addBalanceForm.validate((valid) => {
          if (valid) {

            let params = {
              ExcelName: this.balanceTableForm.name,
              ExcelType: 1,
              ExcelClassifyId: this.balanceTableForm.classify,
              ExcelImage: '',
              Source: 5,
              TableData: {
                CellRelation:"[]",
                Data:[]
              }
            };
            sheetInterface.sheetAdd(params).then(res=>{
              if(res.Ret===200){
                this.$router.push({
                  path:'/editBalanceSheet',
                  query:{
                    id:res.Data.ExcelInfoId
                  }
                })
              }
            })
          } 
        });
    },
    // 更新平衡表编辑状态
    balanceSheetUpdateEdit(data){
      // 找到哪个表格
      this.sheetList.forEach(item => {
        if(item.ExcelInfoId===data.ExcelInfoId){
          item.CanEdit=false
          item.Editor=data.Editor
        }
      });
    },

    /* 添加表格 */
    goAddSheetHandle() {
      if (!this.treeData.length) return this.$message.warning(this.$t('OnlineExcelPage.please_table_classification_msg') );
      let type = this.sourceMap[this.$route.path];

      let path = {
        1: "/addsheet",
        2: "/addCustomSheet",
        3: "/addMixedSheet",
      };

        this.$router.push({ path: path[type] })
    },

    /* 获取表格分类 */
    getTreeData(params = null) {
      sheetInterface.classifyList({
        Source: this.sourceMap[this.$route.path],
        IsShowMe: this.isShowMe
      }).then((res) => {
        const { Ret, Data } = res;
        if (Ret !== 200) return;

        this.showData = true;
        this.treeData = Data.AllNodes || [];

        this.$nextTick(() => {
          /* 新增完成后 处理树展开和选中 */
          params && this.selectCurrentNode(params);
        });
      });
      // 更新一下分类把 新增平衡表时要
      if([2,3,5].includes(this.sourceMap[this.$route.path])){
        this.getBalanceClassifyOpts()
      }
    },

    /* 搜索表格 */
    searchHandle(query) {
      if (query) {
        /* 查找列表 */
        sheetInterface.sheetList({
            Keyword: query,
            CurrentIndex: 1,
            PageSize: 10000,
            Source: this.sourceMap[this.$route.path]
          }).then((res) => {
            if (res.Ret !== 200) return;
            this.searchOptions = res.Data.List || [];
          });
      } else {
        this.searchOptions = [];
      }
    },

    /* 选中分类变化时 */
    nodeChange({ UniqueCode, ExcelInfoId, ExcelClassifyId }, node) {
      console.log(this.select_id,ExcelInfoId,'UniqueCode');

      // 点击的是平衡表模块的表格直接进入预览页
      if(this.sourceMap[this.$route.path]===5&&ExcelInfoId>0){
        this.$router.push({
            path:'/viewBalanceSheet',
            query:{
              id:ExcelInfoId
            }
        })
        return
      }

      this.search_txt = "";
      this.select_node = UniqueCode;
      this.select_classify = !ExcelInfoId ? ExcelClassifyId : 0;
      if (this.select_id !== ExcelInfoId) {
        this.select_id = ExcelInfoId || 0;
      }
      this.resetNodeStyle(node);
      this.dynamicNode = node;
    },

    /* 添加一级目录 */
    addLevelOneHandle() {
      this.dialog_title = this.$t('ETable.Btn.add_btn') ;
      this.classifyForm = {
        classify_name: "",
        parentClassifyId: 0,
        parentName:''
      };
      this.classifyDia = true;
    },

    // 递归节点
		getNodeParentData(data,arr){
			if(data.level===0) return
			arr.push({ExcelClassifyName:data.data.ExcelClassifyName,ExcelClassifyId:data.data.ExcelClassifyId})
			this.getNodeParentData(data.parent,arr)
			return arr
		},

    /* 添加节点 */
    addNode(node,data) {
      let arr = []
      arr = this.getNodeParentData(node,arr).reverse();
      this.dialog_title = this.$t('ETable.Btn.add_btn') ;
      /* 编辑目录 */
      this.classifyForm = {
        classify_name: "",
        parentClassifyId: data.ExcelClassifyId,
        parentName: arr.map(_=>_.ExcelClassifyName).join('/')
      };
      this.classifyDia = true;
    },

    /* 编辑节点 */
    editNode(node, { ExcelClassifyName, ExcelClassifyId,ParentId }) {
      let arr = []
      arr = ParentId ? this.getNodeParentData(node.parent,arr).reverse() : [];
      this.dialog_title = this.$t('ETable.Btn.edit_btn');
      /* 编辑目录 */
      this.classifyForm = {
        classify_name: ExcelClassifyName,
        classify_id: ExcelClassifyId,
        parentClassifyId: ParentId,
        parentName: arr.map(_=>_.ExcelClassifyName).join('/')
      };
      this.classifyDia = true;
    },

    /* 删除节点校验 */
    async removeNode(node, { ExcelClassifyId, ExcelInfoId }) {
      const { Data } = await sheetInterface.classifyDelCheck({
        ExcelClassifyId,
        ExcelInfoId,
      });

      const { DeleteStatus } = Data;

      DeleteStatus === 1
        ? this.$confirm(this.$t('OnlineExcelPage.the_tables_no_delete_msg') , this.$t('MsgPrompt.delete_fail_msg') , {
            confirmButtonText: this.$t('MsgPrompt.known') ,
            showCancelButton: false,
            type: "error",
          })
        : DeleteStatus === 0 && !ExcelInfoId
        ? this.$confirm(this.$t('Chart.OptMsg.classify_del_confirm') , this.$t('Confirm.prompt') , {
            confirmButtonText:  this.$t('Dialog.confirm_btn'),
            cancelButtonText: this.$t('Dialog.cancel_btn'),
            type: "warning",
          }).then(() => {
            this.delApi(ExcelClassifyId, ExcelInfoId);
          })
        : null;
    },

    /* 删除方法 */
    delApi(ExcelClassifyId, ExcelInfoId, type = "") {
      sheetInterface
        .classifyDel({
          ExcelClassifyId,
          ExcelInfoId,
          Source: this.sourceMap[this.$route.path]
        })
        .then((res) => {
          if (res.Ret !== 200) return;
          this.$message.success(res.Msg);

          if (!res.Data.ExcelInfoId) this.select_id = "";

          //删除表格后自动显示下一张表格
          type == "del" && res.Data.ExcelInfoId
            ? this.getTreeData({
                code: res.Data.UniqueCode,
                id: res.Data.ExcelInfoId,
              })
            : this.getTreeData();

          //删除封面
          if (type === "del-list") {
            let index = this.sheetList.findIndex(
              (_) => _.ExcelInfoId === ExcelInfoId
            );
            this.sheetList.splice(index, 1);
          }
        });
    },

    /* 分类成功回调 */
    classifyCallback(type) {
      this.getTreeData();

      if (type === "add") {
        //新增分类完成之后，展开父节点显示刚新增的分类，若已展开节点则不做处理
        let code = this.add_parent_id;
        let flag = this.defaultShowNodes.some((item) => item === code);
        // console.log(flag)
        !flag && this.defaultShowNodes.push(code);
        this.add_parent_id = "";
      }
    },

    /* 展开对应菜单 显示详情 */
    detailShowHandle({ UniqueCode, ExcelInfoId }) {
      let params = {
        code: UniqueCode,
        id: ExcelInfoId,
      };
      this.selectCurrentNode(params);
      this.select_classify = 0;
    },

    /* 下载数据 */
    downloadExcel(cell) {
      const { Source, FileUrl, ExcelInfoId, ExcelName } = cell;
      let value = "";
      if (Source === 1) {
        value = FileUrl;
        this.downLoad(value, ExcelName);
      } else if ([2, 3,5].includes(Source)) {
        value = `${this.downExcelFileUrl}&ExcelInfoId=${ExcelInfoId}`;

        const a = document.createElement("a");
        a.href = value;
        a.target = "_blank";
        a.download = ExcelName;
        a.style.display = "none";
        document.body.append(a);
        a.click();
      }
    },

    downLoad(url, filename) {
      this.handleDownloadResource(url,filename)
    },

    /* 保存表格 */
    saveHandle: _.debounce(async function () {
      luckysheet.exitEditMode();
      //结构类型乱飘 强制定义下
      let data = {...luckysheet.getAllSheets()[0],status:Number(luckysheet.getAllSheets()[0].status)}
      if (!data.celldata.length) return this.$message.warning(this.$t('OnlineExcelPage.input_content_msg') );

      this.loading = this.$loading({
        target: ".dataSheet-container",
        lock: true,
        text: this.$t('MsgPrompt.saveing_msg') + "...",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.6)",
      });
      let img = getSheetImage(data);
      const form = new FormData();
      form.append("Image", img);
      const { Data } = await sheetInterface.uploadImg(form);

      data.luckysheet_select_save = [];
      const { ExcelInfoId, ExcelName, ExcelClassifyId } = this.sheetDetailInfo;
      
      this.cancelAutoSave=true

      const res = await sheetInterface.sheetEdit({
        ExcelInfoId,
        ExcelName,
        ExcelClassifyId,
        ExcelImage: Data.ResourceUrl,
        Content: JSON.stringify(data),
      });
      this.loading.close();
      if (res.Ret !== 200) return;
      if(res.Data.Status==1){
        this.$message.warning(res.Data.Msg)
        this.refreshOnlineExcel()
        this.onlineExcelEditing=false
        this.editButtonText = `${res.Data.Editor}${this.$t('OnlineExcelPage.editing_msg')}`
        return 
      }
      this.$message.success(this.$t('MsgPrompt.saved_msg') );

      if(this.autoSaveType == "nameEdit"){
        this.getTreeData();
        this.autoSaveType=''
      }

      this.getDetailHandle();
    }, 300),
    autoSaveFun:_.debounce(async function(){
      // console.log("自动保存");
      if(!this.onlineExcelEditing || this.cancelAutoSave){
        this.cancelAutoSave=false
        return
      }

      //结构类型乱飘 强制定义下
      let data = {...luckysheet.getAllSheets()[0],status:Number(luckysheet.getAllSheets()[0].status)}
      if (!data.celldata.length) return this.$message.warning(this.$t('OnlineExcelPage.input_content_msg') );

      data.luckysheet_select_save = [];
      const { ExcelInfoId, ExcelName, ExcelClassifyId } = this.sheetDetailInfo;
      const res = await sheetInterface.sheetEdit({
        ExcelInfoId,
        ExcelName,
        ExcelClassifyId,
        Content: JSON.stringify(data),
      });
      if (res.Ret !== 200) return;
      if(res.Data.Status==1){
        this.$message.warning(res.Data.Msg)
        this.refreshOnlineExcel()
        this.onlineExcelEditing=false
        this.editButtonText = `${res.Data.Editor}${this.$t('OnlineExcelPage.editing_msg') }`
        this.autoSaveType=''
        return 
      }
      if(this.autoSaveType == "nameEdit"){
        this.getTreeData();
        this.autoSaveType=''
      }
      
      this.saveTime = this.$moment().format('YYYY-MM-DD HH:mm:ss')

    },1500),
    /* 获取表格列表 */
    getPublicList() {
      this.sheetLoading=true
      sheetInterface.sheetList({
        CurrentIndex: this.sheet_page,
        PageSize: this.sheet_pages_size,
        ExcelClassifyId: this.select_classify || 0,
        Source: this.sourceMap[this.$route.path],
        IsShowMe: this.isShowMe
      }).then((res) => {
        this.sheetLoading=false
        if (res.Ret !== 200) return;

        this.publicHaveMove = res.Data
          ? this.sheet_page < res.Data.Paging.Pages
          : false;
        this.sheetList = res.Data
          ? this.sheet_page === 1
            ? res.Data.List
            : [...this.sheetList, ...res.Data.List]
          : [];
        this.sheet_total = res.Data ? res.Data.Paging.Totals : 0;
      }).catch(()=>{
        this.sheetLoading=false
      });
    },

    /* 加载更多 */
    loadMoreHandle: _.throttle(function () {
      // 平衡表加载下一页
      if(this.sourceMap[this.$route.path]==5){
        this.sheet_page++;
        this.getPublicList();
        return
      }
      let scrollTop = this.$refs.sheetListWrap.$refs.listRef.scrollTop;
      let clientHeight = this.$refs.sheetListWrap.$refs.listRef.clientHeight;
      let scrollHeight = this.$refs.sheetListWrap.$refs.listRef.scrollHeight;
      if (
        scrollTop + clientHeight >= scrollHeight - 10 &&
        this.publicHaveMove
      ) {
        this.sheet_page++;
        this.getPublicList();
      }
    }, 300),

    /* 获取表格详情 */
    getDetailHandle() {
      sheetInterface.sheetDetail({
          ExcelInfoId: this.select_id,
        })
        .then((res) => {
          if (res.Ret !== 200) return;

          this.sheetDetailInfo = res.Data;
          this.saveTime = this.$moment(this.sheetDetailInfo.ModifyTime).format('YYYY-MM-DD HH:mm:ss')||''
          this.editButtonText = this.sheetDetailInfo.CanEdit?'':`${this.sheetDetailInfo.Editor}${this.$t('OnlineExcelPage.editing_msg')}`
          if(!this.sheetDetailInfo.SourcesFrom){
            this.sheetDetailInfo.SourcesFrom = this.setDefaultSource(this.sheetDetailInfo.ExcelSource)
          }
          
          this.$nextTick(() => {
            //sheet组件Mounted已经init一次,再次调用会导致工具栏样式错乱
            //this.sheetDetailInfo.Source === 1 && this.$refs.sheetRef.init();

            this.sheetDetailInfo.Source === 2 && this.$refs.customTableRef &&
              this.$refs.customTableRef.initSheetData(res.Data.TableData);

            this.sheetDetailInfo.Source === 3 && this.$refs.mixedTableRef &&
              this.$refs.mixedTableRef.initData(res.Data.TableData)
            this.sheetDetailInfo.Source === 3 && this.$refs.mixedTableRef && this.$refs.mixedTableRef.getExcelRule(this.select_id);
          });
        });
    },
    setDefaultSource(sourceText){
      return JSON.stringify({
        isShow: true,
        text: sourceText,
        color: "#606266",
        fontSize: 9
      })
    },
    /* 删除表格 */
    delSheetHandle({cell, type = ""}) {
      const { ExcelClassifyId, ExcelInfoId  } = cell;
      this.$confirm(this.$t('ETable.Msg.is_del_table_msg') , this.$t('Confirm.prompt') , {
        confirmButtonText:  this.$t('Dialog.confirm_btn'),
        cancelButtonText: this.$t('Dialog.cancel_btn'),
        type: "warning",
      })
        .then(() => {
          this.delApi(ExcelClassifyId, ExcelInfoId, type);
        })
        .catch(() => {});
    },
    /* 编辑 */
    goEditHandle() {
      // 标记
      sheetInterface.markSheetEditStatus({ExcelInfoId: this.select_id,Status:1}).then(res=>{
        if(res.Ret != 200) return 
        if(res.Data.Status==0){
          let path = {
            1:"/addsheet",
            2: "/addCustomSheet",
            3: "/addMixedSheet",
          };
          if(this.sheetDetailInfo.Source === 1) {
            if(this.editButtonText.indexOf(this.$t('OnlineExcelPage.editing_msg'))!=-1){
              // 编辑中的状态 重新获取最新的详情数据
              this.refreshOnlineExcel()
            }

            this.onlineExcelEditing=true
          }else {
            this.$router.push({
              path: path[this.sheetDetailInfo.Source],
              query: { id: this.sheetDetailInfo.ExcelInfoId },
            });
          }

        }else if(res.Data.Status==1){
          this.editButtonText = `${res.Data.Editor}${this.$t('OnlineExcelPage.editing_msg')}`
          this.$message.warning('当前'+this.editButtonText)
        }
      })

    },

    /* 刷新表格 */
    refreshSheetEdb: _.debounce(async function () {
      if(this.sheetRefreshing) return
      this.sheetRefreshing=true
      const res = await sheetInterface.refreshCustomSheet({
        ExcelInfoId: this.sheetDetailInfo.ExcelInfoId,
      });
      this.sheetRefreshing=false

      if (res.Ret !== 200) return;
      this.$message.success(this.$t('ETable.Msg.refresh_success_msg') );
      this.getDetailHandle();
    }, 300),

    /* 表格另存为 */
    saveOtherHandle() {
      this.saveOtherForm.name = this.sheetDetailInfo.ExcelName + "(1)";
      this.isSaveOther = true;
    },

    cancelSaveOther() {
      this.$refs.formRef.resetFields();
      this.saveOtherForm = {
        name: '',
				classify: ''
      };
      this.isSaveOther = false;
    },

    /* 另存为 */
    async saveCopyOther() {
      await this.$refs.formRef.validate();
      let { classify, name } = this.saveOtherForm;

      const res = await sheetInterface.copyExcel({
        ExcelInfoId: this.sheetDetailInfo.ExcelInfoId,
        ExcelName: name,
        ExcelClassifyId: classify,
      });

      if (res.Ret !== 200) return;

      this.$message.success(this.$t('MsgPrompt.saved_msg') );
      this.cancelSaveOther();
      this.getTreeData();
      if(this.sourceMap[this.$route.path]==5){
        this.sheet_page=1
        this.getPublicList();
      }
    },

    /* 重绘右侧区域宽度 */
    reloadRightWid() {
      let total_wid = $(".data-sheet-main")[0].offsetWidth;
      let left = $("#left")[0].offsetWidth;
      let rigtWid = total_wid - left - 20 + "px";
      $("#right")[0].style.width = rigtWid;
    },
    editExcelName(sheetDetailInfo, type){
      if(!this.onlineExcelEditing) return
      this.editNodeLabel(sheetDetailInfo, type)
    },
    // 标记 编辑完成 退出编辑状态
    markFinishStatus(select_id){
      let id = select_id || this.select_id
      if((!this.onlineExcelEditing) || (!id) || id=='0'){
        this.onlineExcelEditing=false
        return
      }
      sheetInterface.markSheetEditStatus({ExcelInfoId: +id,Status:2}).then(res=>{
        if(res.Ret != 200) return 
      })
      this.onlineExcelEditing=false
    },
    unloadMark(){
      if((!this.onlineExcelEditing) || (!this.select_id) || this.select_id=='0'){
        this.onlineExcelEditing=false
        return
      }

      let url = process.env.VUE_APP_API_ROOT + "/datamanage/excel_info/mark"
      let params={ExcelInfoId: this.select_id,Status:2}
      const uuid = localStorage.getItem("uuid") || "";
      fetch(url, {
        method: 'POST',
        headers:{
          Authorization:localStorage.getItem("auth"),
          Uuid:uuid,
          AccessToken:uuid + "--zheshiyigename"
        },
        body:JSON.stringify(params),
        // 保持连接 让请求不会因为页面关闭而中断
        keepalive: true
      });
    },
    // 刷新在线excel详情数据
    refreshOnlineExcel(){
      sheetInterface.sheetDetail({
        ExcelInfoId: this.select_id,
      })
      .then((res) => {
        if (res.Ret !== 200) return;

        this.sheetDetailInfo = res.Data;
        this.saveTime = this.$moment(this.sheetDetailInfo.ModifyTime).format('YYYY-MM-DD HH:mm:ss')||''

        this.$nextTick(() => {
          this.$refs.sheetRef.init();
        });
      });
    }
  },
  mounted() {
    if (this.$route.query.code) {
      this.getTreeData({
        code: this.$route.query.code,
        id: Number(this.$route.query.id),
      });
    } else {
      this.getTreeData();
      this.getPublicList();
    }
    window.addEventListener("resize", this.reloadRightWid);
    if(this.$route.path == '/sheetList'){
      window.addEventListener('beforeunload',this.unloadMark)
    }
  },
  destroyed() {
    window.removeEventListener("resize", this.reloadRightWid);
    if(this.$route.path == '/sheetList'){
      window.removeEventListener('beforeunload',this.unloadMark)
    }
  },
};
</script>
<style lang="scss" scoped>
* {
  box-sizing: border-box;
}
$mini-font: 12px;
$normal-font: 14px;
.dataSheet-container {
  .slide-icon {
    padding: 20px 0;
    /* display: block; */
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.3);
    border-radius: 5px;
    cursor: pointer;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    z-index: 99;
    &:hover {
      background-color: rgba(0, 0, 0, 0.05);
    }
    &.slide-left {
      right: 0;
    }
    &.slide-right {
      left: 0;
    }
  }
  .data-sheet-main {
    display: flex;

    .main-left {
      width: 400px;
      min-width: 300px;
      background: #fff;
      margin-right: 20px;
      border: 1px solid #ececec;
      border-radius: 4px;
      box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
      height: calc(100vh - 120px);
      overflow: hidden;
      position: relative;
      box-sizing: border-box;

      .datasheet_top {
        padding: 20px;
        background: #fff;
        border: 1px solid #ececec;
        box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
        margin-bottom: 20px;
      }
      .search-cont {
        padding: 0 20px;
      }

      .tree-cont {
        padding: 30px 20px;
        max-height: calc(100vh - 280px);
        overflow: auto;
        margin-right: 20px;
      }
      .target_tree {
        color: #333;
        .custom-tree-node {
          display: flex !important;
          justify-content: space-between;
          align-items: center;
          display: block;
          flex: 1;
          .node_label {
            margin-right: 2px;
          }
          .el-icon-view {
            color: #409eff;
            font-size: 18px;
            margin-left: 5px;
          }
        }
      }
      .noDepart {
        margin: 60px 0;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #409eff;
        font-size: 16px;
        cursor: pointer;
      }
      .move-btn {
        height: 100%;
        width: 4px;
        /* opacity: 0; */
        position: absolute;
        right: 0px;
        top: 0;
        &:hover {
          cursor: col-resize;
          /* background-color: orange */
        }
      }
    }

    .main-right {
      width: 80%;
      min-width: 800px;
      position: relative;
      height: calc(100vh - 120px);
      display: flex;
      .sheet-detail-wrapper {
        flex: 1;
        border: 1px solid #ececec;
        border-radius: 4px;
        box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
        background: #fff;
        box-sizing: border-box;
        overflow-x: auto;
        display: flex;
        flex-direction: column;
        .detail-top {
          padding: 20px;
          border-bottom: 1px solid #ececec;
          .sheet-name {
            font-size: 18px;
            color: #333333;
            margin-bottom: 6px;
            // cursor: pointer;
            // max-width: 450px;
            // &:hover {
            //   text-decoration: underline;
            // }
          }
          .sheet-anothor-info{
            display: flex;
            justify-content: space-between;
            align-items: center;
            white-space: pre;
            .author{
              color: #666666;
              font-size: 16px;
            }
            .action-ul {
              display: flex;
              li {
                margin: 0 10px;
                display: flex;
                align-items: center;
                img{
                  height: 16px;
                  width: 16px;
                  margin-right: 4px;
                }
              }
            }
          }

        }
        .sheet-wrap {
          flex:1;
          position: relative;
          box-sizing: border-box;
          padding: 15px;
          overflow-y: auto;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          /* min-height: 500px; */
        }
      }

      .sheet-list-cont {
        color: #333;
        .el-card .el-card__header,
        .el-card__body {
          padding: 10px;
        }

        .sheetlist-wrapper {
          margin-top: 10px;
          display: flex;
          flex-wrap: wrap;
          max-height: calc(100vh - 143px);
          overflow: hidden;
          overflow-y: auto;
          .drag-cont {
            width: 100%;
            display: flex;
            flex-wrap: wrap;
          }
          .dragShdow {
            box-shadow: 0 1px 8px rgba(64, 158, 255, 0.8);
            opacity: 0.5;
          }
          .sheet-item {
            .item-top {
              display: flex;
              justify-content: space-between;
              align-items: center;
              font-size: 16px;
              font-weight: 600;
            }
            .chart-img {
              width: 100%;
              /* height: 230px; */
              object-fit: contain !important;
              cursor: pointer;
            }
            .item-bottom {
              margin-top: 10px;
              display: flex;
              justify-content: space-between;
              font-size: 12px;
              color: #666;
              .collected {
                color: #f00;
                cursor: pointer;
              }
              .join_txt {
                color: #409eff;
                cursor: pointer;
              }
            }
          }
        }
        .nodata {
          text-align: center;
        }
      }
    }
  }
}
</style>

<style lang="scss">
.add-balance-wrap{
  .el-input{
    width: 100%;
  }
}
.dataSheet-container {
  .label-input .el-input__inner {
    height: 25px;
    line-height: 25px;
    padding: 0 10px;
  }

  .el-tree__drop-indicator {
    height: 3px;
    background-color: #409eff;
  }
  .el-tree-node__content {
    margin-bottom: 14px !important;
  }
  .el-tree-node__children {
    .el-tree-node {
      /* margin-bottom: 8px !important; */
      margin-bottom: 0px !important;
      padding-left: 18px;
    }
    .el-tree-node__content {
      margin-bottom: 5px !important;
      padding-left: 0 !important;
    }
  }
  .expanded.el-icon-caret-right:before {
    content: url("../../assets/img/set_m/down.png") !important;
  }
  .el-icon-caret-right:before {
    content: url("../../assets/img/set_m/slide.png") !important;
  }
  .el-tree-node__expand-icon.is-leaf.el-icon-caret-right:before {
    content: "" !important;
  }
  .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  .el-tree-node.is-current > .el-tree-node__content {
    background-color: #f0f4ff !important;
  }
  .el-tree-node__content {
    padding-right: 10px !important;
  }
}
.sheet-classify-cascader .el-input {
	width: 100%;
}
</style>
