<template>
  <div class="excel-title-table">
    <el-button size="small" @click="nextStep(-1)">上一步</el-button>
    <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="numFlag" width="70">
        <template #default="{ row }">
          <el-checkbox
            size="small"
            true-label="Y"
            false-label="N"
            v-model="row.numFlag"
            @change="(e) => numFlagChange(e, row)"
          ></el-checkbox>
        </template>
      </vxe-column>
      <vxe-column title="特性" field="numTitle" width="90">
        <template #default="{ row }">
          <el-input :disabled="row.numFlag == 'N'" v-model="row.numTitle" size="small"></el-input>
        </template>
      </vxe-column>
      <vxe-column title="操作" field="action" width="50">
        <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" type="primary" @click="setAreaTitle">标记标题</el-button>
    <el-button size="small" type="primary" @click="setNumFlag">设置拆分</el-button>
    <el-button size="small" type="primary" @click="resetAreaTitle">重置</el-button>
    <el-button size="small" type="success" @click="nextStep()">下一步</el-button>
    <el-button size="small" type="success" @click="save">保存</el-button>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, unref } from 'vue'
import { compareSameCell, 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<Recordable[]>([])
const titleArea = ref<Recordable[]>([])

/**设置拆分 */
const setNumFlag = () => {
  if (!excelAreaTitle.value.length) return
  const rangeData = luckysheet.getRangeValue()
  const titles = handleRangeTitle(rangeData)
  // 匹配到的第一个单元格下标
  const idx = excelAreaTitle.value.findIndex((item) => {
    return compareSameCell(item, titles[0])
  })
  if (idx == -1) return
  for (let i = 0; i <= titles.length - 1; i++) {
    const cell = excelAreaTitle.value[i + idx]

    if (!cell) return
    Reflect.set(cell, 'numFlag', 'Y')
    // !cell.numTitle && Reflect.set(cell, 'numTitle', '尺码')
  }
}

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).map((item) => {
    Reflect.set(item, 'numTitle', '')
    Reflect.set(item, 'numFlag', 'N')
    return item
  })

  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 numFlagChange = ([val], row: any) => {
  // if (val == 'Y') {
  //   !row.numTitle && (row.numTitle = '尺码')
  // } else {
  //   row.numTitle = ''
  // }
}

const validateNumTitle = () => {
  if (
    !unref(excelAreaTitle).every(
      (v) => (!v.numTitle && v.numFlag == 'N') || (v.numTitle && v.numFlag == 'Y')
    )
  ) {
    ElMessage.error('拆分的单元格需要设置特性！')
    return false
  }
  return true
}

const save = () => {
  // 验证是否标记了拆分，拆分的单元格必须设置numTitle字段
  if (!validateNumTitle()) return
  emits('next', -2, {
    excelAreaTitle: unref(excelAreaTitle),
    titleArea: unref(titleArea)
  })
}

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 (index > 0) {
    if (!excelAreaTitle.value.length) {
      return ElMessage.error('请添加标题区！')
    }
    if (!validateNumTitle()) return
  }
  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>
