<template>
  <div class="customSheet-wrap">
    <div class="wrap-top">
      <ul class="form-ul">
        <li>
          <el-input
            v-model="sheetForm.name"
            placeholder="请输入表格名称"
            style="width:220px"
            clearable>
          </el-input>
        </li>
        <li>
          <el-cascader
            v-model="sheetForm.classify"
            :options="classifyArr"
            style="width:220px;"
            :props="{
              label: 'ExcelClassifyName',
              value: 'ExcelClassifyId',
              children: 'Children',
              emitPath: false,
              checkStrictly: true
            }"
            clearable
            placeholder="请选择表格分类"
          />
        </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" style="color:#999999 ;">最近保存时间：{{updateTime}}</span>
        <el-button type="primary" size="medium" @click="()=>{ sheetInit=false;getDetail('refresh')}" style="margin-left:10px" icon="el-icon-refresh-right">更新</el-button>
        <el-button type="primary" size="medium" @click="saveSheetHandle" style="margin-left:10px" v-if="hasPermission">保存</el-button>
        <el-button type="primary" size="medium" plain @click="backHandle">返回</el-button>
      </div>
    </div>
    
    <MixedTable @autoSave="autoSaveFun"
      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 },
  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_mix_save')&&this.sheetButton.OpButton:
              this.permissionBtn.isShowBtn('etaTablePermission','etaTable_customize_mix_save')
    }
  },
  // beforeRouteLeave(to,from,next){
  //   if(to.path!='/addMixedSheet'){
  //     this.markFinishStatus()
  //   }
  //   next()
  // },
  data() {
    return {
      sheetId: this.$route.query.id || '',
      classifyArr: [],
      rules: `表格说明：<br>
        1、手动输入：单击每个单元格可直接输入文本、数字、日期（格式示例：2023-05-23）<br>
        2、根据表格中日期选择指标值：在弹窗中搜索并选择指标，默认选择指标最新日期，可插入指标值，随着指标更新；也支持选择指标后，在表格中选择或输入一个日期，则插入该指标在选定日期的值。<br>
        3、导入日期：导入系统或指标相关的日期，可进一步进行日期变换，跟随系统日期或指标日期更新。<br>
        4、日期计算：对表格中日期进行计算。<br>
        5、指标计算：选择指标进行计算，插入指标计算值。`,
      sheetForm: {
        sheetType: 1
      },
      sheetButton:'',
      sheetInit:false,
      sheetTypeOption: [
        { key: 1,label: '指标列+日期行' },
        { key: 2,label: '指标行+日期列' },
      ],

      updateTime: '',
      isCanEdit:false,
      // 取消自动保存，比如返回的时候
      cancelAutoSave:false
    }
  },
  methods: {

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

    /* 获取表格详情 */
    async getDetail(type='init') {
      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()
        },2000)
        return 
      }

      const { ExcelName,ExcelClassifyId,TableData,ModifyTime,Button } = res.Data;
      this.sheetButton=Button
      this.sheetForm = {
        name: ExcelName,
        classify: ExcelClassifyId
      }
      this.$nextTick(()=>{
        this.sheetInit=true
      })
      this.updateTime =  this.$moment(ModifyTime).format('YYYY-MM-DD HH:mm:ss')

      this.$refs.mixedTableRef.initData(TableData);
      
      type==='refresh' && this.$message.success('表格数据已更新')
    },

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

    autoSaveFun:_.debounce(async function(){
      if(!this.sheetId || this.cancelAutoSave) return 
      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 params = {
        ExcelName: name,
        ExcelType: 1,
        ExcelClassifyId: classify,
        ExcelImage:'',
        Source: 3,
        TableData: this.$refs.mixedTableRef.getSaveParams()
      };
      console.log("自动保存");
      const res = await sheetInterface.sheetEdit({ ExcelInfoId: Number(this.sheetId),...params })
      if(res.Ret !==200) return
      if(res.Data.Status==1){
        this.$message.warning(res.Data.Msg)
        setTimeout(()=>{
          this.backHandle()
        },1000)
        return 
      }
      this.updateTime = 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 ? '请选择表格分类' : '请输入表格名称')

      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: this.$refs.mixedTableRef.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
      if(res.Data.Status==1){
        this.$message.warning(res.Data.Msg)
        setTimeout(()=>{
          this.backHandle()
        },1000)
        return 
      }
      this.updateTime = this.$moment().format('YYYY-MM-DD HH:mm:ss')
      
      this.sheetId = this.sheetId || res.Data.ExcelInfoId;
      this.$message.success('保存成功')
      isAdd && this.$router.replace({path:'/addMixedSheet',query:{id:this.sheetId}})
    },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-width: 1070px;
  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>