<template>
  <div class="customSheet-wrap">
    <div class="wrap-top">
      <ul class="form-ul">
        <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-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>
        <span v-if="updateTime">上次保存时间：{{updateTime}}</span>
        <el-button type="primary" size="medium" @click="saveSheetHandle" style="margin-left:10px">保存</el-button>
        <el-button type="primary" size="medium" plain @click="backHandle">返回</el-button>
      </div>
    </div>
    
    <MixedTable
      ref="mixedTableRef"
    />
  </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 MixedTable from './components/MixedTable.vue'
import html2canvas from 'html2canvas';
export default {
  components: { selectTarget,MixedTable },
  data() {
    return {
      sheetId: this.$route.query.id || '',
      classifyArr: [],
      rules: `表格说明：<br>
        1、手动输入：单击每个单元格可直接输入文本、数字、日期（格式示例：2023-05-23），输入内容可匹配指标名称，ETA指标库和ETA预测指标库指标均可搜索，在下拉框中选择指标，则该单元格为已选指标行/列。<br>
        2、插入指标值：右键单元格，点击“插入指标值”，则查询该单元格行、列最近的日期和指标名称，将查找到的指标对应日期的值填入该单元格，指标值总是在右下角。<br>
        3、更新与计算规则：表格中指标值的日期不自动更新，数值不支持单元格计算`,
      sheetForm: {
        sheetType: 1
      },
      sheetTypeOption: [
        { key: 1,label: '指标列+日期行' },
        { key: 2,label: '指标行+日期列' },
      ],

      updateTime: ''

    }
  },
  methods: {

    backHandle() {
      this.$router.go(-1)
    },

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

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

      if(res.Ret !== 200)  return
      const { ExcelName,ExcelClassifyId,TableData,ModifyTime } = res.Data;
      
      this.sheetForm = {
        name: ExcelName,
        classify: ExcelClassifyId
      }
      this.updateTime =  this.$moment(ModifyTime).format('YYYY-MM-DD HH:mm:ss')

      this.$refs.mixedTableRef.initData(TableData);
    },

    /* 获取分类 */
    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 ? '请选择表格分类' : '请输入表格名称')

      let checkAllEmpty = this.$refs.mixedTableRef.config.data.flat(1).some(_ => _.ShowValue);
      if(!checkAllEmpty) 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');
      const formData = new FormData();
      formData.append('Image',imagesrc);
      const { Data } = await dataBaseInterface.uploadImg(formData)

      
      let params = {
        ExcelName: name,
        ExcelType: 1,
        ExcelClassifyId: classify,
        ExcelImage: Data.ResourceUrl,
        Source: 3,
        TableData: {
          CellRelation: JSON.stringify(this.$refs.mixedTableRef.insertRelationArr),
          Data: this.$refs.mixedTableRef.config.data
        }
      };

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

      if(res.Ret !==200) return
      this.updateTime = this.$moment().format('YYYY-MM-DD HH:mm:ss')
      
      this.sheetId = this.sheetId || res.Data.ExcelInfoId;
      this.$message.success('保存成功')

    },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;
        &:first-child {
          padding-top: 0;
        }
      }
    }
  }
}
</style>