<template>
  <div class="customSheet-wrap">
    <div class="wrap-top">
      <ul class="form-ul">
        <li>
          <selectTarget
            ref="selectRef"
            @select="handleSelectTarget"
            :selectStyleType="2"
          />
        </li>
        <li>
          表格名称
          <el-input
            v-model="sheetForm.name"
            placeholder="请输入表格名称"
            style="width:200px"
            clearable>
          </el-input>
        </li>
        <li>
          表格分类
          <el-select 
            v-model="sheetForm.classify" 
            placeholder="请选择表格分类"
            clearable
          >
							<el-option
								v-for="item in classifyArr"
								:key="item.ExcelClassifyId"
								:label="item.ExcelClassifyName"
								:value="item.ExcelClassifyId"
              />
						</el-select>
        </li>
        <li>
          表格类型
          <el-select 
            v-model="sheetForm.sheetType"
            style="width:150px;"
          >
							<el-option
								v-for="item in sheetTypeOption"
								:key="item.key"
								:label="item.label"
								:value="item.key"
              />
						</el-select>
        </li>
        <li>
          表格说明
          <el-tooltip
            effect="dark"
          >
            <div
              slot="content"
              v-html="rules"
              style="line-height: 20px;width:350px"
            ></div>
            <i class="el-icon-question" />
          </el-tooltip>
        </li>
      </ul>
      <div>
        <el-button type="primary" size="medium" @click="saveSheetHandle">保存</el-button>
        <el-button type="primary" size="medium" plain @click="backHandle">返回</el-button>
      </div>
    </div>
    
    <CustomTable
      :sheetType="sheetForm.sheetType"
      ref="customTableRef"
    />
  </div>
</template>

<script>
import * as sheetInterface from '@/api/modules/sheetApi.js';
import { dataBaseInterface } from 'api/api.js';
import selectTarget from '@/views/chartRelevance_manage/components/selectTarget.vue';
import CustomTable from './components/CustomTable.vue'
import html2canvas from 'html2canvas';
export default {
  components: { selectTarget,CustomTable },
  data() {
    return {
      sheetId: this.$route.query.id || '',
      classifyArr: [],
      rules: `表格说明：<br>
        从ETA指标库和ETA预测指标库向表格添加指标，以第一个添加指标的日期序列为准，默认取最新12个值的日期，其他指标匹配日期，若某日期无值，则通过线性插值法【(Y-Y1)/(X-X1)=(Y2-Y1)/(X2-X1)】计算填入，区分颜色表示，日期默认降序，可切换排序，指标更新时，日期和数据值自动更新；`,
      sheetForm: {
        sheetType: 1
      },
      sheetTypeOption: [
        { key: 1,label: '指标列+日期行' },
        { key: 2,label: '指标行+日期列' },
      ],

    }
  },
  methods: {

    backHandle() {
      window.close()
    },

    /* 获取表格详情 */
    async getDetail() {
      if(!this.sheetId) return

      const res = await sheetInterface.sheetDetail({
				ExcelInfoId: Number(this.sheetId)
			})

      if(res.Ret !== 200)  return
      const { ExcelName,ExcelClassifyId,ExcelType,TableData } = res.Data;
      
      this.sheetForm = {
        name: ExcelName,
        classify: ExcelClassifyId,
        sheetType: ExcelType
      }

      this.$refs.customTableRef.initSheetData(TableData);
    },

    /* 选择指标push指标数组 */
    async handleSelectTarget(e) {
      if(!e) return

      const { EdbName,EdbInfoId,Unit,Frequency } = e;
      if(this.$refs.customTableRef.config.data.find(_ => _.EdbInfoId===EdbInfoId)) return this.$message.warning('指标已存在')
      
      const {Data} = this.$refs.customTableRef.config.data.length 
      ? await sheetInterface.getEdbInsertDataOther({EdbInfoId: EdbInfoId,DateList: this.$refs.customTableRef.dateArr})
      : await sheetInterface.getEdbInsertDataA({EdbInfoId: EdbInfoId,Num: 12})
      
      this.$refs.customTableRef.updateEdbData({
        Data: Data.Data.map(_ => ({..._,DataTimeType: 1,})),
        EdbAliasName: '',
        EdbName,
        Unit,
        Frequency,
        EdbInfoId,
      })

      this.$refs.selectRef.search_txt =''
    },

    /* 获取分类 */
    getClassify() {
      sheetInterface.excelClassifyOne().then(res => {
        if(res.Ret !==200) return
        
        this.classifyArr = res.Data.AllNodes || [];
      })
    },


    /* 保存表格 */
    saveSheetHandle: _.debounce(async function() {
      const { name,classify,sheetType } = this.sheetForm;
      if(!name || !classify) return this.$message.warning(name ? '请选择表格分类' : '请输入表格名称')

      if(!document.getElementsByClassName('table')[0]) return this.$message.warning('请添加表格')

      let canvas = await html2canvas(document.getElementsByClassName('table')[0],{
        scale:2,
        useCORS: true,
        backgroundColor:null,
        imageTimeout:0,
        allowTaint:true,
      })
      let imagesrc = canvas.toDataURL('image/png');
      // console.log(imagesrc)
      const formData = new FormData();
      formData.append('Image',imagesrc);
      const { Data } = await dataBaseInterface.uploadImg(formData)

      
      let params = {
        ExcelName: name,
        ExcelType: sheetType,
        ExcelClassifyId: classify,
        ExcelImage: Data.ResourceUrl,
        Source: 2,
        TableData: this.$refs.customTableRef.getSaveParams()
      };

      const res = this.sheetId
      ? await sheetInterface.sheetEdit({ ExcelInfoId: Number(this.sheetId),...params })
      : await sheetInterface.sheetAdd(params)

      if(res.Ret !==200) return
      
      this.sheetId = this.sheetId || res.Data.ExcelInfoId;
      this.$message.success('保存成功')
      
      // this.$router.replace({
      //   path: '/sheetList',
      //   query: {
      //     code: UniqueCode,
      //     id: ExcelInfoId
      //   }
      // })
    },300),
    
  },
  created() {
    this.getClassify();
    this.getDetail();
  }
}
</script>
<style scoped lang="scss">
*{ box-sizing: border-box; }
.customSheet-wrap {
  min-height: calc(100vh - 120px);
  .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);
    display: flex;
    z-index: 1;
    .form-ul {
      flex: 1;
      display: flex;
      align-items: center;
      li {
        margin: 0 10px;
        padding-top: 40px;
        &:first-child {
          padding-top: 0;
        }
      }
    }
  }
}
</style>