<template>
  <div class="edb-detail-data-wrap">
    <div class="handle-list">
      <span class="editsty" @click="$emit('handle',{item:edbInfo.Detail,type:'edit'})" v-if="hasEditAuth"><!-- 编辑 -->{{$t('Table.edit_btn')}}</span>

      <span class="editsty" @click="$emit('handle',{item:edbInfo.Detail,type:'addToBase'})" v-if="edbInfo.Detail&&edbInfo.Detail.IsJoinEdb===0&&permissionBtn.isShowBtn('dataSourcePermission','manualDataWrite_add')"><!-- 加入指标库 -->{{$t('ManualEntryPage.add_tobase')}}</span>

      <span class="editsty" @click="$emit('handle',{item:edbInfo.Detail,type:'logs'})"><!-- 操作日志 -->{{$t('ManualEntryPage.opera_logs')}}</span>

      <span class="deletesty" @click="$emit('handle',{item:edbInfo.Detail,type:'del'})" v-if="edbInfo.Detail&&edbInfo.Detail.IsJoinEdb===0&&permissionBtn.isShowBtn('dataSourcePermission','manualDataWrite_del')"><!-- 删除 -->{{$t('Table.delete_btn')}}</span>
    </div>
		<el-table
			:data="tableData"
			class="firstColumTable" 
      border
    >
			<el-table-column
				v-for="item in tableColumsOne"
				:key="item.key"
				:width="item.widthsty"
        :label="item.label"
				:min-width="item.minwidthsty"
				align="center">
				<template slot-scope="scope">

						<span v-if="item.key === 'Unit'">{{ getUnitTrans(scope.row.Unit) }}</span>
						<span v-else-if="item.key === 'Frequency'">{{ getFrequencyTrans(scope.row.Frequency) }}</span>

						<span v-else>{{ scope.row[item.key] }}</span>
				</template>
			</el-table-column>
		</el-table>
		<el-table
			:data="tableData"
			style="box-shadow: 0px 3px 6px rgba(155, 170, 219, 0.2);"
			border>
			<el-table-column
				v-for="item in tableColumsTwo"
				:key="item.label"
				:label="item.label"
				:width="item.widthsty"
				:min-width="item.minwidthsty"
				align="center"
			>
				<template slot-scope="scope">
					<span>{{ scope.row[item.key] }}</span>
				</template>
			</el-table-column>
			<div slot="empty" style="padding: 50px 0 50px;">
					<tableNoData :text="$t('Table.prompt_slogan')"/>
			</div>
		</el-table>

    <div class="bottom">
      <div class="left-select" ref="url" v-if="yearsList.length">
        <el-button 
          type="primary"
          v-for="year in yearsList"
          :key="year"
          @click="handleLinkPostion(year)"
        >{{year}}</el-button>
      </div>

      <div 
        class="value-ul" 
        ref="valueUl"
        @scroll="handleLoadData"
      >
        <div class="total-cont" :style="{height: totalHeight}" v-if="dataList.length"></div>
        <ul 
          class="list-wrapper" 
          @contextmenu.prevent="handleRightClick"
          v-if="dataList.length"
        >
          <li
            class="value-item"
            v-for="(item,rindex) in renderDataList"
            :key="rindex"
          >
            <div 
              :class="['value-label',
                { 'select': rindex===rightMouseMenu.rindex && rightMouseMenu.cindex === 0 }
              ]"
            >
              <el-date-picker
                v-model="item.Dt"
                type="date"
                :placeholder="$t('Edb.InputHolderAll.input_date')"
                :data-rindex="rindex"
                :data-cindex="0"
                :clearable="false"
                :editable="false"
                value-format="yyyy-MM-dd"
                :readonly="readonly"
                :disabled="!hasEditAuth"
                @mousedown.native="e=> { readonly = e.button===2?true:false }"
                prefix-icon="none"
                @input="handleTimeChange(rindex, item)"
                @focus="handleTimeFocus(rindex, item)"
              ></el-date-picker>
            </div>
            <div 
              :class="['value-label',
                { 'select': rindex===rightMouseMenu.rindex && rightMouseMenu.cindex === 1 }
              ]"
              :data-rindex="rindex"
              :data-cindex="1"
            >
              <input
                @focus="handleInputFocus(item, rindex, 1)"
                @blur="handleInputChange(item)"
                @input="handleInput(item)"
                class="input-val-box"
                type="number"
                v-model="item.Close"
                :data-rindex="rindex"
                :data-cindex="1"
                :disabled="!hasEditAuth"
              />
            </div>
          </li>
        </ul>

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


    <!-- 右键菜单 -->
    <div
      class="right-lick-menu"
      @mouseleave="hideContextMenu"
    >
      <div class="item" @click="handleOptTable('insert_up_row')">
        <!-- 向上插入 -->{{$t('ManualEntryPage.insert_up_row')}}
        <el-input v-model="rightMouseMenu.insertUpRows" size="mini" style="width:50px;" @change="val => { rightMouseMenu.insertUpRows = Number(val) }" @click.native.stop/>
      </div>
      <div class="item" @click="handleOptTable('insert_down_row')">
        <!-- 向下插入 -->{{$t('ManualEntryPage.insert_down_row')}}
        <el-input v-model="rightMouseMenu.insertDownRows" size="mini" style="width:50px;" @change="val => { rightMouseMenu.insertDownRows = Number(val) }" @click.native.stop/>
      </div>
      <div class="item" @click="handleOptTable('del_row')"><!-- 删除行 -->{{$t('ManualEntryPage.right_op_delrow')}}</div>
    </div>
	</div>
</template>
<script>
import { dataInterence } from '@/api/api.js';
export default {
  props: {
    id: {
      type: String
    }
  },
  computed: {
		tableColumsOne(){
			return [
				{
					label: this.$t('Edb.Detail.e_id'),
					key: 'TradeCode',
					minwidthsty: '150px'
				},
				{
					label: this.$t('Edb.Detail.e_name'),
					key: 'SecName',
					minwidthsty: '200px'
				},
				{
					label: this.$t('Edb.Detail.e_fre'),
					key: 'Frequency',
					widthsty: '100px'
				},
				{
					label: this.$t('Edb.Detail.e_unit'),
					key: 'Unit',
					widthsty: '100px'
				},
			]
		},

		tableColumsTwo() {
			return [
				{
					label: this.$t('Edb.Detail.e_menu'),
					key: 'ClassifyName',
					minwidthsty: '150px',
				},
				{
					label: this.$t('Edb.Detail.e_start_time'),
					key: 'StartDate',
					minwidthsty: '115px',
				},
				{
					label: this.$t('Edb.Detail.e_update_time'),
					key: 'ModifyTime',
					minwidthsty: '120px',
				},
				{
					label: this.$t('Edb.creater'),
					key: 'UserName',
					widthsty: '160px',
				}
			]
		},

    yearsList() {
      if(!this.edbInfo.Detail) return []
      if(!['日度','周度'].includes(this.edbInfo.Detail.Frequency)) return []

      let years = [];
      this.dataList.forEach(_ => {
        if(!years.includes(_.Dt.substring(0,4))&&_.Dt) {
          years.push(_.Dt.substring(0,4))
        }
      })
      return years;
    },

    totalHeight() {
      return `${this.dataList.length*45}px`
    },

    renderDataList() {
      console.log(this.startIndex,this.endIndex)
      console.log(this.dataList.slice(this.startIndex,this.endIndex))
      return this.dataList.slice(this.startIndex,this.endIndex)
    },

    hasEditAuth() {
      return this.permissionBtn.isShowBtn('dataSourcePermission','manualDataWrite_edit')
    }

  },
  watch: {
    id(newval) {
      if(!newval) return 
      this.$refs.valueUl.scrollTop = 0;
      this.rightMouseMenu.rindex=-1;
      this.rightMouseMenu.cindex=-1;
      this.getEdbDetail()
    }
  },
  data() {
    return {
      tableData: [],
      edbInfo: {},
      // yearsList: [],
      dataList: [],
      startIndex: 0,
      endIndex: 100,

      readonly:  false,//日期只读
      temInputVal:{},
      tempTime:'',

      rightMouseMenu: {
        rindex:-1,
        cindex:-1,
        insertUpRows: 1,
        insertDownRows: 1,
      }
    }
  },
  mounted(){
    this.getEdbDetail()
  },
  methods:{
    /* 获取指标详情 */
    async getEdbDetail() {
      let loading = this.$loading({
        lock: true,
        text: `${this.$t('Table.data_loading')}...`,
        target: '.edb-detail-data-wrap',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.8)'
      })

      const res = await dataInterence.getEdbDetailV2({
        TradeCode: this.id
      })

      loading.close()
      if(res.Ret !== 200) return 
      this.edbInfo = res.Data;
      res.Data.Detail.ClassifyName = res.Data.ClassifyList.map(_ => _.ClassifyName).join('/')
      this.tableData = [res.Data.Detail]
      
      this.dataList = res.Data.Detail.DataList||[];
      this.dataList.length && this.$nextTick(() => {
        this.handleLoadData()
      })
    },

    /* 滚动加载位置数据 */
    handleLoadData: _.throttle(function() {
      const scrollTop = this.$refs.valueUl.scrollTop;
      const visibleCount = Math.ceil(
        this.$refs.valueUl.clientHeight / 45
      )+5;

      console.log(visibleCount)

      this.startIndex = Math.floor(scrollTop / 45);
      this.endIndex = this.startIndex + visibleCount;

      this.$nextTick(() => {
        $('.list-wrapper')[0].style=`transform: translateY(${this.startIndex*45}px)`
      })
    },300),

    handleLinkPostion(year) {
      let index = this.dataList.findIndex(_ => _.Dt.substring(0,4)===year)
      console.log(index)
      this.$refs.valueUl.scrollTop = index*45
      this.handleLoadData()
    },

    /* 更改日期 */
    async handleTimeChange(index, e) {
        // 判断选择的日期是否重复
      let arr = this.dataList.filter((item) => item.Dt&&(item.Dt===e.Dt));
      if (arr.length>1) {
        if (!this.tempTime) {
          // 如果是新增行的
          e.Dt = "";
        } else {
          e.Dt = this.tempTime;
        }
        this.$message.warning(/* "该日期已存在"  */this.$t('Edb.MsgPrompt.date_haved_msg'));
      } else {
          if(!this.tempTime) return

          // 修改日期
          let params = {
            TradeCode: e.TradeCode,
            CreateDate: e.Dt, //新录入日期
            OldCreateDate: this.tempTime, //之前日期
            Close: e.Close,
          };
          const res = await dataInterence.editData(params);
          if (res.Ret === 200) {
            this.$message.success("修改成功");
          }
      }
    },

     // 日期获取焦点存放日期
    handleTimeFocus(index, e) {
      if(!this.hasEditAuth) return 

      this.tempTime = e.Dt;
      this.rightMouseMenu.rindex = index;
      this.rightMouseMenu.cindex = 0;
    },

    // input 获取焦点
    handleInputFocus(e, rindex, cindex) {
      console.log(e, rindex, cindex)

      if(!this.hasEditAuth) return 

      this.rightMouseMenu.rindex = rindex;
      this.rightMouseMenu.cindex = cindex;
      this.temInputVal = _.cloneDeep(e)
    },

    // input 值改变 失去焦点
    async handleInputChange(e) {
      console.log(e);

      // 如果input 为改变 且 之前也为空
      if (!this.temInputVal.Close && !e.Close) {
        return;
      }

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

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

      // 修改情况
      // 检查该日期下是否存在数据
      let checkRes = await dataInterence.checkData({
        TradeCode: e.TradeCode,
        CreateDate: e.Dt,
      });
      if (checkRes.Data.Status === 0) {
        const editRes = await dataInterence.editData({
          TradeCode: e.TradeCode,
          CreateDate: e.Dt,
          Close: e.Close,
          OldCreateDate: "",
        });
        if (editRes.Ret === 200) {

          this.$message({
            message: /* "新增成功" */this.$t('MsgPrompt.add_msg'),
            type: "success",
          });
        } else {
          this.$message({
            message: editRes.msg,
            type: "warning",
          });
          this.getTableList();
        }
      } else if (checkRes.Data.Status === 1) {
        this.$confirm(
          this.$t('Edb.MsgPrompt.date_have_value_msg',{val:checkRes.Data.Close}),
          /* "提示" */this.$t('Dialog.warn_tit'),
          {
            type: "warning",
          }
        )
          .then(async () => {
            const editRes = await dataInterence.editData({
              TradeCode: e.TradeCode,
              CreateDate: e.Dt,
              Close: e.Close,
              OldCreateDate: e.Dt,
            });
            if (editRes.Ret === 200) {
              this.$message({
                message: /* "修改成功" */this.$t('MsgPrompt.edit_msg'),
                type: "success",
              });
            } else {
              this.$message({
                message: editRes.msg,
                type: "warning",
              });
              this.getTableList();
            }
          })
          .catch(() => {
            this.getTableList();
          });
      }
    },

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

    /* 右键 */
    handleRightClick(e) {
      if(!this.hasEditAuth) return 

      let dom = $('.right-lick-menu')[0];
      if(e.clientY > window.innerHeight/2) {
        dom.style.left = e.clientX-3 + 'px';
        dom.style.top = e.clientY-dom.offsetHeight-3 + 'px';
      }else {
        dom.style.left = e.clientX-3 + 'px';
        dom.style.top = e.clientY-3 + 'px';
      }
    },

    // 隐藏
    hideContextMenu() {
      let dom = $('.right-lick-menu')[0];
			dom.style.left = '-9999px';
			dom.style.top = '-9999px';
      this.rightMouseMenu.insertUpRows = 1;
      this.rightMouseMenu.insertDownRows = 1
    },

    // 插入操作
    handleOptTable(type) {
      const handlesMap = {
        'insert_up_row': this.insertRow,
        'insert_down_row': this.insertRow,
        'del_row': this.delRow
      }
      handlesMap[type] && handlesMap[type](type)
    },
    
    //插入行
    insertRow(type) {
      let newItem = {
        Close: '',
        Dt: '',
        TradeCode: this.edbInfo.Detail.TradeCode
      }
      if(type==='insert_up_row') {
        let insertArr = new Array(this.rightMouseMenu.insertUpRows).fill('').map(item => _.cloneDeep(newItem))
        this.dataList.splice(this.rightMouseMenu.rindex, 0, ...insertArr);
      }else {
        let insertArr = new Array(this.rightMouseMenu.insertDownRows).fill('').map(item => _.cloneDeep(newItem))
        this.dataList.splice(this.rightMouseMenu.rindex+1, 0, ...insertArr);
      }

      console.log(this.dataList)
    },

    delRow() {
      this.dataList.splice(this.rightMouseMenu.rindex, 1);
    }
  },
}
</script>
<style scoped lang='scss'>
.edb-detail-data-wrap{
	display: flex;
	flex-direction: column;
	height: 100%;
	.firstColumTable{
		box-shadow: 0px 3px 6px rgba(155, 170, 219, 0.2);
	}
  .handle-list { 
    flex: 0;
    display: flex;
    justify-content: flex-end;
    gap: 20px;
    margin-bottom: 15px;
  }
	.el-table{
		flex: none;
	}
  .bottom {
    flex: 1;
    display: flex;
    overflow: hidden;
    .value-ul{
      flex: 1;
      max-height: 100%;
      overflow-y: auto;
      border: 1px solid #EBEFF6;
      box-shadow: 0px 3px 6px rgba(155, 170, 219, 0.2);
      position: relative;
      .total-cont {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        z-index: -2;
      }
      .list-wrapper {
        left: 0;
        right: 0;
        top: 0;
        position: absolute;
        .value-item {
          border-bottom: 1px solid #dcdfe6;
          display: flex;

          .value-label {
            width: 50%;
            padding: 2px;
            position: relative;
            text-align: center;
            color: #666;
            &:first-child {
              border-right: 1px solid #dcdfe6;
            }
            &.select::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, 0.5);
            }
            .value-style{
              padding:5px;
              border-radius: 4px;
              &.predict-act {
                color: orange;
              }
            }
          }

          .input-val-box {
            width: 100%;
            height: 100%;
            border: none;
            text-align: center;
            color: #666;
          }
          .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;
          }
        }
      }
      .nodata {
        text-align: center;
        padding: 40px 0;
        color: #999;
      }
    }

    .left-select {
      width: fit-content;
      max-height: 90%;
      border: 1px solid #EBEFF6;
      padding: 10px 15px;
      overflow-y: auto;
      .el-button { display: block;margin:10px 0; }
    }
  }

  .right-lick-menu  {
    position: fixed;
    z-index: 99;
    top: -9999px;
    left: -9999px;
    background: #fff;
    padding: 10px 0;
    min-width: 180px;
    max-height: 400px;
    overflow-y: auto;
    /* border: 1px solid #999; */
    box-shadow: 0 1px 4px #999;
    .item {
      padding: 10px 25px;
      cursor: pointer;
      &:hover {
        background-color: #f5f7fa;
      }
      &:hover .subMenu-wrapper {
        display: block;
      }
    }
  }
}
</style>
<style lang="scss">
.edb-detail-data-wrap {
  .value-ul {
    .el-date-editor.el-input {
      width: 100%;
    }
    .el-date-editor .el-input__inner {
      border: none;
      text-align: center;
    }

    .el-input.is-disabled .el-input__inner {
      background-color: #fff;
      color: #666;
    }
  }
}
</style>
