<template>
  <div class="sheet-detail-wrapper" >
    <div class="detail-top">
      <el-input
        ref="sheetEditTitRef"
        style="width: 400px"
        placeholder="请输入表格名称"
        class="label-input"
        v-model="sheet_title"
        v-if="sheetDetailInfo.isEditTit"
        @blur="changeValue(sheetDetailInfo, 'edit-tit')"
      />
      <span
        class="sheet-name"
        @click="editNodeLabel(sheetDetailInfo, 'edit-tit')"
        v-else
      >
        {{ sheetDetailInfo.ExcelName }}
        <i class="el-icon-edit"/>
      </span>
      <div class="sheet-anothor-info">
        <span class="author">作者：{{ sheetDetailInfo.SysUserRealName }}</span>
        <ul class="action-ul" v-if="sheetDetailInfo.Button">
          <div v-if="updateTime" style="color:#999999;">最近保存时间：{{ updateTime }}</div>
          <el-tooltip effect="dark" content="在当前表格选择日期列和数据列生成指标" placement="top-start">
              <li class="editsty" @click="HandleToPath" v-if="isSheetBtnShow('createedb')&&sheetDetailInfo.Button.OpEdbButton">
                <img src="~@/assets/img/icons/choose_bluebg_new.png"/>
                <span>生成指标</span>
              </li>
          </el-tooltip>

          <el-tooltip effect="dark" content="根据表格保存的最新内容，更新当前表格生成的所有指标" placement="top-start">
              <li class="editsty" @click="refreshSheet" v-if="isSheetBtnShow('refresh')&&sheetDetailInfo.Button.RefreshEdbButton">
                <img src="~@/assets/img/icons/refresh_blue_new.png"/>
                <span>刷新指标</span>
              </li>
          </el-tooltip>
          <li class="editsty" @click="saveHandle" v-if="isSheetBtnShow('save')&&sheetDetailInfo.Button.OpButton">
            <img src="~@/assets/img/icons/save_blue_new.png"/>
            <span>保存</span>
          </li>
          <li class="editsty" @click="backHandle">
            <img src="~@/assets/img/icons/back_arrow_blue_new.png"/>
            <span>返回</span>
          </li>
        </ul>
      </div>
    </div>

    <dataLoading :loading="isSheetLoading"/>

    <!-- 表格 -->
    <div class="sheet-wrap">
      <Sheet
        ref="sheetRef"
        v-if="sheetConfigOpt.data"
        :option="sheetConfigOpt"
      />
    </div>
  </div>
</template>

<script>
import * as sheetInterface from "@/api/modules/sheetApi.js";
import Sheet from "../components/SheetExcel.vue";
import leftMixin from "../mixins/classifyMixin";
import { getSheetImage } from "../common/option";

  export default {
    components:{Sheet},
    mixins: [leftMixin],
    data() {
      return {
        sheetDataPage: 2,
        sheetAllcellData:[],//全部单元格数据 分页push
        dataToalPage: 0,
        isSheetLoading: false,
        code:'',
        sheetConfigOpt: {
          showsheetbar: true,
          data: null
        },
        sheet_title: "", //表格标题 双击标题修改时来存储最新值
        sheetDetailInfo:{},
        isCanEdit:false,
        sheetId:'',
        loading:null,
        updateTime:''
      }
    },
    beforeRouteLeave(to,from,next){
      if(to.path!='/editSheetAnalysis'){
        this.markFinishStatus()
      }
      next()
    },
    created(){
      // console.log(this.$route.query.code);
      if(!this.$route.query.code){
        this.$message.warning("参数丢失")
        this.backHandle()
      }else{
        this.code = this.$route.query.code
        this.getDetailHandle()
      }
    },
    mounted() {
      window.addEventListener('beforeunload',this.markFinishStatus)
    },
    beforeDestroy(){
      window.removeEventListener('beforeunload',this.markFinishStatus)
    },
    methods:{
      /* 获取表格详情 */
      getDetailHandle() {

        this.isSheetLoading = true;
        sheetInterface.sheetAnalysisInterface.getExcelDetail({
          UniqueCode:this.code,
        }).then((res) => {
          if (res.Ret !== 200) return;
          this.isCanEdit = res.Data.ExcelInfo.CanEdit
          if(!this.isCanEdit){
            this.$message.warning(`${res.Data.ExcelInfo.Editor}正在编辑中`)
            setTimeout(()=>{
              this.backHandle()
            },1000)
            return 
          }
          this.sheetDetailInfo = res.Data.ExcelInfo;
          this.updateTime = this.$moment(this.sheetDetailInfo.ModifyTime).format('YYYY-MM-DD HH:mm:ss')||''
          this.sheetId = this.sheetId || res.Data.ExcelInfo.ExcelInfoId;
          this.dataToalPage =  Math.max(...res.Data.SheetList.map(_ => _.PageNum));
          this.sheetAllcellData = res.Data.SheetList.map(_ => _.Data ? JSON.parse(_.Data.Data) : []);

          this.getCellData(res.Data.SheetList)
        });
      },
      //分页获取表格数据
      async getCellData(sheets) {

        let res = await sheetInterface.sheetAnalysisInterface.getExcelDataByPage({
          UniqueCode: this.code,
          Page: this.sheetDataPage
        })

        if(res.Ret !== 200) return
        console.log(this.sheetAllcellData)

        for(let i = 0;i<this.sheetAllcellData.length;i++) {
          if(res.Data[i].Data) {
            this.sheetAllcellData[i] = [...this.sheetAllcellData[i],...JSON.parse(res.Data[i].Data.Data)]
          }

          continue
        }
        
        //数据继续加载或渲染表格.
        if(this.sheetDataPage < this.dataToalPage) {
          this.sheetDataPage++;
          this.getCellData(sheets)
        }else {
          this.sheetConfigOpt.data = sheets.map((_,index) => ({
            index: _.Index, //工作表id
            order: _.Sort, //工作表的下标
            name: _.SheetName,
            calcChain: _.CalcChain?JSON.parse(_.CalcChain):[],
            config: JSON.parse(_.Config),
            celldata: this.sheetAllcellData[index],
          }))

          console.log(this.sheetConfigOpt)

          this.isSheetLoading = false;
        }
      },
      backHandle(){
        let params={
          code:this.sheetDetailInfo.UniqueCode,
          id:this.sheetDetailInfo.ExcelInfoId
        }
        sessionStorage.setItem('editSheetAnalysisBack',JSON.stringify(params))
        this.$router.back()
      },
      //跳转生成指标
      HandleToPath() {
        this.$router.push({ path: '/createTaregtBySheet',query: {
          code: this.sheetDetailInfo.UniqueCode 
        }});
      },
      /* 刷新表格 */
      refreshSheet: _.debounce(async function() {
        let res = await sheetInterface.sheetAnalysisInterface.sheetRefresh({ExcelInfoId: this.sheetDetailInfo.ExcelInfoId})

        if(res.Ret !== 200) return 
        this.$message.success(res.Msg)
      },300),
      /* 保存表格 */
      saveHandle: _.debounce(async function () {
        luckysheet.exitEditMode();
        let data = luckysheet.getAllSheets();

        this.loading = this.$loading({
          target: ".sheet-detail-wrapper",
          lock: true,
          text: "保存中...",
          spinner: "el-icon-loading",
          background: "rgba(255, 255, 255, 0.6)",
        });

        let img = getSheetImage(data[0]);
        const form = new FormData();
        form.append("Image", img);
        const { Data } = await sheetInterface.uploadImg(form);

        data.luckysheet_select_save = [];
        const { ExcelInfoId, ExcelName, ExcelClassifyId } = this.sheetDetailInfo;
        const res = await sheetInterface.sheetAnalysisInterface.sheetEdit({
          ExcelInfoId,
          ExcelName,
          ExcelClassifyId,
          ExcelImage: Data.ResourceUrl,
          Content: JSON.stringify(data),
        });
        this.loading.close();
        if (res.Ret !== 200) return;
        this.$message.success("保存成功");
        this.$router.back()
      }, 300),
      markFinishStatus(){
        if((!this.sheetId) || (!this.isCanEdit)) return
        sheetInterface.markSheetEditStatus({ExcelInfoId: +this.sheetId,Status:2}).then(res=>{
          if(res.Ret != 200) return 
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .sheet-detail-wrapper {
    height: 100%;
    border: 1px solid #ececec;
    border-radius: 4px;
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
    overflow: auto;
    background: #fff;
    .detail-top {
      padding: 20px;
      // display: flex;
      // justify-content: space-between;
      // align-items: center;
      border-bottom: 1px solid #ececec;
      .sheet-name {
        font-size: 18px;
        color: #333333;
        margin-bottom: 6px;
        cursor: pointer;
        max-width: 450px;
        &:hover {
          text-decoration: underline;
        }
      }
      .sheet-anothor-info{
        display: flex;
        justify-content: space-between;
        align-items: center;
        .author{
          color: #666666;
          font-size: 16px;
        }
        .action-ul {
          display: flex;
          li {
            margin: 0 10px;
            display: flex;
            align-items: center;
            img{
              height: 16px;
              width: 16px;
              margin-right: 4px;
            }
          }
        }
      }
    }
    .sheet-wrap {
      position: relative;
      height: calc(100vh - 210px);
    }
  }
</style>