<template>
  <div class="customSheet-wrap">
    <div class="wrap-top">
      <div class="database-select">
        <selectTarget
          ref="selectRef"
          @select="handleSelectTarget"
          :selectStyleType="2"
        />
        <div>
          <div v-if="saveTime" style="color:#999999;margin-right:30px ;">
            最近保存时间：{{ saveTime }}
          </div>
          <el-button type="primary" size="medium" @click="saveSheetHandle" v-if="hasPermission">保存</el-button>
          <el-button type="primary" size="medium" plain @click="backHandle">返回</el-button>
        </div>
      </div>
      <div class="wrap-top-bottom">
        <ul class="form-ul">
          <li>
            <el-input
              v-model="sheetForm.name"
              placeholder="请输入表格名称"
              style="width:240px"
              clearable>
            </el-input>
          </li>
          <li>
            <el-select 
              v-model="sheetForm.classify" 
              placeholder="请选择表格分类"
              style="width:240px;"
              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:240px;"
            >
                <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>
    </div>
    
    <CustomTable
      :sheetType="sheetForm.sheetType"
      ref="customTableRef"
      @autoSave="autoSaveFun"
    />
  </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 },
  beforeRouteEnter(to, from, next) {
    if(to.query.id){
      to.matched[1].name=`编辑表格`
    }else{
      to.matched[1].name='添加表格'
    }
    next()
  },
  watch:{
    sheetForm:{
      handler(newVal){
        console.log(newVal,'newVal','newVal');
        if(this.sheetInit && this.sheetId) this.autoSaveFun()
        
      },
      deep:true
    }
  },
  computed:{
    hasPermission(){
      // console.log(this.sheetButton,'sheetButton');
      return this.sheetButton?
            this.permissionBtn.isShowBtn('etaTablePermission','etaTable_customize_data_save')&&this.sheetButton.OpButton:
            this.permissionBtn.isShowBtn('etaTablePermission','etaTable_customize_data_save')
    }
  },
  beforeRouteLeave(to,from,next){
    if(to.path!='/addMixedSheet'){
      this.markFinishStatus()
    }
    next()
  },
  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: '指标行+日期列' },
      ],
      saveTime:"",
      sheetInit:false,
      isCanEdit:false,
      sheetButton:'',
      // 取消自动保存，比如返回的时候
      cancelAutoSave:false
    }
  },
  methods: {

    backHandle() {
      this.$router.back()
      this.cancelAutoSave=true
    },

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

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

      if(res.Ret !== 200)  return
      this.isCanEdit = res.Data.CanEdit
      if(!res.Data.CanEdit){
        this.$message.warning(`${res.Data.Editor}正在编辑中`)
        setTimeout(()=>{
          this.backHandle()
        },1000)
        return 
      }
      const { ExcelName,ExcelClassifyId,ExcelType,TableData,ModifyTime,Button} = res.Data;
      this.sheetButton=Button
      this.sheetForm = {
        name: ExcelName,
        classify: ExcelClassifyId,
        sheetType: ExcelType
      }
      this.saveTime =  this.$moment(ModifyTime).format('YYYY-MM-DD HH:mm:ss')

      this.$nextTick(()=>{
        this.sheetInit=true
      })
      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,
        SortType: this.$refs.customTableRef.config.order===1 ? 'desc' : 'asc'
      })
      : await sheetInterface.getEdbInsertDataA({
        EdbInfoId: EdbInfoId,
        SortType: this.$refs.customTableRef.config.order===1 ? 'desc' : 'asc',
        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({Source: 2}).then(res => {
        if(res.Ret !==200) return
        
        this.classifyArr = res.Data.AllNodes || [];
      })
    },

    autoSaveFun:_.debounce(async function(){
      // console.log("触发自动",this.cancelAutoSave);
      if(!this.sheetId || this.cancelAutoSave) return 
      const { name,classify,sheetType } = this.sheetForm;
      if(!name || !classify) return this.$message.warning(name ? '请选择表格分类' : '请输入表格名称')
      if(!document.getElementsByClassName('table')[0]) return this.$message.warning('请添加表格')
      let params = {
        ExcelName: name,
        ExcelType: sheetType,
        ExcelClassifyId: classify,
        ExcelImage:'',
        Source: 3,
        TableData: this.$refs.customTableRef.getSaveParams()
      };
      console.log("自动保存");
      const res = await sheetInterface.sheetEdit({ ExcelInfoId: Number(this.sheetId),...params })
      if(res.Ret !==200) return
      this.saveTime = this.$moment().format('YYYY-MM-DD HH:mm:ss')
    },1500),
    /* 保存表格 */
    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()
      };

      let isAdd = this.sheetId?false:true

      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.saveTime =  this.$moment().format('YYYY-MM-DD HH:mm:ss')
      
      isAdd && this.$router.replace({path:'/addCustomSheet',query:{id:this.sheetId}})

      // this.$router.replace({
      //   path: '/sheetList',
      //   query: {
      //     code: UniqueCode,
      //     id: ExcelInfoId
      //   }
      // })
    },300),
    markFinishStatus(){
      if((!this.sheetId) || (!this.isCanEdit)) return
      sheetInterface.markSheetEditStatus({ExcelInfoId: +this.sheetId,Status:2}).then(res=>{
        if(res.Ret != 200) return 
      })
    }
  },
  created() {
    this.getClassify();
    this.getDetail();
  },
  mounted(){
    window.addEventListener('beforeunload',this.markFinishStatus)
  },
  beforeDestroy(){
    window.removeEventListener('beforeunload',this.markFinishStatus)
  }
}
</script>
<style scoped lang="scss">
*{ box-sizing: border-box; }
.customSheet-wrap {
  min-height: calc(100vh - 120px);
  min-width: 1020px;
  .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;
    .database-select{
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      div{
        display: flex;
        align-items: center;
      }
    }
    .wrap-top-bottom{
      display: flex;
      justify-content: space-between;
      align-items: center;
      .form-ul {
        flex: 1;
        display: flex;
        align-items: center;
        li {
          margin: 0 10px;
          // padding-top: 40px;
          &:first-child {
            padding-top: 0;
            margin:0
          }
        }
      }
    }

  }
}
</style>
<style lang="scss">
  .database-select{
    .el-select{
      margin-top: 0!important;
      margin-left: 20px;
      .el-input{
        width: 240px;
      }
    }
    .database-choose{
      display: flex;
      align-items: center;
      label,div{
        white-space: nowrap;
      }
    }
  }
</style>