<template>
  <div class="flex h-full">
    <div id="luckysheet" class="flex-1"></div>
    <div class="w-[360px] bg-white">
      <p class="pl-2 text-xl font-bold leading-[50px] bg-slate-200">标注配置</p>
      <CommentForm :selected-row="selectedRow" :selected-cell="selectedCell" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import LuckyExcel from 'luckyexcel'
import { nextTick, onMounted, reactive, watch, ref, unref, onUnmounted } from 'vue'
import { isFunction } from '@/utils/is'
import {
  cellRightClickConfig,
  sheetRightClickConfig,
  showsheetbarConfig,
  authorityConfig
} from '../../constant'
import { useLuckysheetMark } from '../useLuckysheet'
import { useExcelStore } from '@/stores/excel'

import CommentForm from '../CommentForm/CommentForm.vue'
import { apiGetMark, getExcelOrderIndex } from '@/api/excel'
import { storeToRefs } from 'pinia'

const jsonData = ref({})
const selectedCell = reactive({})
const selectedRow = reactive({
  sheetNum: '',
  rowNum: []
})

const { setSheetMarks } = useLuckysheetMark()
const excelStore = useExcelStore()
const {
  setIsSelectedRow,
  setMark,
  getMark,
  setSheetBegin,
  setIsSetSheetMark,
  initSheetBegin,
  initIsSetSheetMarks
} = excelStore
const { getFileInfo, getIsSetSheetMarks, getMarks, getSheetBegin } = storeToRefs(excelStore)

/**
 * - 设置工作表权限
 * - 解决有格式的单元格，无法锁定单元格问题
 */
const setSheetAuthority = (exportJson: any) => {
  exportJson.sheets.forEach((sheet: any) => {
    // 工作表格权限
    sheet.config.authority = authorityConfig
    // 单元格锁定
    sheet.celldata.forEach((item: any) => {
      item.v.lo = 1
    })
  })

  jsonData.value = exportJson
}

const sheetMouseup = (c: any, p: any, sheet: any, status: any) => {
  const { rowsSelectedStatus, selectStatus } = status
  // 选中一整行 status
  if (rowsSelectedStatus) {
    setIsSelectedRow(true)

    const sRow = sheet.luckysheet_select_save.filter((v) => v?.row_select)
    const rowNums: any = []

    sRow.forEach((v: any) => {
      if (v.row[0] === v.row[1]) {
        rowNums.push(v.row[0])
      } else {
        for (let i = v.row[0]; i <= v.row[1]; i++) {
          rowNums.push(i)
        }
      }
    })
    rowNums.sort((a: any, b: any) => a - b)

    // 查询 选中行是否有循环体开始标记
    // ...

    const o = {
      sheetNum: sheet.order,
      rowNum: rowNums
    }

    Object.assign(unref(selectedRow), o)
  } else if (selectStatus) {
    if (c !== null) {
      setIsSelectedRow(false)
      cellMousedownHook(c, p, sheet)
    }
  }
}

const cellMousedownHook = (c, p, sheet) => {
  // 判断本地是否保存过该标记
  const mark = getMark(sheet.order, p.r, p.c)
  if (mark) {
    const cell = {
      ...mark
    }
    cell.mp = mark.filed.filedName
    cell.v = window.luckysheet.getCellValue(mark.rowNum, mark.columNum)
    Object.assign(unref(selectedCell), cell)
    return
  }

  let v = ''
  if (c.v) {
    v = c.v
  } else if (c.ct?.s?.length) {
    v = c.ct?.s[0]?.v || ''
  }
  const cell = {
    filedConfId: '',
    rowNum: p.r,
    columNum: p.c,
    v: v,
    sheetNum: sheet.order,
    mp: '',
    params: {},
    formart: '',
    scriptName: ''
  }

  Object.assign(unref(selectedCell), cell)
}

const getFileMarks = async () => {
  // 获取标记
  const { data } = await apiGetMark(getFileInfo.value.orderFileId)
  const { result } = data
  if (!result.length) return
  // 保存本地标记
  result.forEach((item: any) => {
    setMark(item.sheetNum, item.rowNum, item.columNum, item)
  })
}

const querySheetBegin = async () => {
  const { data } = await getExcelOrderIndex(getFileInfo.value.orderFileId)
  data.result.forEach((item: any) => {
    setSheetBegin(item.sheetNum, item)
  })
}
const loadExcel = () => {
  LuckyExcel.transformExcelToLuckyByUrl(
    '/api/sys/static/' + getFileInfo.value.mergeFilePath,
    new Date().getTime() + '.xlsx',
    async (exportJson: any, luckysheetfile: any) => {
      initIsSetSheetMarks(exportJson.sheets.length)
      initSheetBegin(exportJson.sheets.length)

      await getFileMarks()
      await querySheetBegin()

      setSheetAuthority(exportJson)
      isFunction(window?.luckysheet?.destroy) && window.luckysheet.destroy()

      // 创建并添加hook，单元格点击事件
      window.luckysheet.create({
        container: 'luckysheet', //luckysheet is the container id
        showinfobar: false,
        showtoolbar: false,
        showsheetbar: false,
        showsheetbarConfig,
        cellRightClickConfig,
        sheetRightClickConfig,
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator,
        hook: {
          sheetMouseup: sheetMouseup,
          sheetActivate: (index: any) => {
            const sheet = window.luckysheet.getSheet({ index: index })
            const { order } = sheet

            if (getIsSetSheetMarks.value[order]) {
              return
            }
            setIsSetSheetMark(order)

            if (Reflect.has(getMarks.value, order)) {
              setSheetMarks(getMarks.value[order])
            }

            // 设置begin开始行颜色
            if (getSheetBegin.value[order]) {
              const po = [
                getSheetBegin.value[order].rowNum,
                getSheetBegin.value[order].rowNum,
                0,
                1
              ]
              setTimeout(() => {
                window.luckysheet.menuButton.customUpdateFormat(null, 'bg', '#c7f5d3', ...po)
              }, 100)
            }
          },
          workbookCreateAfter: () => {
            // 设置标记 默认显示第一个sheet order 为 0
            setIsSetSheetMark(0)
            if (Reflect.has(getMarks.value, 0)) {
              setSheetMarks(getMarks.value[0])
            }
            // 设置显示begin开始行颜色
            const beginOrderIndex = getSheetBegin.value[0]
            console.log(beginOrderIndex, '----')
            if (beginOrderIndex.forIndexId) {
              const po = [beginOrderIndex.rowNum, beginOrderIndex.rowNum, 0, 10]
              window.luckysheet.menuButton.customUpdateFormat(null, 'bg', '#c7f5d3', ...po)
            }
          }
        }
      })
    }
  )
}

// !!! create luckysheet after mounted
onMounted(() => {
  loadExcel()
  // nextTick(() => {
  //   window.luckysheet.luckysheetsizeauto()
  // })
})
onUnmounted(() => {
  isFunction(window?.luckysheet?.destroy) && window.luckysheet.destroy()
})
</script>
<style lang="scss" scoped>
#luckysheet {
  height: 100%;
}
</style>
