<template>
  <div class="adjust-data-container">
    <div class="wrap-top">
      <div>
        <ul class="min-top" v-if="!edb_id">
          <li>
            <label style="margin-right:5px;">选择指标：</label>
            <el-select
              v-model="select_target"
              v-loadMore="searchLoad"
              :filterable="!select_target"
              clearable
              placeholder="请输入指标名称"
              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="isLookHistory=true;lookEdbId=select_target" v-if="select_target"/>
          </li>
          <li v-show="old_edb_info.id">
            <label style="margin-right:5px;"> 查询结果：( </label>
            <span style="margin-right: 20px">指标ID：{{old_edb_info.id}}</span>
            <span>指标名称：{{old_edb_info.name}})</span>
          </li>
        </ul>
        <div v-if="edb_id" style="margin-bottom:20px">
          <span style="display:inline-block;margin-right:30px">原指标ID：{{EDBInfoOfCalculateData.FromEdbCode}}</span>
          <span>原指标名称：{{EDBInfoOfCalculateData.FromEdbName}}</span>
        </div>
        <el-form
          ref="form"
          label-position="right"
          inline
          label-width="80px"
          :model="formData"
          :rules="formRules"
        >
          <el-form-item label="指标名称" prop="targetName">
            <el-input
              v-model="formData.targetName"
              style="width: 150px"
              placeholder="请输入指标名称"
            />
          </el-form-item>
          <el-form-item label="单位" prop="unit">
            <selectUnit 
							v-model="formData.unit" 
							style="width: 150px"
						/>
          </el-form-item>
          <el-form-item label="指标目录" prop="menu">
            <el-cascader
              v-model="formData.menu"
              :options="classifyOptions"
              :props="{
                label: 'ClassifyName',
                value: 'ClassifyId',
                children: 'Children',
                emitPath: false
              }"
              clearable
              placeholder="请选择指标目录"
            />
          </el-form-item>
          <el-form-item label="频度" prop="frequency">
            <el-select
              v-model="formData.frequency"
              placeholder="请选择频度"
              style="width: 150px"
              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="right-handle">
        <div>
          <el-button type="primary" size="medium" @click="saveSheetHandle">保存</el-button>
          <el-button type="primary" size="medium" plain @click="$router.go(-1)">取消</el-button>
        </div>
        <el-tooltip>
          <div slot="content" v-html="tips"></div>
          <div class="tips-cont">
            <span>使用说明</span>
            <i class="el-icon-question" style="color: #999;"></i>
          </div>
        </el-tooltip>
      </div>
    </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="暂无数据" 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 } 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: '日期',key:'DataTime' },
        { label: '值',key:'Value' }
      ],

      tips: `数据调整：<br>1、将所选指标的历史数据经过调整后保存，该指标更新时将在调整数据的基础上更新最新数据；<br>
      2、支持对所选指标添加未来的数据，指标更新到未来相同的日期时，进行数据更正；<br>
      3、选中表格，使用“Ctrl+F”可调用快速查找功能，支持快速定位到表格中的数据；<br>
      注：系统只取A、B列数据`,

      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.Level === 2) {
						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('请输入表格内容');

      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('保存成功')

      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;
    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;
      align-items: center;
      color: #606266;
      li { margin-right: 35px; }
    }
    .right-handle {
      min-width: 155px;
    }
    .tips-cont {
      margin-top: 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>