<template>
  <div class="addSheet-wrap">
    
    <createTargetForm 
      v-if="$route.path==='/createTaregtBySheet'"
      ref="createTargetRef" 
      @save="handleCreateTarget" 
    />


    <div class="main">
      <div class="left-section">
        <el-tabs 
          v-model="selectIndex" 
          type="card"
        >
          <el-tab-pane
            :key="item.name"
            v-for="(item,index) in uploadSheetsList"
            :label="item.name"
            :name="String(index)"
          />
        </el-tabs>
        <div class="sheet-wrapper">
          <Sheet ref="sheetRef" :option="sheetConfig" v-if="sheetConfig.data" :limit="{disabled:false}"/>

          <dataLoading :loading="isLoading"/>
        </div>

      </div>

      <!-- 指标列表 -->
      <rightSection 
        ref="edbWrapRef"
        v-if="$route.path==='/createTaregtBySheet'"
        :list="edbList"
        @choose="chooseEdbHandle"
      />
    </div>


    <!-- 上传文件 -->
    <bottomSection
      ref="bottomSecRef"
      v-if="$route.path==='/addAnalysisSheet'" 
      :sheetList="sheetConfig.data||[]"
      :classifyArr="classifyArr"
      @save="handleAddSheet"
    />

  </div>
</template>

<script>
import * as sheetInterface from '@/api/modules/sheetApi.js';
import Sheet from '../components/SheetExcel.vue';
import { getSheetImage } from '../common/option';
import bottomSection from './components/bottomSection.vue'
import rightSection from './components/rightSection.vue';
import createTargetForm from './components/createTargetForm.vue';
export default {
  components: { Sheet,bottomSection,rightSection,createTargetForm },
  computed: {
    files() {
      return this.$store.state.sheet.files;
    },
    sheetConfig() {
      return this.$route.path==='/createTaregtBySheet' 
        ? {
            showsheetbar: true,
            // allowCopy:false,
            // allowEdit:false,
            // allowUpdate:false,
            // enableAddRow:false,
            data: null,
            hook: {
              //选区时
              rangeSelect: (sheet,range) => {
                if(this.$refs.createTargetRef && this.$refs.createTargetRef.selectArea && !this.$refs.createTargetRef.isLockUpdate) this.getRangeCell()
              },
            }
          } 
        : {
            showsheetbar: true,
            data: null
          }
    },
  },
  data() {
    return {
      isLoading: false,
      uploadSheetsList: [],
      pageSize: 2000,
      currentPage: 0,
      maxPage:0,

      selectIndex: '0',
      classifyArr: [],

      sheetDetailInfo: {},
      sheetDataPage: 2,
      sheetAllcellData:[],//全部单元格数据 分页push
      dataToalPage: 0,

      edbList: [],//生成的指标列表
    }
  },
  methods: {

    backHandle(scence=null) {
      if(scence === 'into-detail') {
        const { ExcelInfoId, UniqueCode } = this.sheetDetailInfo;
        
        this.$router.replace({
          path: '/sheetAnalysisList',
          query: {
            code: UniqueCode,
            id: ExcelInfoId
          }
        })
      }else {
        this.$router.go(-1);
      }

    },

    /* 切换表格 */
    handleSwitchSheet() {
      this.sheetConfig.data = null;
      this.handelTranslateData(); 
    },

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

    loadDataSync() {
      let len = this.sheetConfig.data.length;
      for(let i =0;i<len;i++) {
        if(this.allSheetData[i].celldata[this.currentPage*this.pageSize]) {
          let concatData = this.allSheetData[i].celldata.slice(this.currentPage*this.pageSize, (this.currentPage+1)*this.pageSize);

          // this.sheetConfig.data[i].celldata = this.sheetConfig.data[i].celldata.concat(concatData) 
          // this.$refs.sheetRef.init()
        }
        continue

      }

      if (this.currentPage<this.maxPage) {
        this.currentPage++
        requestAnimationFrame(this.loadDataSync());
      }
    },

    /* 分割数据 */
    splitSheetData(sheets) {
      // this.allSheetData = sheets.map(_ => ({
      //   index: _.index, //工作表索引
      //   order: _.order, //工作表的下标
      //   name: _.name,
      //   calcChain: _.calcChain,
      //   celldata: _.celldata,
      //   config: _.config
      // }));
      // this.maxPage = Math.max(...sheets.map(_ =>  Math.ceil(_.celldata.length / this.pageSize)))
      console.log(sheets)

      this.sheetConfig.data = sheets.map(_ => ({
        index: _.index, //工作表索引
        order: Number(_.order), //工作表的下标
        name: _.name,
        calcChain: _.calcChain,
        config: _.config,
        celldata: _.celldata,
      }));
      
      //辣鸡插件连更新数据的api都没有
       //  this.loadDataSync();
      
      this.isLoading = false;
    },

    handelTranslateData() {
        this.isLoading = true;
        LuckyExcel.transformExcelToLucky(this.uploadSheetsList[Number(this.selectIndex)], (exportJson, luckysheetfile) =>{
                                  
          if(exportJson.sheets==null || exportJson.sheets.length==0){
              this.$message.warning('解析文件失败')
              return;
          }

            this.splitSheetData(exportJson.sheets);

        });

    },

    /* 移除表格 */
    handleRemoveSheet(index) {
      if(this.uploadSheetsList.length === 1) {
        this.backHandle()
        return
      }

      this.uploadSheetsList.splice(Number(index),1)
      if(this.selectIndex === index) {
        this.selectIndex = '0';
        this.handleSwitchSheet()
      }

    },


    /* 保存表格 */
    handleAddSheet: _.debounce(async function() {
      luckysheet.exitEditMode()
      let data = luckysheet.getAllSheets().filter(_ => this.$refs.bottomSecRef.sheetChecked.includes(_.name));
      console.log(data)

      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[0]);
			const form  = new FormData();
			form.append('Image', img);
			const { Data } = await sheetInterface.uploadImg(form)

      data.luckysheet_select_save = [];
      const res = await sheetInterface.sheetAnalysisInterface.excelSheetAdd({
        ExcelName: this.uploadSheetsList[0].name,
        ExcelClassifyId: this.$refs.bottomSecRef.select_classify,
        ExcelImage: Data.ResourceUrl,
        Content: JSON.stringify(data)
      })
      this.loading.close()
      if(res.Ret !== 200) return

      this.$message.success(res.Msg);

      // const { ExcelInfoId, UniqueCode } = res.Data;
      
      this.$router.replace({
        path: '/sheetAnalysisList',
        // query: {
        //   code: UniqueCode,
        //   id: ExcelInfoId
        // }
      })
    },300),

     /* 获取表格详情 */
    getDetailHandle() {
      this.isLoading = true;
      sheetInterface.sheetAnalysisInterface.getExcelDetail({
        UniqueCode: this.$route.query.code,
      }).then((res) => {
        if (res.Ret !== 200) return;

        this.sheetDetailInfo = res.Data.ExcelInfo;
        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.$route.query.code,
        Page: this.sheetDataPage
      })

      if(res.Ret !== 200) return

      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.sheetConfig.data = sheets.map((_,index) => ({
          index: _.Index, //工作表id
          order: _.Sort, //工作表的下标
          name: _.SheetName,
          calcChain: JSON.parse(_.CalcChain),
          config: JSON.parse(_.Config),
          celldata: this.sheetAllcellData[index],
        }))

        this.isLoading = false;
        this.getTargetList()
      }
    },


    /* 获取选取对应单元格数组和拼接选取的公式 
      Sheet1!$A$1:$A$25
      Sheet1!$E:$E
    */
    getRangeCell: _.debounce(function() {
      let sheet = luckysheet.getSheet();
      let rangeArr = luckysheet.getRangeAxis();

      if(rangeArr.length > 1) return this.$message.warning('同时只允许选择一块区域');
      //检查选取是否满足同行/同列
      if(!this.checkRangeVaild(rangeArr[0])) return this.$message.warning('序列只允许选择同行或同列');

      let rangeCells = luckysheet.getRangeValue().flat().map(_=>_?_.m:'');

      let format = `${sheet.name}!${this.formatStr(rangeArr[0])}`;

      console.log(format)
      this.$refs.createTargetRef.setFormula(format,rangeCells)
    },300),

    //检验同行同列
    checkRangeVaild(range) {
      let reg = /^([A-Z]+)(\d+)$/;
      let arr = range.split(':').map(_ => [_.match(reg)[1],_.match(reg)[2]]);
      
      if(arr.length ===1) return true;

      if(arr[0][0] === arr[1][0] || arr[0][1] === arr[1][1]) {
        return true
      }else {
        return false
      }
    },

    formatStr(inputRange) {
      // 将字母和数字前面都拼接"$"
      const parts = inputRange.split(':');
      if (parts.length === 2) {
          const start = parts[0].replace(/(^[A-Z]+)(\d+)$/, '$$$1$$$2');
          const end = parts[1].replace(/(^[A-Z]+)(\d+)$/, '$$$1$$$2');
          return start + ':' + end;
      }
      return inputRange;
      
    },
    
    /* 生成指标 */
    async handleCreateTarget() {
      console.log(this.$refs.createTargetRef.formData)
      this.loading = this.$loading({
				target:'.addSheet-wrap',
				lock: true,
				text: '保存中...',
				spinner: 'el-icon-loading',
				background: 'rgba(255, 255, 255, 0.6)'
			});

      let data = luckysheet.getAllSheets();
      data.luckysheet_select_save = [];
      const { ExcelInfoId, ExcelName, ExcelClassifyId } = this.sheetDetailInfo;
      await sheetInterface.sheetAnalysisInterface.sheetEdit({
        ExcelInfoId,
        ExcelName,
        ExcelClassifyId,
        // ExcelImage: Data.ResourceUrl,
        Content: JSON.stringify(data)
      });
      
      const { edbInfoId,
        dateSeries,
        valueSeries,
        dateArr,
        valueArr,
				edbName,
				classify,
				frequency,
				unit } = this.$refs.createTargetRef.formData;
      let params = {
        EdbName: edbName,
        ExcelInfoId: ExcelInfoId,
        ClassifyId: classify,
        Frequency: frequency,
        Unit: unit,
        DateSequenceVal: dateArr,
        DataSequenceVal: valueArr,
        DateSequenceStr: dateSeries,
        DataSequenceStr: valueSeries
      }
      const res = edbInfoId 
        ? await sheetInterface.sheetAnalysisInterface.edbEditBysheet({...params,EdbInfoId: edbInfoId})
        : await sheetInterface.sheetAnalysisInterface.edbAddBysheet(params)

      this.loading.close();
      if(res.Ret !== 200) return

      this.$message.success(res.Msg)

      if(!edbInfoId) this.$refs.createTargetRef.initData();

      this.getTargetList()
    },

    /* 获取生成指标列表 */
    async getTargetList() {
      const res = await sheetInterface.sheetAnalysisInterface.edbListBySheet({
        ExcelInfoId: this.sheetDetailInfo.ExcelInfoId
      })

      if(res.Ret !== 200) return
      
      this.edbList = res.Data || [];
    },

    /* 选择指标列表更新表单信息和区域选中 */
    chooseEdbHandle() {

      if(this.$refs.edbWrapRef.selectEdb.EdbInfoId) {
        this.$refs.createTargetRef.initData(this.$refs.edbWrapRef.selectEdb)
      } else {
        this.$refs.createTargetRef.initData()
      }
    }
    
  },
  mounted() {
    this.getClassify();
    //上传文件的解析渲染
    if(this.files) {
      this.uploadSheetsList =  Object.values(this.files);
      this.handelTranslateData()
      this.$store.commit('sheet/SET_UPLOADFIlES',null)
    }

    //详情的渲染
    if(this.$route.query.code) this.getDetailHandle();
  }
}
</script>
<style scoped lang="scss">
*{ box-sizing: border-box; }
.addSheet-wrap {
  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;
      li {
        margin-right: 30px;
      }
    }
  }
  .main {
    display: flex;
    position: relative;
    min-height: 700px;
    .left-section {
      flex:1;
      .sheet-wrapper {
        position: relative;
        background: #fff;
        min-height: 700px;
      }
    
    }
    &.full-height {
      min-height: calc(100vh - 120px);
    }
  }
}
</style>
<style lang="scss">
.addSheet-wrap {
  .el-tabs__nav {
    background: #fff;
  }
  .el-tabs__header {
    margin-bottom: 0;
    // border-bottom: none;
  }
}
</style>