<template>
  <div class="addSheet-wrap">
    <div class="wrap-top">
      <ul class="form-ul">
        <li style="margin-right:30px;">
          <el-input
            v-model="sheetForm.name"
            placeholder="请输入表格名称"
            clearable
            style="width:240px">
          </el-input>
        </li>
        <li>
          <el-cascader
            v-model="sheetForm.classify"
            :options="classifyArr"
            style="width:240px;"
            :props="{
              label: 'ExcelClassifyName',
              value: 'ExcelClassifyId',
              children: 'Children',
              emitPath: false,
              checkStrictly: true
            }"
            clearable
            placeholder="请选择表格分类"
          />
        </li>
      </ul>
      <div v-if="updateTime" style="color:#999999;margin-right: 30px;">最近保存时间：{{ updateTime }}</div>
      <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="main">
      <Sheet ref="sheetRef" :limit="{disabled:false}" :option="this.option" v-if="sheetInit" @updated="autoSaveFun"
      :sheetInfo="{
        ExcelInfoId: sheetForm.infoId,
        ExcelName: sheetForm.name,
        ExcelClassifyId: sheetForm.classify,
        Source: sheetForm.source
      }" />
    </div>
  </div>
</template>

<script>
import * as sheetInterface from '@/api/modules/sheetApi.js';
import Sheet from './components/SheetExcel.vue';
import { getSheetImage } from './common/option';
export default {
  components: { Sheet },
  data() {
    return {
      sheetId: this.$route.query.id || '',
      isCanEdit:false,
      sheetForm: {},
      classifyArr: [],
      sheetInit:false,
      option:{},
      updateTime:'',
      sheetButton:'',
      cancelAutoSave:false
    }
  },
  beforeRouteEnter(to, from, next) {
    if(to.query.id){
      to.matched[1].name=`编辑表格`
    }else{
      to.matched[1].name='添加表格'
    }
    next()
  },
  beforeRouteLeave(to,from,next){
    if(to.path!='/addsheet'){
      this.markFinishStatus()
    }
    next()
  },
  watch:{
    sheetForm:{
      handler(newVal){
        console.log(this.sheetInit,this.sheetId);
        if(this.sheetId && this.sheetInit) this.autoSaveFun()
      },
      deep:true
    }
  },
  computed:{
    hasPermission(){
      // console.log(this.sheetButton,'sheetButton');
      return this.sheetButton?
            this.permissionBtn.isShowBtn('etaTablePermission','etaTable_excel_save')&&this.sheetButton.OpButton:
            this.permissionBtn.isShowBtn('etaTablePermission','etaTable_excel_save')
    }
  },
  methods: {

    backHandle() {
      // window.close();
      this.$router.back()
    },

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

    /* 获取表格详情 */
    async getDetail() {
      if(!this.sheetId){
        // 初始化数据
        this.option={data:[{}]}
        this.sheetInit=true
        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 { ExcelInfoId,ExcelName,ExcelClassifyId,ExcelType,ModifyTime,Content,Source,Button} = res.Data;
      this.sheetButton=Button
      this.sheetForm = {
        infoId:ExcelInfoId,
        name: ExcelName,
        classify: ExcelClassifyId,
        sheetType: ExcelType,
        source:Source
      }
      this.updateTime =  this.$moment(ModifyTime).format('YYYY-MM-DD HH:mm:ss')

      this.option={
        data: [{
          ...JSON.parse(Content),
          scrollTop: 0,
          scrollLeft: 0
        }]
      }

      this.$nextTick(()=>{
        this.sheetInit=true
      })

    },
    autoSaveFun:_.debounce(async function(){
      // cancelAutoSave -- 由于是延时自动保存 防止用户在聚焦文本框时点击保存，文本框失焦后又发起自动保存的情况
      if(!this.sheetId && this.sheetInit || this.cancelAutoSave) return
      const { name,classify,infoId } = this.sheetForm;
      luckysheet.exitEditMode()
      let data = luckysheet.getAllSheets()[0];
      if(!name || !classify) return this.$message.warning(name ? '请选择表格分类' : '请输入表格名称')
      if(!data.celldata.length) return this.$message.warning('请输入表格内容');
      let params={
        ExcelInfoId:infoId,
        ExcelName: name,
        ExcelClassifyId: classify,
        ExcelImage: "",
        Content: JSON.stringify(data)
      }
      const res = await sheetInterface.sheetEdit(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')

      // console.log("自动保存");
    },1500),
    /* 保存表格 */
    saveSheetHandle: _.debounce(async function() {
      const { name,classify} = this.sheetForm;
      luckysheet.exitEditMode()
      //结构类型乱飘 强制定义下
      let data = {...luckysheet.getAllSheets()[0],status:Number(luckysheet.getAllSheets()[0].status)}
      if(!name || !classify) return this.$message.warning(name ? '请选择表格分类' : '请输入表格名称')
      if(!data.celldata.length) return this.$message.warning('请输入表格内容');

      this.loading = this.$loading({
				target:'.addSheet-wrap',
				lock: true,
				text: '保存中...',
				spinner: 'el-icon-loading',
				background: 'rgba(255, 255, 255, 0.6)'
			});
      let img = getSheetImage(data);
			const form  = new FormData();
			form.append('Image', img);
			const { Data } = await sheetInterface.uploadImg(form)

      data.luckysheet_select_save = [];
      let params={
        ExcelName: name,
        ExcelClassifyId: classify,
        ExcelImage: Data.ResourceUrl,
        Content: JSON.stringify(data)
      }
      let isAdd = this.sheetId?false:true
      const res = this.sheetId
      ? await sheetInterface.sheetEdit({ ExcelInfoId: Number(this.sheetId),...params })
      : await sheetInterface.sheetAdd(params)

      this.loading.close()
      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(res.Msg);
      if(isAdd){
        this.$router.replace({path:'/addsheet',query:{id:this.sheetId}})
        this.cancelAutoSave=true
      }


      // const { ExcelInfoId, UniqueCode } = res.Data;
      
      // 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 
      })
    }
  },
  mounted() {
    this.getDetail()
    this.getClassify();
    window.addEventListener('beforeunload',this.markFinishStatus)
  },
  beforeDestroy(){
    window.removeEventListener('beforeunload',this.markFinishStatus)
  }
}
</script>
<style scoped lang="scss">
*{ box-sizing: border-box; }
.addSheet-wrap {
  min-height: calc(100vh - 120px);
  min-width: 1000px;
  .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;
    }
  }
  .main {
    position: relative;
    min-height: 700px;
  }
}
</style>