<template>
  <div class="edit-data-page">
    <div class="wrap-top">
      <div class="left-handle">
        <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('ManualEntryPage.label_vaiety')" prop="menu">
            <el-cascader
              v-model="formData.menu"
              :options="classifyOptions"
              :props="{
                label: 'ClassifyName',
                value: 'ClassifyId',
                children: 'Child',
                emitPath: false,
              }"
              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"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </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>
      </div>
      <div class="right-handle">
        <div>
          <el-button type="primary" size="medium" @click="handleSaveEdb"><!-- 保存 -->{{$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>
      </div>
      
    </div>
    
    <div class="main">
      <div id="excel-container"></div>
    </div>

  </div>
</template>

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

      excelData: [
        {
          r:0,
          c:0,
          v:{
            m: this.$t('Edb.Detail.e_date'),
            v: this.$t('Edb.Detail.e_date'),
            bg:'#bbb'
          },
        },
        {
          r:0,
          c:1,
          v:{
            m:this.$t('Edb.Detail.e_value'),
            v:this.$t('Edb.Detail.e_value'),
            bg:'#bbb'
          },
        },
      ],

    }
  },
  computed: {
    excelOptions() {
      return {
        container: 'excel-container',
        lang: this.$i18nt.locale, // 设定表格语言
        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
          },
          cellMousedownBefore(e,{r,c}){
            if(r===0) return false
          },
        },
      }  
    },

    ...mapState({
			currentLang: state => state.lang,
		}),
    frequencyArr(){
        return frequencySelectList(['半年度'])
    }
  },

  mounted() {
    this.getClassify();
    if(this.$route.query.id) {
      this.getEdbDetail()
    }else {
      this.initExcelOptions();
    }
    
  },

  beforeDestroy() {
    luckysheet.destroy();
  },

  methods: {

    async getEdbDetail() {
      const res = await dataInterence.getEdbDetailV2({
        TradeCode: this.$route.query.id,
      })
      if (res.Ret!==200) return 

      this.edbInfo = res.Data;

      this.formData = {
        targetName: this.edbInfo.Detail.SecName,
        menu: this.edbInfo.Detail.ClassifyId,
        frequency: this.edbInfo.Detail.Frequency,
        unit: this.edbInfo.Detail.Unit
      }
      this.initData()
    },

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

      this.edbInfo.Detail.DataList&&this.edbInfo.Detail.DataList.forEach((item,index) => {
        this.excelData.push({
          r: index+1,
          c:0,
          v:{
            m:item.Dt,
            v:item.Dt
          },
        })
        this.excelData.push({
          r: index+1,
          c:1,
          v:{
            m:item.Close,
            v:item.Close
          },
        })
      })
      luckysheet.create(this.excelOptions)
    },

    getClassify() {
			dataInterence.getClassify().then(res =>{
				if(res.Ret === 200 && res.Data.List) {
					this.classifyOptions = res.Data.List||[];
				}
			})
		},

    /* 保存 */
    async handleSaveEdb() {
      let data = luckysheet.getAllSheets()[0]
      await this.$refs.form.validate();
      
      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 dataInterence.editEdbDataV2({
        EdbName: targetName,
        Frequency: frequency,
        Unit: unit,
        ClassifyId: menu,
        TradeCode: this.$route.query.id,
        Data: DataList
      })

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

      this.$router.replace({path:'/dataList'});
    },  

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

<style lang="scss" scoped>
*{ box-sizing: border-box; }
.edit-data-page {
  .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>