<template>
  <div class="custom-table">
    <div v-if="config.data.length">
      <div class="formula-wrapper" v-if="!disabled">
        <span style="flex-shrink: 0;color:#C0C4CC">{{$t('OnlineExcelPage.formula_lable')}}</span>
        <el-input
          v-show="selectCell.DataType===4"
          v-model="selectCell.Value"
          @change="updateValueByFormula"
        />
      </div>

      <!-- 日期行表格 -->
      <div class="table-wrapper" v-if="config.type === 1">
        <table width="auto" border="0" class="table" :style="disabled ? 'width:100%':''">
          <thead>
            <tr>
              <!-- 行头 -->
              <th class="th-tg sm"></th>

              <th class="th-tg"></th>
              <!-- 列头 -->
              <th 
                v-for="(item, index) in columnHeader" 
                :key="index" 
                class="th-tg th-col"
                :data-cindex="item"
                :data-rindex="-1"
                @contextmenu.prevent="rightClickHandle">
                {{item}}
              </th>
            </tr>
          </thead>

          <tbody>
            <tr v-for="(item, index) in config.EdbKeys" :key="item">
              <!-- 行头 -->
              <th class="th-tg sm"></th>

              <td rowspan="2" v-if="index === 0">
                {{$t('OnlineExcelPage.date_row_table')}}
                <i class="el-icon-sort" @click="changeSort"></i>
              </td>
              <td 
                v-for="(edb, sub_index) in config.data" 
                :key="sub_index"
                :data-rindex="-1"
                :data-cindex="columnHeader[sub_index]"
                @click="() => { !disabled && item==='EdbName' && clickEdbName(edb)}"
              >
                <template v-if="item === 'EdbName'">
                  <span :class="{'edbname-td':disabled}" @click="edbJumpToBase(edb)">{{ edb.EdbAliasName||edb[item] }}</span>
                </template>
                <template v-else>{{ edb[item] }}/{{ edb.Frequency }}</template>
              </td>
            </tr>

            <!-- 数据行  第一列日期-->
            <tr v-for="(date, dateIndex) in dateArr" :key="date">
              <!-- 行头 -->
              <th 
                class="th-tg th-row sm"
                :data-cindex="-1"
                :data-rindex="rowHeader[dateIndex]"
                @contextmenu.prevent="rightClickHandle"
              >{{rowHeader[dateIndex]}}</th>

              <td 
                :data-rindex="rowHeader[dateIndex]"
                :data-cindex="-1"
              >{{date}}</td>
              <td 
                v-for="(edb, edb_index) in config.data" 
                :key="edb_index"
                :data-rindex="rowHeader[dateIndex]"
                :data-cindex="columnHeader[edb_index]"
                :class="([2,3,5].includes(edb.Data.find(_ =>_.DataTime === date).DataType)&&edb.Data.find(_ =>_.DataTime === date).ShowValue)?'insert': ''"
                @click="clickCell($event,edb.Data.find(_ =>_.DataTime === date))"
                @dblclick="dblClickCell($event,edb.Data.find(_ =>_.DataTime === date))"
                @copy="copyCellHandle($event,edb.Data.find(_ =>_.DataTime === date))"
                @paste="pasteCellHandle($event,edb.Data.find(_ =>_.DataTime === date))"
              >
                <!-- 实际值/插值 -->
                <span 
                  :data-rindex="rowHeader[dateIndex]"
                  :data-cindex="columnHeader[edb_index]"
                  v-if="(edb.Data.find(_ =>_.DataTime === date).ShowValue&&!edb.Data.find(_ =>_.DataTime === date).CanEdit)||disabled"
                >
                  {{edb.Data.find(_ =>_.DataTime === date).ShowValue}}
                </span>

                <!-- 输入值/公式 -->
                <el-input
                  v-else
                  :data-rindex="rowHeader[dateIndex]"
                  :data-cindex="columnHeader[edb_index]"
                  v-model="edb.Data.find(_ =>_.DataTime === date).Value"
                  @click="clickCell($event,edb.Data.find(_ =>_.DataTime === date))"
                  @blur="changeVal($event,edb.Data.find(_ =>_.DataTime === date))"
                  @keydown.native="e =>{ e.keyCode===13 && changeVal(e,edb.Data.find(_ =>_.DataTime === date)) }"
                />
              </td>
            </tr>

            <!-- 文本行 -->
            <tr v-for="(row,index) in config.textRowData" :key="index">
              <!-- 行头 -->
              <th 
                class="th-tg th-row sm" 
                @contextmenu.prevent="rightClickHandle"
                :data-rindex="rowHeader[index+dateArr.length]"
                :data-cindex="-1"
              >{{rowHeader[index+dateArr.length]}}</th>

              <td 
                v-for="(cell, cell_index) in row" 
                :key="`${index}_${cell_index}`"
                :data-rindex="rowHeader[index+dateArr.length]"
                :data-cindex="cell_index===0?-1:columnHeader[cell_index-1]"
                :class="([2,3,5].includes(cell.DataType)&&cell.ShowValue)?'insert': ''"
                @click="clickCell($event,cell)"
                @dblclick="dblClickCell($event,cell)"
                @copy="copyCellHandle($event,cell)"
                @paste="pasteCellHandle($event,cell)"
              >
              
                  <span 
                    :data-rindex="rowHeader[index+dateArr.length]"
                    :data-cindex="cell_index===0?-1:columnHeader[cell_index-1]"
                    v-if="(cell.ShowValue&&!cell.CanEdit)||disabled"
                  > {{cell.ShowValue}}</span>
                  
                  <!-- 输入值/公式 -->
                  <el-input
                    v-else
                    v-model="cell.Value"
                    :data-rindex="rowHeader[index+dateArr.length]"
                    :data-cindex="cell_index===0?-1:columnHeader[cell_index-1]"
                    @click="clickCell($event,cell)"
                    @blur="changeVal($event,cell)"
                    @keydown.native="e =>{ e.keyCode===13 && changeVal(e,cell) }"
                  />
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      

      <!-- 日期列表格 -->
      <div class="table-wrapper" v-else>
        <table width="auto" border="0" class="table" :style="disabled ? 'width:100%':''">
          <thead>
            <tr>
              <!-- 行头 -->
              <th class="th-tg sm"></th>

              <th class="th-tg"></th>
              <th class="th-tg"></th>

              <!-- 列头 -->
              <th 
                v-for="(item, index) in rowHeader" 
                :key="index" 
                class="th-tg th-col"
                :data-cindex="-1"
                :data-rindex="rowHeader[index]"
                @contextmenu.prevent="rightClickHandle">
                {{item}}
              </th>
            </tr>
          </thead>

          <tbody>
            <tr>
              <!-- 行头 -->
              <th class="th-tg sm"></th>

              <td colspan="2">
                {{$t('OnlineExcelPage.date_row_table')}}
                <i class="el-icon-sort" style="transform: rotate(90deg)" @click="changeSort"></i>
              </td>

              <!-- 日期列 -->
              <td 
                v-for="(date, sub_index) in dateArr" 
                :key="date"
                :data-rindex="rowHeader[sub_index]"
                :data-cindex="-1"
              >{{ date }}</td>

              <!-- 文本列 -->
              <td
                v-for="(column,index) in config.textRowData"
                :key="index"
                :data-cindex="-1"
                :data-rindex="rowHeader[index+dateArr.length]"
                :class="([2,3,5].includes(column[0].DataType)&&column[0].ShowValue)?'insert': ''"
                @click="clickCell($event,column[0])"
                @dblclick="dblClickCell($event,column[0])"
                @copy="copyCellHandle($event,column[0])"
                @paste="pasteCellHandle($event,column[0])"
              >
                <span 
                  :data-cindex="-1"
                  :data-rindex="rowHeader[index+dateArr.length]"
                  v-if="(column[0].ShowValue&&!column[0].CanEdit)||disabled"
                > {{column[0].ShowValue}}</span>
                  
                <!-- 输入值/公式 -->
                <el-input
                  v-else
                  v-model="column[0].Value"
                  :data-cindex="-1"
                  :data-rindex="rowHeader[index+dateArr.length]"
                  @click="clickCell($event,column[0])"
                  @blur="changeVal($event,column[0])"
                  @keydown.native="e =>{ e.keyCode===13 && changeVal(e,column[0]) }"
                />
              </td>
            </tr>


            <!-- 指标行 -->
            <tr v-for="(edb, edb_index) in config.data" :key="edb.EdbInfoId">
              <!-- 行头 -->
              <th 
                class="th-tg th-row sm"
                :data-cindex="columnHeader[edb_index]"
                :data-rindex="-1"
                @contextmenu.prevent="rightClickHandle"
              >
                {{columnHeader[edb_index]}}
              </th>

              <!-- 名称 单位 -->
              <td 
                v-for="(item, index) in config.EdbKeys" 
                :key="index"
                :data-rindex="-1"
                :data-cindex="columnHeader[edb_index]"
                @click="() => { !disabled && item==='EdbName' && clickEdbName(edb)}"
              >
                <template v-if="item === 'EdbName'">
                  <span :class="{'edbname-td':disabled}" @click="edbJumpToBase(edb)">{{ edb.EdbAliasName||edb[item] }}</span>
                </template>
                <template v-else>{{ edb[item] }}/{{ edb.Frequency }}</template>
              </td>

              <!-- 数据列 -->
              <td 
                v-for="(data, data_index) in edb.Data"
                :key="`${edb.EdbInfoId}_${rowHeader[data_index]}_${columnHeader[edb_index]}`"
                :data-rindex="rowHeader[data_index]"
                :data-cindex="columnHeader[edb_index]"
                :class="([2,3,5].includes(data.DataType)&&data.ShowValue)?'insert': ''"
                @click="clickCell($event,data)"
                @dblclick="dblClickCell($event,data)"
                @copy="copyCellHandle($event,data)"
                @paste="pasteCellHandle($event,data)"
              >
                <!-- 实际值/插值 -->
                <span
                  :data-rindex="rowHeader[data_index]"
                  :data-cindex="columnHeader[edb_index]"
                  v-if="(data.ShowValue&&!data.CanEdit)||disabled"
                >
                  {{data.ShowValue}}
                </span>

                <!-- 输入值/公式 -->
                <el-input
                  v-else
                  :data-rindex="rowHeader[data_index]"
                  :data-cindex="columnHeader[edb_index]"
                  v-model="data.Value"
                  @click="clickCell($event,data)"
                  @blur="changeVal($event,data)"
                  @keydown.native="e =>{ e.keyCode===13 && changeVal(e,data) }"
                />
              </td>

              <!-- 文本列 -->
              <td
                v-for="(column,column_index) in config.textRowData"
                :key="`${rowHeader[column_index+dateArr.length]}_${columnHeader[edb_index]}`"
                :data-rindex="rowHeader[column_index+dateArr.length]"
                :data-cindex="columnHeader[edb_index]"
                :class="([2,3,5].includes(column[edb_index+1].DataType)&&column[edb_index+1].ShowValue)?'insert': ''"
                @click="clickCell($event,column[edb_index+1])"
                @dblclick="dblClickCell($event,column[edb_index+1])"
                @copy="copyCellHandle($event,column[edb_index+1])"
                @paste="pasteCellHandle($event,column[edb_index+1])"
              >
                <span 
                  :data-rindex="rowHeader[column_index+dateArr.length]"
                  :data-cindex="columnHeader[edb_index]"
                  v-if="(column[edb_index+1].ShowValue&&!column[edb_index+1].CanEdit)||disabled"
                > {{column[edb_index+1].ShowValue}}</span>
                  
                <!-- 输入值/公式 -->
                <el-input
                  v-else
                  v-model="column[edb_index+1].Value"
                  :data-rindex="rowHeader[column_index+dateArr.length]"
                  :data-cindex="columnHeader[edb_index]"
                  @click="clickCell($event,column[edb_index+1])"
                  @blur="changeVal($event,column[edb_index+1])"
                  @keydown.native="e =>{ e.keyCode===13 && changeVal(e,column[edb_index+1]) }"
                />
              </td>
        
            </tr>
          </tbody>
        </table>
      </div>


      <!-- 添加 -->
      <div class="add-fixed" v-if="!disabled" draggable @dragend="dragEnd" :style="isCollapse?'left:70px;':'left:200px;'">
        <div class="add-wrapper" v-show="!isSlideLeft">
          <div @click="addDateRow"> <i class="el-icon-circle-plus-outline"></i> {{$t('OnlineExcelPage.add_date_wrapper')}}</div>
          <div @click="addTextRow"> <i class="el-icon-circle-plus-outline"></i> {{$t('OnlineExcelPage.add_text_wrapper')}}</div>

          <span class="slide-icon slide-left" @click="isSlideLeft=!isSlideLeft">
            <i class="el-icon-d-arrow-left"></i>
          </span>
        </div>
        <!-- 折叠icon -->
        <div class="slide-cont" v-show="isSlideLeft">
          <span
            class="slide-icon slide-right"
            @click="isSlideLeft=!isSlideLeft"
           
          >
            <i class="el-icon-d-arrow-right"></i>
          </span>
        </div>

      </div>
    </div>

    <div class="nodata" v-else>
      <tableNoData :text="$t('Table.prompt_slogan')"/>
    </div>

    <!-- 右键菜单 -->
    <div class="contextMenu-wrapper" id="contextMenu-wrapper" @mouseleave="hideContextMenu">
      <div class="item" v-for="menu in contextMenuOption" :key="menu.key" @click="handleContext(menu.key)">{{menu.label}}</div>
    </div>


    <!-- 添加日期弹窗 -->
    <addDateCellDia 
      :isOpenDialog.sync="isAddDateDia"
      @success="concatData"
    />


    <!-- 指标别名 -->
    <m-dialog
      :show.sync="isEditEdbAliasDialog"
      width="650px"
      :title="$t('OnlineExcelPage.edit_indicator_tle')"
      @close="isEditEdbAliasDialog = false"
    >
      <div style="padding-left:80px">
        <el-form
          ref="formRef"
          label-position="left"
          hide-required-asterisk
          label-width="80px"
          :model="editEdb"
        >
          <el-form-item :label="$t('OnlineExcelPage.indicator_name_lbl')">
            <span>{{ editEdb.EdbName }}</span>
          </el-form-item>
          <el-form-item :label="$t('OnlineExcelPage.indicator_alias_lbl')" prop="EdbAliasName">
            <el-input v-model="editEdb.EdbAliasName" style="width:80%"/>
          </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="saveEdbAlias"
          >{{$t('Dialog.confirm_save_btn')}}</el-button
        >
        <el-button type="primary" plain @click="isEditEdbAliasDialog = false"
          >{{$t('Dialog.cancel_btn')}}</el-button
        >
      </div>
    </m-dialog>

  </div>
</template>
<script>
import { 
  getRowHeaderCode,
  getColumnHeaderCode,
  selectCellStyle,
  selectMoreCellStyle,
  extractFactorsFromFormula,
  findCellByFactor,
  splitString,
  toUpperCase,
  resetStyle,
  setFocus
} from '../common/customTable';
import addDateCellDia from './addDateCellDia';
import * as sheetInterface from '@/api/modules/sheetApi.js';
import { dataBaseInterface }  from '@/api/api.js';
import mDialog from '@/components/mDialog.vue'
export default {
  props: {
    sheetType: {
      type: Number
    },
    disabled: { //是否只预览
      type: Boolean,
      default: false
    }
  },
  watch: {
    sheetType(nval) {
      this.config.type = nval;
      this.$nextTick(() => {
        resetStyle();
      })
    },
    // 'config.data':{
    //   handler(value){
    //     console.log(value,'valuevaluevalue');
    //     if(!this.disabled && this.hasInit){
    //       this.$emit("autoSave")
    //     }
    //   },
    //   deep:true
    // },
    'config.textRowData':{
      handler(value){
        if(!this.disabled && this.hasInit){
          this.$emit("autoSave")
        }

      },
      deep:true
    },
    'config.order':{
      handler(value){
        if(!this.disabled && this.hasInit){
          this.$emit("autoSave")
        }
      }
    }
  },
  components: {addDateCellDia,mDialog},
  computed: {
    //列头
    columnHeader() {
      return getColumnHeaderCode(this.config.data.length)
    },
    //行头
    rowHeader() {
      let total_length = this.dateArr.length + this.config.textRowData.length;
      return getRowHeaderCode(total_length)
    },
    dateArr() {
      console.log(this.config.data)
      return this.config.data.length ? this.config.data[0].Data.map(_ => _.DataTime) : []
    },
    isCollapse() {
      return this.$store.state.isCollapse
    },
    contextMenuOption(){
        return [{ label: this.$t('ETable.Btn.delete_btn') ,key: 'del' }]
    }
  },
  data() {
    return {
      isSlideLeft: false,
      formula: '',
      config:{
        type: this.sheetType,
        order: 2,// 1降序 2升序
        EdbKeys: ["EdbName", "Unit"],
        data: [], //单元格类型 1默认格 2补充格 3自定义输入 4公式求值格 5预测值
        textRowData: [],
      },

      //选中的cell
      selectCell: {},

      //右击记录表格位置
      rightClickCell: {
        rindex: '',
        cindex: ''
      },

      isAddDateDia: false,

      //指标别名弹窗
      isEditEdbAliasDialog: false,
      editEdb: {},

      copyCellItem: {},
      hasInit:false
    };
  },
  methods: {

    /* 选择指标后push新数据 */
    updateEdbData(edb) {
      this.config.data.push(edb);

      //如果有文本行 文本行的数据长度也要增加
      if(this.config.textRowData.length) {
        let cell_item = {
          ShowValue: '',
          Value: '',
          DataType: 3,
          DataTime: '',
        }
        this.config.textRowData.forEach(row => {
            row.push(_.cloneDeep(cell_item))
            
        })
      }
      if(!this.disabled && this.hasInit){
        this.$emit("autoSave")
      }
    },

    /* 改变排序 */
    changeSort() {
      this.config.order = this.config.order === 1 ? 2 : 1;
      this.selectCell = {};
      this.config.data.forEach(edb => {

        edb.Data = this.config.order === 1 
          ? edb.Data.sort((x,y) => new Date(y.DataTime)-new Date(x.DataTime))
          : edb.Data.sort((x,y) => new Date(x.DataTime)-new Date(y.DataTime))
      })
      if(!this.disabled && this.hasInit){
        this.$emit("autoSave")
      }
    },

    // 单击指标名称修改别名
    clickEdbName(edb) {
      // console.log(edb)
      const { EdbName,EdbAliasName,EdbInfoId } = edb;
      this.editEdb = {
        EdbName,
        EdbAliasName,
        EdbInfoId
      };
      this.isEditEdbAliasDialog = true;
    },

    /* 保存别名 */
    saveEdbAlias() {
      this.config.data.find(_ =>_.EdbInfoId === this.editEdb.EdbInfoId).EdbAliasName = this.editEdb.EdbAliasName;
      if(!this.disabled && this.hasInit){
        this.$emit("autoSave")
      }
      this.isEditEdbAliasDialog = false;
    },

    /* 单机单元格 */
    clickCell(e,cell) {
      if(this.disabled) return

      this.selectCell = cell;
      selectCellStyle(e)
      setFocus(e)
    },

    /* 双击单元格 3 4可编辑 */
    dblClickCell(e,cell) {
      if(this.disabled || ![3,4].includes(cell.DataType) || !cell.ShowValue) return

      this.$set(cell,'CanEdit',true)
      this.$nextTick(() => {
        // console.log(e.target.childNodes[0])
        if(e.target.childNodes[0].childNodes[1].nodeName==='INPUT') {
          e.target.childNodes[0].childNodes[1].focus()
        }
      })
    },

    /* 添加一行空行/空列 */
    addTextRow() {
        let row = new Array(this.config.data.length+1).fill('').map(_ =>({
          ShowValue: '',
          Value: '',
          DataType: 3,
          DataTime: '',
        }))
        this.config.textRowData.push(_.cloneDeep(row))
        console.log(this.config.textRowData)
    },

    /* 添加日期 */
    addDateRow() {
      this.isAddDateDia = true
    },

    /* 添加日期后拼接数据 */
    concatData({type,data}) {
      let concatData = data.map( _ => ({
        ..._,
        Data: _.Data.map(_ => ({..._,DataTimeType: type==='past'?1:2})),
      }))

      this.config.data.forEach(edb => {
        let edb_concat_data = concatData.find(_ => _.EdbInfoId === edb.EdbInfoId).Data;

        edb.Data = this.config.order === 1 
          ? [...edb.Data,...edb_concat_data].sort((x,y) => new Date(y.DataTime)-new Date(x.DataTime))
          : [...edb.Data,...edb_concat_data].sort((x,y) => new Date(x.DataTime)-new Date(y.DataTime))
      })
      if(!this.disabled && this.hasInit){
        this.$emit("autoSave")
      }
    },

    /* 输入框失焦 存值或公式计算 val,行标 列标 指标信息 */
    async changeVal(e,cell) {
      //判断是否有= 判定为输入公式DataType为4 
      //否则是自填数 DataType为3
      const {value} = e.target;
      if(!value){
        cell.DataType = 3;
        cell.ShowValue = '';
        if(!this.disabled && this.hasInit){
          this.$emit("autoSave")
        }
        return
      }

      if(value.startsWith('=')) {
        cell.DataType = 4;
        let calculateVal = await this.getValueByFormula(value);
        cell.ShowValue = calculateVal;

      }else { //更新显示
        cell.DataType = 3;
        cell.ShowValue = value
      }
      this.$set(cell,'CanEdit',false)

      if(!this.disabled && this.hasInit){
        this.$emit("autoSave")
      }
    },

    /* 输入公式的计算值 */
    async getValueByFormula(val) {

      // 提取因数数组
      let factors = extractFactorsFromFormula(val)
      console.log(factors)
      
      //根据因数找单元格
      let isAllCell = factors.some(_ => findCellByFactor(_)=== null)
      if(isAllCell) {
        this.$message.warning(this.$t('OnlineExcelPage.error_parameter_not_msg') )
        return '';
      } 

      let TagMap = {};
      factors.forEach(_ => {
        if(!TagMap[_]) {
          TagMap[_] = Number(findCellByFactor(_))
        }
      });

      const res = await sheetInterface.calculateCustomCellData({
        CalculateFormula: val,
        TagMap
      })
      if(res.Ret !== 200) return 
      return res.Data
    },

    /* 顶部公式改变 */
    async updateValueByFormula(value) {
      this.changeVal({target: {value}},this.selectCell)
    },

    /* 行头和列头右键删除 */
    rightClickHandle(e) {
      if(this.disabled) return
      const {rindex,cindex} = e.target.dataset;
      this.rightClickCell = {
        rindex,
        cindex
      }
      const dom = $('#contextMenu-wrapper')[0];
			dom.style.left = e.clientX-3 + 'px';
			dom.style.top = e.clientY-3 + 'px';
      
      selectMoreCellStyle(e,this.config.type)
    },

    /*  */
    hideContextMenu() {
      const dom = $('#contextMenu-wrapper')[0];
			dom.style.left = '-9999px';
			dom.style.top = '-9999px';
    },

    /* 右键事件 */
    async handleContext(key) {
      let { rindex,cindex } = this.rightClickCell;

      if(rindex==='-1') { //删除列
        console.log('删除列',cindex)
          if(cindex === 'A') {
            await this.$confirm(this.$t('OnlineExcelPage.dlt_the_all_msg') ,this.$t('Confirm.prompt') ,{ type: 'warning' })
            this.reset()
            return
          }

          let index = this.columnHeader.findIndex(_ => _ === cindex);
          this.config.data.splice(index,1)
          this.config.textRowData.forEach(row => {
            row.splice(index+1,1)
          })
      }else if(cindex === '-1') { //删除行
        console.log('删除行',rindex)

        if(this.dateArr.length === 1) return this.$message.warning(this.$t('OnlineExcelPage.please_keep_one_msg') )

        let index = this.rowHeader.findIndex(_ => _ === rindex)
        if(index >= this.dateArr.length) {
          this.config.textRowData.splice(index-this.dateArr.length,1)
        }else {
          this.dateArr.splice(index,1)
          this.config.data.forEach(_ => {
            _.Data.splice(index,1)
          })
        }

        
      }
      if(!this.disabled && this.hasInit){
        this.$emit("autoSave")
      }
      this.hideContextMenu()
    },

    /* 保存时处理参数 */
    getSaveParams() {
      const { data,textRowData,order } = this.config;

      let TextRowData = textRowData.map(_ => {
        return _.map(cell => ({
          ...cell,
          RelationEdbInfoList: cell.DataType===4?this.dealFormulaConstruction(cell.Value):[]
        }))
      })

      let Data = data.map((_,index) => {
        return {
          EdbInfoId: _.EdbInfoId,
          EdbAliasName: _.EdbAliasName,
          Tag: this.columnHeader[index],
          Data: _.Data.map(cell => ({
            ...cell,
            RelationEdbInfoList: cell.DataType===4?this.dealFormulaConstruction(cell.Value):[]
          }))
        }
      })
      

      let params = {
        EdbInfoIdList: this.config.data.map(_ => _.EdbInfoId),
        Sort: order,
        TextRowData,
        Data,
      }
      console.log(params)
      return params
    },

    /* 处理因数结构 =a1+b1 => [{ Tag: a,Row:1 }] */
    dealFormulaConstruction(val) {
      // 提取因数数组
      let factors = extractFactorsFromFormula(val)
      let arr = factors.map(str => ({
          Tag: splitString(toUpperCase(str))[0],
          Row: splitString(toUpperCase(str))[1],
      }))
      return arr
    },

    /* 详情initData */
    initSheetData(initData) {
      this.hasInit=false
      if(initData.Data) {
        const { Data,Sort,TextRowData } = initData;

        this.config.order = Sort;
        this.config.data = Data;
        this.config.textRowData = TextRowData;
      }
      this.$nextTick(()=>{
        this.hasInit=true
      })
    },

    /* 跳转到指标库 */
    async edbJumpToBase(edb) {
      //非详情页不跳转
      if(!this.disabled) return
      
      if(!edb.HaveOperaAuth) return this.$message.warning(this.$t('MsgPrompt.no_edb_auth'))

      const res = await dataBaseInterface.targetDetail({EdbInfoId:edb.EdbInfoId})
      if(res.Ret !== 200) return

       //EdbInfoType=1 跳预测指标详情,=0跳指标库详情
      const {ClassifyId,UniqueCode,EdbInfoId,EdbInfoType} = res.Data;
      let {href} = this.$router.resolve({
        path:EdbInfoType===1?'/predictEdb':'/database',
        query:{code:UniqueCode,id:EdbInfoId,classifyId:ClassifyId}
      });
      window.open(href,'_blank');
    },

    /* 清空所有数据 */
    reset() {
      this.config.data = [];
      if(!this.disabled && this.hasInit){
        this.$emit("autoSave")
      }
      this.config.textRowData = [];
    },

    dragEnd(e) {
      let dom = document.querySelector('.add-fixed');
      dom.style.top = e.clientY-10 + 'px';
    },

    /* 要支持复制粘贴把公式也带过去 公式单元格类型为6 其余就正常复制文本 */
    copyCellHandle(e,cell) {
      this.copyCellItem = cell;
      // 阻止默认的复制操作
      e.preventDefault();
    },

    /* 要支持复制粘贴把公式也带过去 公式单元格类型为4 其余就正常复制文本 */
    pasteCellHandle(e,cell) {
      if(this.copyCellItem.DataType === 4) {
        cell.DataType = this.copyCellItem.DataType;
        cell.ShowValue = this.copyCellItem.ShowValue;
        cell.Value = this.copyCellItem.Value;
      }else {
        cell.DataType = 3;
        cell.ShowValue = this.copyCellItem.ShowValue;
        cell.Value = this.copyCellItem.ShowValue;
      }
      
      // 阻止默认的粘贴操作
      e.preventDefault();
    }  
    
  },
};
</script>
<style scoped lang="scss">
.custom-table {
  * { box-sizing: border-box; }
  .formula-wrapper {
    height: 42px;
    display: flex;
    align-items: center;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
    border: 1px solid #DCDFE6;
    margin-bottom: 15px;
    padding: 0 15px;
  }
  .table-wrapper {
    width: 100%;
    overflow: auto;
  }
  .nodata {
    text-align: center;
    font-size: 16px;
    color: #666;
    padding: 100px 0;
  }
  
  .table td,th {
    width: 104px;
    min-width: 104px;
    height: 35px;
    background: #fff;
    text-align: center;
    word-break: break-all;
    border: 1px solid #dcdfe6;
    word-wrap: break-word;
    word-break: break-all;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    position: relative;

    &.td-chose::after {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      content: "";
      display: block;
      outline: 0;
      border: 2px solid #0033FF;
      box-shadow: 0 0 5px rgba(73, 177, 249, .5)
    }
    &.td-col-select::after {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      content: "";
      display: block;
      outline: 0;
      border: 1px solid rgb(24, 173, 24);
      border-bottom: none;
      border-top: none;
    }
    &.td-row-select::after {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      content: "";
      display: block;
      outline: 0;
      border: 1px solid rgb(24, 173, 24);
      border-left: none;
      border-right: none;
    }
    &.insert {
      background: #FFEFDD;
    }
    .edbname-td {
      &:hover {
        text-decoration: underline;
      }
    }
  }
  
  .th-tg {
    background: #EBEEF5;
    &:hover {
      cursor: pointer;
      background: #ddd;
      /* border: 2px solid #409eff; */
    }
    &.sm {
      width: 36px;
      min-width: 36px;
      max-width: 36px;
    }
  }
  //整行选中
  tr {
    position: relative;
    &.choose-all::after {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      content: "";
      display: block;
      outline: 0;
      border: 2px solid #5897fb;
      box-shadow: 0 0 5px rgba(73, 177, 249, .5)
    }
  } 

  .el-icon-sort {
    color: #409eff;
    cursor: pointer;
    font-size: 16px;
  }

  .add-fixed {
    cursor: move;
    position: fixed;
    top: 70%;
    left: 0;
    z-index: 99;
    .add-wrapper {
      position: relative;
      padding: 5px 50px 5px 20px;
      background: #fff;
      border-radius: 0px 64px 64px 0px;
      font-size: 16px;
      box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
      border: 1px solid #DCDFE6;
      div { margin: 5px 0; cursor: pointer;color: #409eff; }

      .slide-icon {
        position: absolute;
        cursor: pointer;
        right: 20px;
        top: 50%;
        transform: translateY(-50%);
      }
    }
    .slide-cont {
      position: absolute;
      .slide-icon {
        padding: 20px 0;
        box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.3);
        border-radius: 5px;
        cursor: pointer;
        &:hover {
          background-color: rgba(0, 0, 0, 0.05);
        }
      }
    }
  }


  .contextMenu-wrapper {
    position: fixed;
    z-index: 99;
    top: -9999px;
    left: -9999px;
    background: #fff;
    padding: 10px 0;
    /* border: 1px solid #999; */
    box-shadow: 0 1px 4px #999;
    .item {
      padding: 10px 25px;
      cursor: pointer;
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}
</style>
<style lang="scss">
.custom-table {
  td,.formula-wrapper {
    .el-input__inner { border: none; outline: none; }
  }
  td .el-input__inner { text-align: center;height: 34px; line-height: 34px; }
  .el-input.is-disabled .el-input__inner {
    background-color: #fff;
  }
}
</style>
