<template>
  <!--  :style="{ height: tableHeight }" -->
  <div class='flex'>
    <div class="left_menu flex flex-y" v-if="!sheetTotal">
      <el-button type="text" round @click="handelClickBack" icon="el-icon-back">返回</el-button>
     <section >
      <h3>{{menuList[0].taskTitle}}</h3>
      <p>{{menuList[0].agencyName}}</p>
     </section>
      <section>
        <div :class="{ 'menu_item': true, 'active': menuActive === index }" v-for="(item, index) in menuList"
          :key="index" @click="handleClickMenu(index, item)">
          <span>第{{ item.taskNum }}个周期提交</span>
          <i class="el-icon-arrow-right"></i>
        </div>
      </section>
    </div>
    <div :class="['flex', 'flex-y', 'flex1', sheetTotal ? 'luckysheet-wrap' : 'luckysheet-wrap-all']">
      <div class="top_btn flex flex-end">
        <div>
          <el-button type="warning" v-if="pageType === 'add'" @click="handleClickInspect"> 自动检查</el-button>
          <el-button type="text" round @click="handelClickBack" v-if="pageType !== 'add' || sheetTotal"
            icon="el-icon-back">返回</el-button>
          <el-button type="success" @click="onClickUplond()" v-if="pageType !== 'add'"> 智能填表</el-button>
        </div>
        <div>
          <!--  -->
          <el-button type="danger" v-if="pageType === 'add' && !sheetTotal&&mergeObj.taskStateName=='已提交'" @click="handleClickCurrencyEvent('rejected')"> 驳回重提</el-button>
          <el-button type="primary" v-if="pageType === 'add'&& !sheetTotal&&mergeObj.taskStateName=='已提交'" @click="handleClickCurrencyEvent('archived')"> 审核存档</el-button>
          <el-button type="primary" v-if="pageType === 'filling'&& (taskStateName=='处理中'|| taskStateName=='已驳回')" @click="handleClickCurrencyEvent('submit')"> 提交</el-button>
        </div>
      </div>
      <div id="luckysheet"></div>
    </div>
    <el-dialog title="上传共享数据" v-if="showUploadData" :visible.sync="showUploadData" width="60%"
      :close-on-click-modal="false">
      <excelUploadData @handelUploadDataHide="handelUploadDataHide" :currentTable="currentTable" 
        :btnLoading="btnLoading" :sheetRow="sheetR">
      </excelUploadData>
    </el-dialog>
  </div>
</template>

<script>
import excelUploadData from './excel-upload-data.vue';
import LuckyExcel from 'luckyexcel';
import options from "@/utils/luckysheetConfig.js";
import { mapGetters } from 'vuex'
import { requestPost, requestGet } from "@/js/dai/request";

export default {
  data() {
    return {
      showUploadData: false,
      menuList: [],
      menuActive: 0,
      socket: null,
      currentTable: null,
      currentId: '',
      btnLoading:false,
    };
  },
  props: {
    workbookId: {
      type: String,
      default: ''
    },
    pageType: {
      type: String,
      default: ''
    },
    sheetTotal: {
      type: Boolean,
      default: false
    },
    infoObj:{
      type:Object,
      default:()=>{}
    },
    mergeObj:{
      type:Object,
      default:()=>{}
    },
    userId:{
      type:String,
      default:''
    },
    taskStateName: {
      type: String,
      default: ""
    },
  },
  computed: {
    tableHeight() {
      return (this.clientHeight - 140) + 'px'
    },
    ...mapGetters(['clientHeight', 'resolution']),
  },
  async created() {

  },
  watch: {},
  async mounted() {
    console.log(this.mergeObj,"dskjlfsdklf");
    
    if (this.sheetTotal) {
      this.currentId = this.workbookId;
      this.loadWorkBook()
    } else {
       this.getTaskList()
    }
  },
  methods: {
    async getTaskList() {
      let parm = {
        taskId: this.workbookId,//注：此处实际为任务Id只是没必要再声明另外一个参数了
        pageNo: 1,
        pageSize: 1000,
        userId:this.userId
      }
      let { data, code, msg } = await requestGet('/actual/base/communityOneTablePeriodPublish/myPageList', parm)
      if (code === 0) {
        this.menuList = data.list;
        this.currentId = this.menuList[0].subWorkBookId
        this.loadWorkBook()
      }
    },
 
    async handleClickInspect() {
      // 获取celldata并转换为list
      const list = luckysheet.getAllSheets()[0].celldata.map(item => ({
        r: item.r,
        c: item.c,
        v: item.v.v || ''
      }));
      // 发送请求获取异常数据
      let { data, code, msg } = await requestPost('/actual/base/intelligentImportData/checkData', list);
      if (code === 0) {
        if (data && data.length > 0) {
          for (const { r, c } of data) {
            luckysheet.setCellFormat(r, c, 'bg', '#f5504a');
          }
          const findArr = this.findUniqueElements(luckysheet.getAllSheets()[0].celldata, data);
          findArr.forEach(({ r, c, v }) => {
            if (v.bg === "#f5504a") {
              luckysheet.setCellFormat(r, c, 'bg', '#ffffff');
            }
          });
        } else {
          this.$message.success('没有找到异常');
        }
      }
  },

  findUniqueElements(A, B) {
    // 创建B中r和c组合的键集合
    const bCombinations = new Set(B.map(item => `${item.r},${item.c}`));
    // 过滤A中不存在于B的组合
    return A.filter(item => !bCombinations.has(`${item.r},${item.c}`));
  },

    onClickUplond() {
      this.showUploadData = true;
      let list = luckysheet.getAllSheets()
      this.currentTable = list.filter(item => item.status == '1')
      const findLastNonNullIndex = (arr) => {
        for (let i = arr.length - 1; i >= 0; i--) {
          const subArray = arr[i];
          // 判断：是数组，且至少有一个不为 null 的元素
          if (Array.isArray(subArray) && subArray.some(item => item !== null && item.v && item.v !== null && item.v !== '')) {
            return i;  // 返回下标
          }
        }
        return -1;  // 如果没有符合条件的，返回 -1
      };
      this.sheetR = findLastNonNullIndex(this.currentTable[0].data)
      if (this.sheetR != -1) {
        luckysheet.insertRow(this.currentTable[0].data.length, 5)//固定插入5行
      }
    },
    handelUploadDataHide() {
      this.showUploadData = false
    },
    loadWorkBook() {
      window.luckysheet.destroy();
      const { id } = this.$store.state.user;
      options.gridKey = this.currentId;
      options.allowUpdate = true;
      options.container = 'luckysheet'
      options.loadUrl = `${process.env.VUE_APP_API_SERVER}/actual/base/luckySheet/workbook/load?workbookId=${this.currentId}`
      options.updateUrl = `${process.env.VUE_APP_SOCKET_SERVER}/actual/base/ws/luckysheet/${this.currentId}/${id}`
      options.loadSheetUrl = `${process.env.VUE_APP_API_SERVER}/actual/base/luckySheet/workbook/loadSheets`
      window.luckysheet.create({
        ...options,
        hook: {
          cellEditBefore: this.handleCellEditBefore,
          sheetCreateAfter: this.handleSheetCreateAfter,
        },
      });
    },
    handleSheetCreateAfter(e) {
      console.log('setsheet', e);
    },
    handleClickMenu(i, val) {
      this.menuActive = i;
      this.currentId = val.subWorkBookId;
      this.loadWorkBook()
    },

    handelClickBack() {
      this.$emit('close')
    },

    // 驳回重提，审核存档，保存统一用这一个事件来处理
   async handleClickCurrencyEvent(val){
     const url = '/actual/base/communityOneTablePeriodPublish/update'
     let parm = {
      ...this.infoObj
     }
     parm.taskState = val;
     if(val === 'archived'){
      this.workbookMerge()
     }
     const {data,code,msg} = await requestPost(url,parm)
     if(code === 0){
      this.$message.success('操作成功')
     }else{
      console.log(msg);
     }
    },
    async workbookMerge(){
      const url = '/actual/base/luckySheet/workbook/merge'
      let parm = {
        sourceWorkbookId:this.mergeObj.subWorkBookId,
        targetWorkbookId:this.mergeObj.workBookId
      }
      const {data,code,msg} = await requestPost(url,parm)
      if(code === 0){
        console.log('合并成功');
      }
    },
    
  },
  components: {
    excelUploadData
  },
  components: {
    excelUploadData
  },
  beforeDestroy() {
    this.$store.state.sidebarFold = false;
    if (this.socket) {
      this.socket.close();
    }
  },
};
</script>
<style lang="scss" scoped>
.el-card {
  margin: 10px auto;
  padding: 0 16px;
  box-sizing: border-box;
  width: calc(100% - 40px);
  border: none;
}

.luckysheet-wrap {
  margin: 10px;
  padding: 0px;
  z-index: 2;
  width: calc(100vw - 400px);
  height: calc(100vh - 250px);
}

.luckysheet-wrap-all {
  margin: 10px;
  padding: 0px;
  z-index: 2;
  width: calc(100vw - 100px);
  height: calc(100vh - 250px);
}

#luckysheet {
  width: 100%;
  padding: 0px;
  z-index: 2;
  height: calc(100% - 80px);
  margin: 10px;
}

.top_btn {
  height: 60px;
  width: 100%;
}

.upload-demo {
  position: absolute;
  z-index: 999999;
  margin: 20px 0 0 22px;
}

.right-slider {
  position: absolute;
  z-index: 999999;
  border: 1px solid #eeeeee;
  box-shadow: -5px 0px 5px 0px rgba(0, 0, 0, 0.2);
  background: #ffffff;
  margin: 10px 0 0 22px;
  right: 10px;
  width: 36%;
  height: calc(100% - 20px);
}

.el-header,
.el-footer {
  text-align: left;
  line-height: 40px;
  padding-top: 0;
  padding-bottom: 0;
}

.el-main {
  text-align: left;
  line-height: 40px;
  padding-top: 0;
  padding-bottom: 0;
}

.el-container {
  display: flex;
  height: 100%;
  flex-direction: column;
}

.left_menu {
  width: 240px;

  .menu_item {
    cursor: pointer;
    padding: 10px 16px;
    box-sizing: border-box;
    margin-bottom: 5px;
    background-color: #f2f8fd;
    border-radius: 5px;
    font-size: 14px;
  }

  .active {
    color: #3989eb;
  }
}
</style>