<template>
  <div class="customSheet-wrap">
    <div class="wrap-top">
      <ul class="form-ul">
        <li>
          <el-input
            v-model="sheetForm.name"
            :placeholder="$t('OnlineExcelPage.please_table_name_ipt')"
            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="$t('OnlineExcelPage.select_table_category')"
          />
        </li>
        <li>
          {{$t('OnlineExcelPage.table_explaination_text')}}
          <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 ;">{{$t('OnlineExcelPage.recent_save_time_info')}}{{updateTime}}</span>
        <el-button type="primary" size="medium" :loading="updating" @click="updateHandle" style="margin-left:10px" icon="el-icon-refresh-right">{{updating?$t('ETable.Btn.renewing_btn'):$t('ETable.Btn.renew_btn')}}</el-button>
        <el-button type="primary" size="medium" @click="saveSheetHandle" style="margin-left:10px" v-if="hasPermission">{{$t('ETable.Btn.save_btn')}}</el-button>
        <el-button type="primary" size="medium" plain @click="backHandle">{{$t('ETable.Btn.back_btn')}}</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')
    },
    rules(){
      return this.$t('OnlineExcelPage.TableInstructionsText') ||''
    },
    sheetTypeOption(){
      return [
        { key: 1,label: this.$t('OnlineExcelPage.data_row_label')},
        { key: 2,label: this.$t('OnlineExcelPage.data_column_label')},
      ]
    }
  },
  // beforeRouteLeave(to,from,next){
  //   if(to.path!='/addMixedSheet'){
  //     this.markFinishStatus()
  //   }
  //   next()
  // },
  data() {
    return {
      sheetId: this.$route.query.id || '',
      classifyArr: [],
      sheetForm: {
        sheetType: 1
      },
      sheetButton:'',
      sheetInit:false,
     

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

      updating: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(type==='refresh'){
        this.updating=false
      }

      if(res.Ret !== 200)  return
      this.isCanEdit = res.Data.CanEdit
      if(!res.Data.CanEdit){
        this.$message.warning(`${res.Data.Editor}${this.$t('OnlineExcelPage.currently_editing_msg') }`)
        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(this.$t('OnlineExcelPage.table_data_update_msg') )
    },

    /* 获取分类 */
    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 ? this.$t('OnlineExcelPage.select_table_category')  : this.$t('OnlineExcelPage.please_table_name_ipt') )
      let checkAllEmpty = this.$refs.mixedTableRef.config.data.flat(1).some(_ => _.ShowValue);
      if(!checkAllEmpty) return this.$message.warning(this.$t('OnlineExcelPage.input_content_msg') )
      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 ? this.$t('OnlineExcelPage.select_table_category')  : this.$t('OnlineExcelPage.please_table_name_ipt') )

      let checkAllEmpty = this.$refs.mixedTableRef.config.data.flat(1).some(_ => _.ShowValue);
      if(!checkAllEmpty) return this.$message.warning(this.$t('OnlineExcelPage.input_content_msg') )

      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(this.$t('MsgPrompt.saved_msg') )
      isAdd && this.$router.replace({path:'/addMixedSheet',query:{id:this.sheetId}})
    },300),

    //更新
    updateHandle(){
      if(this.updating) return
      this.updating=true
      this.sheetInit=false
      this.getDetail('refresh')
    },
    

    // 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>