<template>
  <div class="excel-title-table">
    <vxe-table
      :row-config="{ isCurrent: true }"
      border
      :data="excelAreaTitle"
      size="mini"
      height="200"
      :edit-config="{ trigger: 'click', mode: 'cell' }"
    >
      <vxe-column title="title" field="title" :edit-render="{}">
        <template #edit="{ row }">
          <el-input v-model="row.title" size="small"></el-input>
        </template>
      </vxe-column>
      <vxe-column title="单元格" field="cell" width="90">
        <template #default="{ row }">
          {{ getRangetxt(row.row, row.row, row.colum, row.colum) }}
        </template>
      </vxe-column>
      <vxe-column title="操作" field="action" width="90">
        <template #default="{ row, $rowIndex }">
          <el-link style="font-size: 12px" type="danger" @click="delAreaTitle($rowIndex, row)"
            >删除</el-link
          >
        </template>
      </vxe-column>
    </vxe-table>
    <el-button size="small" @click="nextStep(-1)">上一步</el-button>
    <el-button size="small" type="primary" @click="setAreaTitle">标记标题</el-button>
    <el-button size="small" type="primary" @click="resetAreaTitle">重置</el-button>
    <el-button size="small" type="success" @click="nextStep()">下一步</el-button>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, unref } from 'vue'
import { getRangetxt, handleRangeTitle } from '@/utils/excel'
import { areaMarksColor } from '@/constants/excelConfig'
import { ElMessage } from 'element-plus'
import type { Recordable } from '@/types/global'

const props = defineProps({
  currentAreaMark: {
    type: Object,
    default: () => ({})
  }
})
const luckysheet = (window as any).luckysheet
const emits = defineEmits(['next'])
const excelAreaTitle = ref([])
const titleArea = ref<Recordable[]>([])

const setAreaTitle = () => {
  const sheet = luckysheet.getSheet()
  // 判断是否在同一sheet
  if (sheet.order != props.currentAreaMark.sheetNum) {
    return ElMessage.error('请在同一sheet页中选择数据！')
  }
  const [sr, er] = sheet.luckysheet_select_save[0].row
  const [sc, ec] = sheet.luckysheet_select_save[0].column
  const rangeData = luckysheet.getRangeValue()
  const titles = handleRangeTitle(rangeData)

  titleArea.value.push({
    excelAreaNicname: props.currentAreaMark.excelAreaNicname,
    sr,
    sc,
    er,
    ec
  })

  if (excelAreaTitle.value.length) {
    const arr = [...titles, ...unref(excelAreaTitle)]
    excelAreaTitle.value = uniqArrayObject(arr)
  } else {
    excelAreaTitle.value = titles
  }

  function uniqArrayObject(arr = []) {
    return arr.reduce((cur, pre, index) => {
      if (index == 0) {
        cur.push(pre)
      } else {
        const isDiff = cur.every((item) => {
          return (
            item.column != pre.column ||
            item.row != pre.row ||
            item.sheet != pre.sheet ||
            item.title != pre.title
          )
        })
        isDiff && cur.push(pre)
      }
      return cur
    }, [])
  }

  setAreaTitleBg('head')
}

const delAreaTitle = (index: number, row: Recordable) => {
  excelAreaTitle.value.splice(index, 1)
}

/**
 * 重置标题区
 * 1.重置表格数据，重置缓存标题区域
 * 2.当前数据区标题区颜色
 */
const resetAreaTitle = () => {
  titleArea.value.forEach((area: any) => {
    luckysheet.menuButton.customUpdateFormat(
      null,
      'bg',
      areaMarksColor['data'],
      area.sr,
      area.er,
      area.sc,
      area.ec,
      false
    )
  })
  resetExcelAreaTitleState()
}
const setAreaTitleBg = (type: 'head') => {
  luckysheet.setRangeFormat('bg', areaMarksColor[type])
}
const resetExcelAreaTitleState = () => {
  excelAreaTitle.value = []
  titleArea.value = []
}
const nextStep = (index: number = 1) => {
  // 验证是否设置标题区域
  if (!excelAreaTitle.value.length && index > 0) {
    return ElMessage.error('请添加标题区！')
  }
  emits(
    'next',
    index,
    index > 0
      ? {
          excelAreaTitle: unref(excelAreaTitle),
          titleArea: unref(titleArea)
        }
      : undefined
  )
  // 返回重置表头标记
  if (index < 0) {
    resetAreaTitle()
  }
}
defineExpose({
  resetExcelAreaTitleState
})
</script>
<style lang="scss" scoped>
.excel-title-table {
  padding: 8px;
}
</style>
