<template>
  <div>
    <div class="data-entry-wrap" @click="rightMouseMenu.show = false">
      <div class="left-wrap wrap-box">
        <div style="display: flex; justify-content: space-between;flex-wrap: wrap;" v-if="role!='special_researcher'">
          <el-button type="primary" style="width: 47%;" @click="isShowinsert = true">导入excel数据</el-button>
          <el-button type="primary" style="width: 47%;" @click="copyExcelNew">复制excel数据</el-button>
          <a style="width: 100%" :href="exportUrl" download>
            <el-button type="primary" style="width: 100%;margin-top: 14px;" plain>导出excel数据</el-button>
          </a>
        </div>
        <div style="margin: 20px 0">
          <!-- <el-input placeholder="请输入内容" prefix-icon="el-icon-search" v-model="leftSearchVal"> </el-input> -->
          <el-autocomplete
            clearable
            prefix-icon="el-icon-search"
            v-model="leftSearchVal"
            :fetch-suggestions="handleLeftSearch"
            placeholder="请输入内容"
            @select="handleSelectLeftSearchval"
            popper-class="el-autocomplete-suggestion-data-entry"
          >
            <template slot-scope="scope">
              <div v-if="scope.item.nodata" style="text-align:center">暂无数据</div>
              <div v-else>
                {{scope.item.SecName}}
              </div>
            </template>
          </el-autocomplete>
        </div>
        <ul class="classify-list">
          <li
            :class="[
              'classify-item',
              {
                'active-classify': selectClassifyId === item.ClassifyId,
              },
            ]"
            v-for="item in classifyList"
            :key="item.ClassifyId"
            @click="handleClassifyChange(item)"
          >
            {{ item.ClassifyName }}（{{item.EdbInfoTotal}}）
          </li>
        </ul>
      </div>
      <div class="right-wrap wrap-box" v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
        <el-button type="primary" style="font-size: 16px;margin-bottom: 20px;width:120px ;padding: 10px 8px;" @click="copyExcel" >编辑</el-button>
        <div class="table-con" v-infinite-scroll="handleOnScroll" :infinite-scroll-immediate="false" @scroll="rightMouseMenu.show = false">
          <table width="auto" border="0">
            <thead>
              <tr v-for="(item, index) in tableHeadArr" :key="item">
                <td class="sticky" style="left: 0">
                  {{ tableHeadMap.get(item) }}
                </td>
                <td v-for="(data, sub_index) in tableHeadData" :key="sub_index">
                  <div v-if="item !== 'SecName'">
                    <template v-if="item==='Status'">
                      <span v-if="data[item]==='未完成'" style="color:#FF0000">{{data[item]}}</span>
                      <span v-else-if="data[item]==='完成'" style="color:#4AC526">{{data[item]}}</span>
                      <span v-else>{{data[item]}}</span>
                    </template>
                    <template v-else>{{data[item]}}</template>
                  </div>
                  <div v-else>
                    <div v-if="data[item]">{{ data[item] }}</div>
                    <div v-else>
                        <el-select 
                            v-model="data[item]" 
                            filterable
                            remote 
                            placeholder="请输入关键词" 
                            :remote-method="handleTableHeadSearch" 
                            @change="handleTableSelect(sub_index,$event)"
                            @visible-change="handleTableSelectshow"
                            :disabled="leftSearchTradeCode||role=='special_researcher'"
                        >
                            <el-option v-for="item in searchList" :key="item.TradeCode" :label="item.SecName" :value="item"> </el-option>
                        </el-select>
                    </div>
                  </div>
                </td>
              </tr>
            </thead>
            <tbody @contextmenu.prevent="rightClick($event)">
              <tr v-for="(item, rindex) in tableData" :key="rindex">
                <td class="sticky" 
                    style="left: 0" 
                    :data-rindex="rindex" 
                    :data-cindex="-1" 
                    :class="(rindex===rightMouseMenu.rindex&&-1===rightMouseMenu.cindex)?'s-td':null"
                >
                  <!-- <span v-if="item.timeVal" :data-rindex="rindex" :data-cindex="-1">{{item.timeVal}}</span> -->
                  <el-date-picker
                    v-model="item.timeVal"
                    type="date"
                    :data-rindex="rindex"
                    :data-cindex="-1"
                    placeholder="选择日期"
                    :clearable="false"
                    :editable="false"
                    value-format="yyyy-MM-dd"
                    :readonly="readonly||role=='special_researcher'"
                    @mousedown.native="mousedown($event)"
                    prefix-icon="none"
                    @input="handleTimeChange(rindex,item)"
                    @focus="handleTimeFocus(rindex,item)"
                  ></el-date-picker>
                </td>
                <td 
                  v-for="(data, cindex) in item.list" 
                  :key="cindex" 
                  :data-rindex="rindex" 
                  :data-cindex="cindex"
                  :class="(rindex===rightMouseMenu.rindex&&cindex===rightMouseMenu.cindex)?'s-td':null"
                >
                  <input 
                    @focus="handleInputFocus(data,rindex,cindex)" 
                    @blur="handleInputChange(data)" 
                    @input="handleInput(data)"
                    class="input-val-box" 
                    type="number" 
                    v-model="data.item.Close" 
                    :data-rindex="rindex" 
                    :data-cindex="cindex" 
                    :disabled="role=='special_researcher'"
                  />
                  <!--  -->
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="frequency-wrap" v-if="showFrequency">
          <span :class="['item', { active: frequency === item }]" v-for="item in frequencyList" :key="item" @click="handleFrequencyChange(item)">{{ item }}</span>
        </div>
      </div>
    </div>

    <!-- 鼠标右键菜单 -->
    <div
      class="right-mouse-menu"
      v-if="rightMouseMenu.show"
      :style="{
        left: rightMouseMenu.left,
        top: rightMouseMenu.top,
      }"
    >
      <div class="item" @click="handleOptTable('插入行')">插入行</div>
      <div class="item" @click="handleOptTable('插入列')">插入列</div>
      <div class="item" @click="handleOptTable('删除行')">删除行</div>
      <div class="item" @click="handleOptTable('删除列')">删除列</div>
    </div>

    <!-- 导入数据弹窗 -->
    <insert-data 
      :isShowinsert="isShowinsert" 
      @cancelHandle="cancelHandle" 
      @importSuccess="importSuccess"
      source="dataEntry"
    > 
    </insert-data>
  </div>
</template>

<script>
import { dataAuthInterface, dataInterence } from "@/api/api.js";
import insertData from "./components/insertData";
import http from '@/api/http'
import { router } from "../../main";
export default {
  name: "dataEntry",
  components: { insertData },
  data() {
    return {
      timeArr:[],
      TradeCode:'',
      exportDataurl: process.env.API_ROOT + "/entry/export/dataList", //导出数据
      tableHeadArr: ["SecName", "TradeCode", "Frequency", "Unit", "ModifyDate", "Status"],
      tableHeadMap: new Map([
        ["SecName", "指标名称"],
        ["TradeCode", "指标ID"],
        ["Frequency", "频度"],
        ["Unit", "单位"],
        ["ModifyDate", "待更新日期"],
        ["Status", "更新状态"],
      ]),
      tableHeadData: [], // 表头数据
      tableData: [], //表格数据

      classifyList: [],
      selectClassifyId: null,
      frequencyList: ['日度','周度','旬度','月度','季度','半年度','年度'],
      frequency: "日度",
      showFrequency:true,

      rightMouseMenu: {
        show: false,
        left: null,
        top: null,
        rindex: null,
        cindex: null,
      }, //鼠标右键

      readonly: false,
      loading: false,

      isShowinsert: false,

      searchList:[],//头部搜索的值

      temInputVal:{},// 点击某个input 获取焦点则存放在此

      beforeInputVal:{},// 失焦时的input 数据

      leftSearchVal:'',//左侧搜索值
      // leftSearchList:[],
      leftSearchTradeCode:null, //如果是搜索选择的 则有此code 

      currentIndex:0,
      pageSize:50,
      finished:false,

      tempTime:'',// 存放更改日期前的日期
      sessionParams:{} //sessionStorage 的缓存参数
    };
  },
  computed:{
    exportUrl(){
      let str = `${this.exportDataurl}?Frequency=${this.frequency}&ClassifyId=${this.selectClassifyId}&KeyWord=${!this.leftSearchTradeCode?'':this.leftSearchVal}&TradeCode=${!this.leftSearchTradeCode?'':this.leftSearchTradeCode}&StartDate=&EndDate=&Mobile=&${localStorage.getItem('auth')}`
      return str.replace(/#/g,escape('#')).replace(/;/g,escape(';'))
    },
    role(){
      return localStorage.getItem('Role')||''
    }
  },

  watch: {
    "rightMouseMenu.show": {
      handler(nval) {
        if (!nval) {
          this.readonly = false;
        }
      },
    },
  },

  created() {
    // sessionStorage 缓存 从复制excel页面过来
    if(sessionStorage.getItem('onlineExcelBack')){
      this.sessionParams = JSON.parse(sessionStorage.getItem('onlineExcelBack'))
    }
    this.getClassify();
  },
  beforeRouteEnter (to, from, next) {
    if(from.path != '/onlineExcelCopy'){
      // 不是复制excel过来的 清除缓存
      sessionStorage.removeItem('onlineExcelBack')
    }
    next()
  },
  methods: {
    // 监听滚动
    handleOnScroll(){
      console.log('触底了');
      if(this.currentIndex>=1){
        this.handleMore()
      }
    },
    copyExcel(){
      // 找二级ID 对应的一级ID
      let parentClassifyId = this.classifyList.find(item => item.ClassifyId == this.selectClassifyId ).ParentId
      router.push({
        path:'/onlineExcelCopy',
        query:{
          Frequency: this.frequency,
          ClassifyId: this.selectClassifyId,
          parentClassifyId,
          TradeCode:this.leftSearchTradeCode || '',
          TradeName:this.leftSearchVal || '',
          isEdit:true
        }
      })
    },
    copyExcelNew(){
      let parentClassifyId = this.classifyList.find(item => item.ClassifyId == this.selectClassifyId ).ParentId
      router.push({
        path:'/onlineExcelCopy',
        query:{
          Frequency: this.frequency,
          ClassifyId: this.selectClassifyId,
          parentClassifyId,
          TradeCode:this.leftSearchTradeCode || '',
          TradeName:this.leftSearchVal || '',
          isEdit:false
        }
      })
    },
    //左侧搜索
    async handleLeftSearch(query,cb){
      cb([])
      if(!query) return
      const res=await dataInterence.getTargetListByName({
        Frequency: '',
        ClassifyId: '',
        Keyword:query,
        EdbShowType: 0,
      })
      if(res.Ret===200){
        let arr=res.Data.List||[]
        if(!arr.length){
          cb([{nodata:true}])
        }else{
          cb(arr)
        }
      }
    },

    // 选中左侧搜索值
    handleSelectLeftSearchval(e){
      console.log(e);
      if(!e.TradeCode) return
      this.showFrequency=false
      this.frequency=''
      this.selectClassifyId=''
      this.leftSearchTradeCode=e.TradeCode
      this.leftSearchVal=e.SecName
      this.getTableList(e.TradeCode)
      this.selectClassifyId=e.ClassifyId
      this.$nextTick(()=>{
        this.handleScrollLeftWrap()
      })
      
    },

    // 左侧滚动
    handleScrollLeftWrap(){
      let top=$('.active-classify')[0].offsetTop
      $('.classify-list').animate({
        "scrollTop": top-200
      })
    },

    // 日期改变
    async handleTimeChange(index,e){
      // 判断选择的日期是否重复
      let flag=this.timeArr.some(item=>item==e.timeVal)
      if(flag){
        if(!this.tempTime){// 如果是新增行的
          e.timeVal=''
        }else{
          e.timeVal=this.tempTime
        }
        this.$message.warning('该日期已存在')
      }else{
        if(!this.tempTime){// 新增行
          this.timeArr.splice(index,0,e.timeVal)
          this.tableData[index].list.forEach(item=>{
            item.item.Dt=e.timeVal
          })
          this.currentIndex++
        }else{// 修改日期
          let arr=[]
          this.tableData[index].list.forEach(item=>{
            item.item.Dt=e.timeVal
            if(item.TradeCode&&item.item.Close){
              arr.push({Close:item.item.Close,TradeCode:item.TradeCode})
            }
          })
          let params={
            CreateDate:e.timeVal,//新录入日期
            OldCreateDate:this.tempTime,//之前日期
            List:arr
          }
          const res=await dataInterence.modifyTargetDate(params)
          if(res.Ret===200){
            this.$message.success('修改成功')
            // 将timeArr 修改掉
            this.timeArr.splice(index,1,e.timeVal)
          }
        }
        
      }
      
    },

    // 日期获取焦点存放日期
    handleTimeFocus(index,e){
      if(this.role=='special_researcher') return
      this.tempTime=e.timeVal
      this.rightMouseMenu.rindex=index
      this.rightMouseMenu.cindex=-1
    },

    // input 获取焦点 每次获取焦点则存一次
    handleInputFocus(e,rindex,cindex){
      this.rightMouseMenu.rindex=rindex 
      this.rightMouseMenu.cindex=cindex
      this.temInputVal=JSON.parse(JSON.stringify(e))
    },

    // input 值改变 失去焦点
    async handleInputChange(e){
      console.log(e);
      // console.log(e.item.Close.test(/^(\d+|\d+\.\d{1,4})$/));
      // e.item.Close.replace(/^(\d+|\d+\.\d{1,4})$/,'')
      // 存储改变的input rindex cindex 等数据
      this.beforeInputVal={
        rindex:this.rightMouseMenu.rindex,
        cindex:this.rightMouseMenu.cindex,
        frequency:this.tableHeadData[this.rightMouseMenu.cindex].Frequency
      }

      // 如果input 为改变 且 之前也为空 
      if(!this.temInputVal.item.Close&&!e.item.Close){
        // console.log('之前之后都是空');
        return
      }
      // 在没有选择指标的列操作
      if(!e.TradeCode){
        e.item.Close=''
        this.$message.warning('请选择指标')
        return
      }

      // 没有选择日期
      if(!e.item.Dt){
        e.item.Close=''
        this.$message.warning('请选择日期')
        return
      }
      // 判断值是否改变
      if(this.temInputVal.TradeCode===e.TradeCode&&this.temInputVal.item.Close===e.item.Close){
        console.log('值未改变');
        return
      }

      // 删除情况
      if(!e.item.Close){
        this.handleDelete(e)
        return
      }

      // 修改情况
      // 检查该日期下是否存在数据
      let checkRes=await dataInterence.checkData({
        TradeCode:e.TradeCode,
				CreateDate:e.item.Dt
      })
      if(checkRes.Data.Status===0){
        const editRes=await dataInterence.editData({
          TradeCode:e.TradeCode,
          CreateDate:e.item.Dt,
          Close:e.item.Close,
          OldCreateDate:''
        })
        if(editRes.Ret===200){
          // 判断是否需要改变待更新状态
          this.handleChangeTradeStatus(e)
          this.handleUpdateClassify()
          this.$message({
					  message: '新增成功',
						type: 'success'
					});
        }else{
          this.$message({
            message:editRes.msg,
            type:'warning'
          })
          this.getTableList()
        }
      }else if(checkRes.Data.Status===1){
        this.$confirm('该日期已存在数据值'+checkRes.Data.Close+'，确认修改?','提示',{
					type:'warning'
				}).then(async ()=>{
          const editRes=await dataInterence.editData({
            TradeCode:e.TradeCode,
            CreateDate:e.item.Dt,
            Close:e.item.Close,
            OldCreateDate:e.item.Dt
          })
          if(editRes.Ret===200){
            this.$message({
              message: '修改成功',
              type: 'success'
            });
          }else{
            this.$message({
              message:editRes.msg,
              type:'warning'
            })
            this.getTableList()
          }
        }).catch(()=>{
          this.getTableList()
        })
      }
      
    },

    // 只允许输入整数或者小数点后四位
    handleInput(e){
      if(e.item.Close.indexOf('.')>0){
        e.item.Close=e.item.Close.slice(0,e.item.Close.indexOf('.') + 5)
      }
    },

    // 更新左侧分类数量统计
    handleUpdateClassify(){
      this.getClassify('update')
    },

    // 指标更新状态改变以及待更新日期变更
    async handleChangeTradeStatus(e){
      console.log(e);

      let res = await dataInterence.getTargetList({
        Frequency: '',
        ClassifyId: '',
        TradeCode:e.TradeCode,
        EdbShowType: 0,
      });
      if(res.Ret===200){
        if(res.Data.List){
          this.tableHeadData[this.beforeInputVal.cindex].Status=res.Data.List[0].Status
          this.tableHeadData[this.beforeInputVal.cindex].ModifyDate=res.Data.List[0].ModifyDate
        }
      }


      // let t1=this.tableHeadData[this.beforeInputVal.cindex].ModifyDate
      // let t2=e.item.Dt
      // // 日度
      // if(this.beforeInputVal.frequency==='日度'){
      //   if(new Date(t2)>=new Date(t1)){
      //     this.tableHeadData[this.beforeInputVal.cindex].Status='完成'
      //     // 待更新日期 推后一天
      //     let nextDay=(http.dateFormatter(new Date(new Date(t1).getTime()+(1000*60*60*24)),false)).replace(/\./g,'-')
      //     this.tableHeadData[this.beforeInputVal.cindex].ModifyDate=nextDay
      //   }
      // }

      // // 周度
      // if(this.beforeInputVal.frequency==='周度'){
      //   const week=new Date(t1).getDay()===0?7:new Date(t1).getDay()  //  1-7
      //   // 判断修改的日期是否在待更新这周内
      //   const mint=new Date(t1).getTime()-(week*1000*60*60*24)
      //   const maxt=new Date(t1).getTime()+((7-week)*1000*60*60*24)
      //   if(new Date(t2).getTime()>mint&&new Date(t2).getTime()<maxt){
      //     this.tableHeadData[this.beforeInputVal.cindex].Status='完成'
      //     let nextDay=(http.dateFormatter(new Date(new Date(t1).getTime()+(1000*60*60*24*7)),false)).replace(/\./g,'-')
      //     this.tableHeadData[this.beforeInputVal.cindex].ModifyDate=nextDay
      //   }
      // }

      // // 月度
      // if(this.beforeInputVal.frequency==='月度'){
      //   // 判断修改的日期是否在本月内
      //   const arr1=t1.split('-')
      //   const arr2=t2.split('-')
      //   if(arr1[0]===arr2[0]&&arr1[1]===arr2[1]){
      //     this.tableHeadData[this.beforeInputVal.cindex].Status='完成'
      //     let year=arr1[0]
      //     let month=''
      //   }
      // }
      
    },

    // 删除指标
    async handleDelete(e){
      // console.log(e);
      const res=await dataInterence.delData({
        TradeCode:e.TradeCode,
        CreateDate:e.item.Dt
      })
      if(res.Ret===200){
        this.$message.success('删除成功!');
      }else{
        this.$message(res.msg)
      }
    },

    //   表格头部搜索
    async handleTableHeadSearch(query){
        this.searchList=[]
        let res=await dataInterence.getTargetListByName({
            Frequency: this.frequency,
            ClassifyId: this.selectClassifyId,
            Keyword:query,
            EdbShowType: 2,
        });
        if(res.Ret===200){
            this.searchList=res.Data.List||[]
        }
    },

    // 表头搜索结果选择
    handleTableSelect(index,e){
        console.log(index,e);
        this.tableHeadData[index]=e
        this.tableData.forEach(item=>{
            item.list[index].SecName=e.SecName
            item.list[index].TradeCode=e.TradeCode
        })
        this.searchList=[]
    },

    // 表头搜索选择 下拉框收起时 将搜索结果列表置空
    handleTableSelectshow(e){
      if(!e){
        this.searchList=[]
      }
    },

    // 获取表格数据
    async getTableList(code) {
      this.loading = true;
      this.timeArr=[]
      this.tableData=[]
      this.tableHeadData=[]
      this.currentIndex=0
      this.finished=false
      // 缓存存在
      if(this.sessionParams.secondClassify){
        this.frequency = this.sessionParams.frequency
        this.selectClassifyId=this.sessionParams.secondClassify
        code = this.leftSearchTradeCode=this.sessionParams.tradeCode
        this.leftSearchVal=this.sessionParams.tradeName
        this.showFrequency= code ? false:true
        // 滚动到对应的分类
        this.$nextTick(()=>{
          this.handleScrollLeftWrap()
        })
        // 清除缓存 用完即弃
        this.sessionParams={}
        sessionStorage.removeItem('onlineExcelBack')
      }
      let res = await dataInterence.getTargetList({
        Frequency: code?'':this.frequency,
        ClassifyId: code?'':this.selectClassifyId,
        TradeCode:code,
        EdbShowType: code?0:1,
      });
      if (res.Ret !== 200) return;
      this.tableHeadData = res.Data.List || [];
      if(code) this.frequency = res.Data.FrequencyList ? res.Data.FrequencyList[0]:''
      //  不满6列 追加 到6列
      if (this.tableHeadData.length < 6) {
        let min = 5 - this.tableHeadData.length;
        for (let i = 0; i < min; i++) {
          this.tableHeadData.push({
            SecName: "",
            TradeCode: "",
            Frequency: "",
            Unit: "",
            ModifyDate: "",
            Status: "",
            DataList: [],
          });
        }
      }

      // 处理日期 合并所有日期 去重排序
      let temArr = this.tableHeadData && this.tableHeadData.map((item) => item.DataList).flat();
      let temTimeArr = temArr.map((item) => item.Dt);
      let Arr = [...new Set(temTimeArr)].sort().reverse();
      // 如果第一项不是今天 则增加一个今日日期 --- 判断错误 可能会存在 未来日期 真是神奇Arr[0]!==nowDay
      // 如果第一项小于今日 则增加今日日期
      let nowDay=(http.dateFormatter(new Date(),false)).replace(/\./g,'-')
      if((new Date(Arr[0])<new Date(nowDay))&&res.Data.List){
        Arr=[nowDay,...Arr]
      }
      this.timeArr=Arr 

      // let arr2 = Arr.map((item) => {
      //   let obj = {
      //     timeVal: item,
      //     list: [],
      //   };
      //   this.tableHeadData.forEach((item2) => {
      //     let obj2 = {
      //       SecName: item2.SecName,
      //       TradeCode: item2.TradeCode,
      //       item: {
      //         Close:'',
      //         Dt:item||''
      //       },
      //     };
      //     obj2.item = item2.DataList.find((time) => time.Dt === item)||{Close:'',Dt:item}
      //     obj.list.push(obj2);
      //   });
      //   return obj;
      // });
      // this.tableData = arr2;

      // // 时间少于12行 则 增加到12
      // if (this.tableData.length < 12) {
      //   let min = 12 - this.tableData.length;
      //   let temList = this.tableHeadData.map((item) => {
      //     let obj={ SecName: item.SecName, TradeCode: item.TradeCode, item: { Close: "",Dt:'' } }
      //     return obj;
      //   });
      //   // 此处JSON 转换不可省去  有拷贝复制问题
      //   for (let i = 0; i < min; i++) {
      //     this.tableData.push({ timeVal: "", list: JSON.parse(JSON.stringify(temList)) });
      //   }
      // }
      this.handleMore()
      setTimeout(() => {
        this.loading = false;
      }, 200);

    },

    // 分页
    handleMore(){
      if(this.finished) return
      // this.page++
      // const startIndex=(this.page-1)*this.pageSize
      // const endIndex=this.page*this.pageSize
      const startIndex=this.currentIndex
      const endIndex=this.currentIndex+this.pageSize
      this.currentIndex=endIndex
      if(endIndex>=this.timeArr.length){
        this.finished=true
      }else{
        this.finished=false
      }
      const temTimeArr=this.timeArr.slice(startIndex,endIndex)
      let arr = temTimeArr.map((item) => {
        let obj = {
          timeVal: item,
          list: [],
        };
        this.tableHeadData.forEach((item2) => {
          let obj2 = {
            SecName: item2.SecName,
            TradeCode: item2.TradeCode,
            item: {
              Close:'',
              Dt:item||''
            },
          };
          obj2.item = item2.DataList.find((time) => time.Dt === item)||{Close:'',Dt:item}
          obj.list.push(obj2);
        });
        return obj;
      });
      this.tableData=[...this.tableData,...arr];

      // 不满12行 补行
      if(this.currentIndex<=this.pageSize&&this.tableData.length < 12){
        let min = 12 - this.tableData.length;
        let temList = this.tableHeadData.map((item) => {
          let obj={ SecName: item.SecName, TradeCode: item.TradeCode, item: { Close: "",Dt:'' } }
          return obj;
        });
        // 此处JSON 转换不可省去  有拷贝复制问题
        for (let i = 0; i < min; i++) {
          this.tableData.push({ timeVal: "", list: JSON.parse(JSON.stringify(temList)) });
        }
      }
    },

    // 获取频度
    // async getFrequencyList() {
    //   let res = await dataInterence.getFrequencyList({
    //     ClassifyId: this.selectClassifyId,
    //   });
    //   if (res.Ret === 200) {
    //     this.frequencyList = res.Data || [];
    //     this.frequency = this.frequencyList.length ? this.frequencyList[0] : "";
    //     this.getTableList();
    //   }
    // },

    /* 获取分类 */
    async getClassify(e) {
      // dataAuthInterface.classifyList().then((res) => {
      //   if (res.Ret === 200) {
      //     this.classifyList = res.Data || [];
      //     this.selectClassifyId = this.classifyList.length ? this.classifyList[0].ClassifyId : "";
      //     // this.getFrequencyList();
      //     this.getTableList()
      //   }
      // });
      let res=await dataInterence.getClassify()
      if(res.Ret===200){
        let arr=[]
        let arr2=[]
        res.Data.List&&res.Data.List.forEach(item=>{
          item.Child.forEach(_item=>{
            if(_item.ClassifyName==='利率债'||_item.ClassifyName==='宏观经济'){
              arr2.push(_item)
            }else{
              arr.push(_item)
            }
          })
          // arr.push(...item.Child)
        })
        this.classifyList=[...arr,...arr2]
        if(e==='update') return
        this.selectClassifyId = this.classifyList.length ? this.classifyList[0].ClassifyId : "";
        this.getTableList()
      }
    },

    // 左侧分类切换
    handleClassifyChange(e) {
      this.selectClassifyId = e.ClassifyId;
      this.frequency='日度'
      this.showFrequency=true
      this.leftSearchVal=''
      this.leftSearchTradeCode=null
      this.searchList=[]
      // this.leftSearchList=[]
      this.getTableList()
    },

    //频度切换
    handleFrequencyChange(e) {
      this.frequency = e;
      this.getTableList();
    },

    // 此处 处理在日期选择组件上右键 显示菜单bug
    mousedown(event) {
      // event.button 0左键 2右键
      if (event.button === 2) {
        this.readonly = true;
      } else {
        this.readonly = false;
      }
    },

    //鼠标右键
    rightClick(e) {
      if(this.role=='special_researcher') return
      // console.log(e.target.dataset);
      // console.log(e.target.parentNode.dataset)
      let rindex=e.target.dataset.rindex
      let cindex=e.target.dataset.cindex
      if(!rindex){
        rindex=e.target.parentNode.dataset.rindex 
        cindex=e.target.parentNode.dataset.cindex 
      }

      this.rightMouseMenu.show = true;
      this.rightMouseMenu.left = e.clientX + "px";
      this.rightMouseMenu.top = e.clientY + "px";
      this.rightMouseMenu.rindex = Number(rindex);
      this.rightMouseMenu.cindex = Number(cindex);
    },

    //删除整行
    async handleDeleteTargetByDate(){
      // 判断该行是否有日期 有则 将timeArr 中该日期去除
      if(this.tableData[this.rightMouseMenu.rindex].timeVal){
        this.timeArr=this.timeArr.filter(item=>item!=this.tableData[this.rightMouseMenu.rindex].timeVal)
        this.currentIndex--
      }

      //判断该行是否有数据 没有直接删除 不请求接口
      let valArr=[]
      this.tableData[this.rightMouseMenu.rindex].list.forEach(item=>{
        if(item.item.Close){
            valArr.push(item.item.Close)
        }
      })
      if(!valArr.length){
        this.tableData.splice(this.rightMouseMenu.rindex,1)
        return
      }

      let codeArr=[]
      this.tableData[this.rightMouseMenu.rindex].list.forEach(item=>{
        if(item.TradeCode){
          codeArr.push(item.TradeCode)
        }
      })
      console.log(codeArr);

      const res=await dataInterence.deleteTargetByDate({
        CreateDate:this.tableData[this.rightMouseMenu.rindex].timeVal,
        TradeCodeList:codeArr
      })
      if(res.Ret===200){
        this.$message.success('删除成功')
        this.tableData.splice(this.rightMouseMenu.rindex,1)
      }else{
        this.$message(res.msg)
      }
    },

    //删除列
    async handleDeleteTargetByCode(){
      if(this.rightMouseMenu.cindex<0){
        this.$message.warning('该列不可删除')
        return
      }

      let TradeCode=this.tableHeadData[this.rightMouseMenu.cindex].TradeCode
      // 删除的是没有数据的列
      if(!TradeCode){
        this.tableHeadData.splice(this.rightMouseMenu.cindex,1)
        this.tableData.forEach(item=>{
          item.list.splice(this.rightMouseMenu.cindex,1)
        })
        this.$message.success('删除成功')
        return
      }

      // 删除的是新增的列 但未填写数据
      const dataList=this.tableHeadData[this.rightMouseMenu.cindex].DataList
      if(!dataList||dataList.length===0){
        this.tableHeadData.splice(this.rightMouseMenu.cindex,1)
        this.tableData.forEach(item=>{
          item.list.splice(this.rightMouseMenu.cindex,1)
        })
        this.$message.success('删除成功')
        return
      }

      const res=await dataInterence.deleteTargetByCode({
        TradeCode:TradeCode
      })
      if(res.Ret===200){
        this.$message.success('删除成功')
        this.tableHeadData.splice(this.rightMouseMenu.cindex,1)
        this.tableData.forEach(item=>{
          item.list.splice(this.rightMouseMenu.cindex,1)
        })
        this.handleUpdateClassify()
      }else{
        this.$message(res.msg)
      }
    },

    //新增列
    handleInsertCol(){
      let temHeadDataItem={SecName: "",TradeCode: "",Frequency: "",Unit: "",ModifyDate: "",Status: "",DataList: []}
      this.tableHeadData.splice(this.rightMouseMenu.cindex+1,0,temHeadDataItem)
      this.tableData.forEach(item=>{
        let tem={SecName:'',TradeCode:'',item:{Close:'',Dt:item.timeVal}}
        item.list.splice(this.rightMouseMenu.cindex+1,0,tem)
      })
    },

    // 新增/删除 行列
    handleOptTable(e) {
      this.rightMouseMenu.show = false;
      if (e === "插入行") {
        let temList = this.tableHeadData.map((item) => {
          let obj={ SecName: item.SecName, TradeCode: item.TradeCode, item: { Close: "",Dt:'' } }
          return obj;
        });
        let temItem = {timeVal:'',list:JSON.parse(JSON.stringify(temList))}
        this.tableData.splice(this.rightMouseMenu.rindex + 1, 0, temItem);
      }else if(e==='删除行'){
        this.handleDeleteTargetByDate()
      }else if(e==='删除列'){
        this.handleDeleteTargetByCode()
      }else if(e==='插入列'){
        this.handleInsertCol()
      }
    },

    //取消导入
    cancelHandle() {
      this.isShowinsert = false;
    },

    //导入成功
    importSuccess() {
      this.isShowinsert = false;
      this.getTableList()
      this.handleUpdateClassify()
    },
  },
};
</script>

<style>
.data-entry-wrap .right-wrap .el-date-editor.el-input {
  width: auto;
}
.data-entry-wrap .right-wrap .el-date-editor .el-input__inner {
  border: none;
  text-align: center;
}
.data-entry-wrap .right-wrap .el-select .el-input--suffix .el-input__inner{
    background: transparent;
    border: none;
    text-align: center;
    padding: 0;
}
</style>

<style lang="scss" scoped>
.data-entry-wrap {
  display: flex;
  .wrap-box {
    background: #ffffff;
    border: 1px solid #ececec;
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
    border-radius: 4px;
    padding: 15px;
    height: calc(100vh - 160px);
  }
  .left-wrap {
    min-width: 300px;
    width: 300px;
    margin-right: 20px;
    box-sizing: border-box;
    .classify-list {
      padding: 0 10px;
      height: calc(100% - 176px);
      overflow-y: scroll;
      &::-webkit-scrollbar {
        width: 0px !important;
      }
      .classify-item {
        text-align: left;
        font-size: 15px;
        // height: 40px;
        margin-bottom: 20px;
        cursor: pointer;
        color: #666;
      }
      .active-classify {
        color: #409eff;
      }
    }
  }
  .right-wrap {
    width: 80%;
    .sticky {
      position: sticky;
      border-right: 1px solid #dcdfe6;
    }
    .table-con {
      overflow: auto;
      height: calc(100% - 124px);
      &::-webkit-scrollbar{
        width: 5px !important;
      }
    }
    table {
      border-color: #dcdfe6;
      border-bottom: 1px solid #dcdfe6;
      border-right: 1px solid #dcdfe6;
      border-collapse: separate;
    }
    thead {
      position: sticky;
      z-index: 2;
      top: 0;
      background-color: #f0f2f5;
      td {
        background-color: #f0f2f5;
      }
    }
    td {
      min-width: 220px;
      max-width: 220px;
      height: 40px;
      text-align: center;
      color: #666;
      box-sizing: border-box;
      padding: 0 5px;
      background-color: #fff;
      border-top: 1px solid #dcdfe6;
      border-left: 1px solid #dcdfe6;
    }
    .s-td{
      border: 2px solid #409EFF;
    }

    .frequency-wrap {
      margin-top: 20px;
      .item {
        cursor: pointer;
        width: 105px;
        height: 40px;
        background: #ecf5ff;
        border: 1px solid #b3d8ff;
        border-radius: 4px;
        color: #409eff;
        display: inline-block;
        line-height: 40px;
        text-align: center;
        margin-right: 30px;
      }
      .active {
        color: #fff;
        background: #409eff;
        box-shadow: 0px 3px 6px rgba(49, 78, 223, 0.16);
      }
    }
    .input-val-box {
      border: none;
      text-align: center;
      color: #666;
      height: 100%;
    }
    .input-val-box:disabled{
      background: transparent;
    }
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
      -webkit-appearance: none !important;
      margin: 0;
    }
    input[type="number"] {
      -moz-appearance: textfield;
    }
  }
}

.right-mouse-menu {
  position: fixed;
  z-index: 999;
  background: #ffffff;
  border: 1px solid #ececec;
  box-shadow: 0px 3px 6px rgba(143, 143, 143, 0.16);
  border-radius: 4px;
  color: #333;
  font-size: 15px;
  padding: 13px 0;
  .item {
    line-height: 30px;
    padding: 0 20px;
    cursor: pointer;
    &:hover {
      background-color: #f5f7fa;
    }
  }
}
.left-wrap /deep/ .el-button{
  font-size: 16px;
  padding: 10px 8px;
}
</style>
