<template>
  <div class="adjust-data-container">
    <div class="wrap-top">
      <div class="left-handle">
        <ul class="min-top" v-if="!edb_id">
          <li>
            <label style="margin-right:5px;">{{$t('AdjustDataPage.choose_edb')}}：</label>
            <el-select
              v-model="select_target"
              v-loadMore="searchLoad"
              :filterable="!select_target"
              clearable
              :placeholder="$t('Edb.InputHolderAll.input_name')"
              style="width: 200px"
              remote
              :remote-method="getTarget"
              @click.native="inputFocusHandle"
              @change="chooseTarget"
              @blur="search_have_more = false"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
              <el-option
                v-for="item in searchOptions"
                :key="item.EdbInfoId"
                :label="eta_lang==='en'?(item.EdbNameEn||item.EdbName):item.EdbName"
                :value="item.EdbInfoId"
              >
              </el-option>
            </el-select>
            <i class="el-icon-tickets" style="color:#409EFF;font-size:18px" @click="toHistoryPage(select_target,$route.matched);lookEdbId=select_target" v-if="select_target"/>
          </li>
          <li v-show="old_edb_info.id">
            <label style="margin-right:5px;"> {{$t('AdjustDataPage.search_res')}}：</label>
            <span style="margin-right: 20px">{{$t('Edb.Detail.e_id')}}：{{old_edb_info.id}}</span>
            <span>{{$t('Edb.Detail.e_name')}}：{{old_edb_info.name}}</span>
          </li>
        </ul>
        <div v-if="edb_id" style="margin-bottom:20px">
          <span style="display:inline-block;margin-right:30px">{{$t('AdjustDataPage.or_edbid')}}：{{EDBInfoOfCalculateData.FromEdbCode}}</span>
          <span>{{$t('AdjustDataPage.or_edbname')}}：{{EDBInfoOfCalculateData.FromEdbName}}</span>
        </div>
      </div>
      <div class="right-handle">
        <div>
          <el-button type="primary" size="medium" @click="saveSheetHandle"><!-- 保存 -->{{$t('Dialog.confirm_save_btn')}}</el-button>
          <el-button type="primary" size="medium" plain @click="$router.go(-1)"><!-- 取消 -->{{$t('Dialog.back_btn')}}</el-button>
        </div>
        <el-tooltip>
          <div slot="content" v-html="tips"></div>
          <div class="tips-cont">
            <span><!-- 使用说明 -->{{$t('AdjustDataPage.usetip_msg')}}</span>
            <i class="el-icon-question" style="color: #999;"></i>
          </div>
        </el-tooltip>
      </div>
      <el-form
          ref="form"
          label-position="right"
          inline
          label-width="120px"
          :model="formData"
          :rules="formRules"
        >
          <el-form-item :label="$t('Edb.Detail.e_name')" prop="targetName">
            <el-input
              v-model="formData.targetName"
              style="width: 150px"
              :placeholder="$t('Edb.InputHolderAll.input_name')"
            />
          </el-form-item>
          <el-form-item :label="$t('Edb.Detail.e_unit')" prop="unit">
            <selectUnit 
							v-model="formData.unit" 
							style="width: 120px"
						/>
          </el-form-item>
          <el-form-item :label="$t('Edb.Detail.e_menu')" prop="menu">
            <el-cascader
              v-model="formData.menu"
              :options="classifyOptions"
              :props="{
                label: 'ClassifyName',
                value: 'ClassifyId',
                children: 'Children',
                emitPath: false,
                checkStrictly: true
              }"
              clearable
              :placeholder="$t('Edb.InputHolderAll.input_menu')"
            />
          </el-form-item>
          <el-form-item :label="$t('Edb.Detail.e_fre')" prop="frequency">
            <el-select
              v-model="formData.frequency"
              :placeholder="$t('Edb.InputHolderAll.input_fre')"
              style="width: 120px"
              clearable
            >
              <el-option
                v-for="item in frequencyArr"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
    </div>
    
    <div class="main">
      <div class="table-cont" v-if="!edb_id">
        <el-table
          :data="filterList"
          border
          height="650"
          ref="table"
        >
            <el-table-column
              v-for="item in tableColums"
              :key="item.key"
              :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;">
              <tableNoData :text="$t('Table.prompt_slogan')" size="mini"/>
            </div>
        </el-table>
      </div>
      <div id="excel-container"></div>
    </div>

    <!-- 指标历史记录 -->
    <!-- <edbHistoryDialog
      :isOpenDialog.sync="isLookHistory"
      :edbId="lookEdbId"
    /> -->
  </div>
</template>

<script>
import {dataBaseInterface} from '@/api/modules/chartApi'
import { formRules,frequencyArr } from '../databaseComponents/util';
import { unitArr } from '@/utils/defaultOptions';
import { mapState } from 'vuex';
export default {
  data() {
    return {
      edb_id: this.$route.query.edbid,
      select_target: '',
      formData: {
        targetName: '',
        menu: '',
        frequency: '',
        unit: ''
      },
      formRules,
      unitArr,
      frequencyArr,
      classifyOptions: [],

      searchOptions: [],
      search_have_more: false,
			search_page: 1,
			current_search: '',

      old_edb_info: {
        id: '',
        name: ''
      },
      old_edb_data: [],
      rowHeight: 48,
      page_size: 20,
      start_index: 0,
      end_index: 49,
      tableColums: [
        { label: this.$t('Edb.Detail.e_date'),key:'DataTime' },
        { label: this.$t('Edb.Detail.e_value'),key:'Value' }
      ],

      tips: this.$t('AdjustDataPage.usetip'),

      excelData: [
        {
          r:0,
          c:0,
          v:{
            m:"日期",
            v:"日期",
            bg:'#bbb'
          },
        },
        {
          r:0,
          c:1,
          v:{
            m:"值",
            v:"值",
            bg:'#bbb'
          },
        },
      ],

      /* 查看历史弹窗 */
			isLookHistory: false,
			lookEdbId: 0,
      EDBInfoOfCalculateData:{},
    }
  },
  computed: {
    excelOptions() {
      return {
        container: 'excel-container',
        lang: 'zh', // 设定表格语言
        showinfobar: false,//顶部info
        showsheetbar:false,//底部sheet页 暂禁止添加多个表格
        showtoolbarConfig:{
          image: false,//图片
          print: false,//打印
          chart: false, // '图表'
          postil:  false, //'批注'
          pivotTable: false,  //'数据透视表'
          function: false, // '公式'
          frozenMode: false, // '冻结方式'
          sortAndFilter: false, // '排序和筛选'
          conditionalFormat: false, // '条件格式'
          dataVerification: false, // '数据验证'
          splitColumn: false, // '分列'
          screenshot: false, // '截图'
          findAndReplace: false, // '查找替换'
        },
        cellRightClickConfig: {
          insertColumn: false,
          matrix: false,
          chart: false, // 图表生成
          image: false, // 插入图片
          link: false, // 插入链接
          copyAs: false,
        },
        data: [{
          column: 2,
          scrollTop: 0,
          scrollLeft: 0,
          defaultColWidth: 200,
          defaultRowHeight: 20,
          frozen: [
            {
              type: 'row'
            }
          ],
          celldata: this.excelData,
        }],
        hook:{
          cellUpdateBefore(r,c,value){
            // 禁止更新第一行
            if(r===0) return false
            
            // if(c===0&&value) {
            //   console.log(value)
            //   console.log(isNaN(value)&&!isNaN(Date.parse(value)))
            //   if(isNaN(value)&&!isNaN(Date.parse(value))) {
            //     return true
            //   }else {
            //     bus.$message.warning('请输入正确的日期格式')
            //     return false
            //   }
            // }
          },
          cellMousedownBefore(e,{r,c}){
            if(r===0) return false
          },

          cellAllRenderBefore(a,b,c) {
            // console.log(a,b,c)
          },

          rangePasteBefore(range,data) {
            console.log(range,data)
          }
        },
      }  
    },

    filterList() {
      return this.old_edb_data.slice(this.start_index,this.end_index)
    },

    total_length() {
      return this.old_edb_data.length;
    },

     ...mapState({
			eta_lang: state => state.edb.eta_lang,	
		})
  },

  mounted() {
    this.getMenu();
    if(this.$route.query.edbid) {
      this.getEdaData(this.edb_id)
      this.getEDBInfoOfCalculate()
    }else {
      this.$refs.table.bodyWrapper && this.$refs.table.bodyWrapper.addEventListener('scroll',this.loadMoreData)
      this.initExcelOptions();
    }
    
  },

  beforeDestroy() {
    luckysheet.destroy();
    this.$refs.table && this.$refs.table.bodyWrapper && this.$refs.table.bodyWrapper.removeEventListener('scroll',this.loadMoreData)
  },

  methods: {
    // 获取计算指标与基础指标关联信息
    async getEDBInfoOfCalculate(){
      const res=await dataBaseInterface.getEDBInfoCalculateMap({EdbInfoId:Number(this.edb_id)})
      if(res.Ret===200){
        this.EDBInfoOfCalculateData=res.Data
      }
    },

    async getEdaData() {
      const res = await dataBaseInterface.targetList({
        PageSize: 100000,
        CurrentIndex: this.page_no,
        EdbInfoId: this.edb_id,
      })
      if (res.Ret!==200) return 
      let arr = res.Data.Item.DataList ||[];
      this.old_edb_data = arr;
      this.formData = {
        targetName: res.Data.Item.EdbName,
        menu: res.Data.ClassifyList[0].ClassifyId,
        frequency: res.Data.Item.Frequency,
        unit: res.Data.Item.Unit
      }
      this.resetData()
    },

    /* 获取目录结构 */
		getMenu() {
			dataBaseInterface.menuListV3().then((res) => {
				if (res.Ret === 200) {
					this.filterNodes(res.Data.AllNodes||[])
					this.classifyOptions = res.Data.AllNodes || [];
				}
			});
		},
		// 递归改变第三级目录结构
		filterNodes(arr) {
			arr.length &&
				arr.forEach((item) => {
					item.Children.length && this.filterNodes(item.Children);
					if (!item.Children.length) {
						delete item.Children;
					}
				});
		},

    /* 指标列表 */
		getTarget(query) {
			this.search_page = 1;
			this.current_search = query;
			this.searchApi(this.current_search);
		},

		/* 聚焦获取当前检索 */
		inputFocusHandle(e) {
			this.search_page = 1;
			this.current_search = e.target.value;
			this.searchApi(this.current_search);
		},

		searchApi(query,page=1) {
			dataBaseInterface.targetSearchByPage({
				KeyWord:query,
				CurrentIndex: page
			}).then(res => {
				if(res.Ret !== 200) return

				const { List,Paging } = res.Data;
				this.search_have_more = page < Paging.Pages;
				let arr = page === 1 ? List : this.searchOptions.concat(List);

				this.searchOptions = this.$route.query.edbid ? arr.filter(item => item.EdbInfoId !== this.$route.query.edb_id) : arr;
					
			})
		},

		searchLoad() {
			if(!this.search_have_more) return;
			this.searchApi(this.current_search,++this.search_page)
		},

    /* 选择指标 */
    async chooseTarget(val) {
      if(val) {
        this.old_edb_info = {
          id: this.searchOptions.find(_ => _.EdbInfoId === val) ? this.searchOptions.find(_ => _.EdbInfoId === val).EdbCode : '',
          name: this.searchOptions.find(_ => _.EdbInfoId === val) ? this.searchOptions.find(_ => _.EdbInfoId === val).EdbName : ''
        }
        const res = await dataBaseInterface.targetList({
          PageSize: 100000,
          CurrentIndex: this.page_no,
          EdbInfoId: val,
        })
        if (res.Ret!==200) return 
        let arr = res.Data.Item.DataList ||[];
        this.old_edb_data = arr;
        this.resetData()
      }else {
        this.old_edb_info = {};
        this.old_edb_data = [];
        this.resetData()
      }
    },

    /* 选择指标后重置数据 */
    resetData() { 
      this.excelData = [
        {
          r:0,
          c:0,
          v:{
            m:"日期",
            v:"日期",
            bg:'#bbb'
          },
        },
        {
          r:0,
          c:1,
          v:{
            m:"值",
            v:"值",
            bg:'#bbb'
          },
        },
      ]

      this.old_edb_data.forEach((item,index) => {
        this.excelData.push({
          r: index+1,
          c:0,
          v:{
            m:item.DataTime,
            v:item.DataTime
          },
        })
        this.excelData.push({
          r: index+1,
          c:1,
          v:{
            m:item.Value,
            v:item.Value
          },
        })
      })
      luckysheet.create(this.excelOptions)
    },

    /* 滚动加载当前数据 */
    loadMoreData() {
      const scrollTop = this.$refs.table.bodyWrapper.scrollTop;
      this.start_index = Math.floor(scrollTop/this.rowHeight);
      this.end_index = this.start_index + this.page_size;
      $('.el-table__body')[0].style=`transform: translateY(${this.start_index*this.rowHeight}px)`
    },

    /* 保存 */
    async saveSheetHandle() {
      let data = luckysheet.getAllSheets()[0]
      await this.$refs.form.validate();
      // console.log(data.celldata)
      if(data.celldata.length < 3) return this.$message.warning(this.$t('AdjustDataPage.input_content_msg'));

      const { targetName,menu,frequency,unit} = this.formData;

      //处理数据格式
      let result_obj = {},DataList=[];
      data.celldata.forEach(item => {
        if(result_obj[item.r]&&item.c===1) {
          result_obj[item.r] = {
            Date: result_obj[item.r].v.m,
            Value: Number(item.v.m)
          }
        } else {
          result_obj[item.r] = item
        }
      })
      for(let key in result_obj) {
        if(result_obj[key].Date && !isNaN(result_obj[key].Value)) DataList.push(result_obj[key]);
      }

      const { Ret,Data } = await dataBaseInterface.adjustEdbEdit({
        EdbName: targetName,
        Frequency: frequency,
        Unit: unit,
        ClassifyId: menu,
        EdbInfoId: Number(this.edb_id)|| 0,
        FromEdbInfoId: this.select_target || 0,
        DataList
      })

      if(Ret !== 200) return
      // this.$message.success('保存成功')
      this.$message.success(this.$t('MsgPrompt.saved_msg'))

      const { UniqueCode,EdbInfoId } = Data;

      this.$router.replace({path:'/database', query: {
        code: UniqueCode,
        id: EdbInfoId
      }});
    },  

    initExcelOptions() {
      this.$nextTick(() => {
        luckysheet.create(this.excelOptions)
      })
    },
  }
}
</script>

<style lang="scss" scoped>
*{ box-sizing: border-box; }
.adjust-data-container {
  .wrap-top {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    /* align-items: center; */
    margin-bottom: 20px;
    padding: 20px;
    background: #fff;
    border: 1px solid #ececec;
    border-radius: 4px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
    z-index: 1;
    .min-top {
      margin-bottom: 10px;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      color: #606266;
      li { margin-right: 35px; }
    }
    .left-handle{
        flex: 1;
    }
    .right-handle {
      min-width: 155px;
      display: flex;
      flex-direction: row-reverse;
      align-items: center;
    }
    .el-form{
        width:100%;
    }
    .tips-cont {
      margin-right: 20px;
    }
  }
  .main {
    position: relative;
    height: 650px;
    display: flex;
    .table-cont {
      width: 260px;
      flex-shrink: 0;
      margin-right: 20px;
      /* height: 600px;
      overflow-y: scroll; */
    }
    #excel-container {
      margin:0;padding:0;
      width:100%;
    }
  }
}
</style>
<style lang="scss">
  .luckysheet .toolbar {
    background: none;
    margin: 0;
    padding: 0;
  }
.luckysheet-input-box {
  z-index: 99999;
}
</style>