<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="{}" width="150">
        <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="是否填充" width="70">
        <template #default="{ row }">
          <el-checkbox
            size="small"
            true-label="Y"
            false-label="N"
            v-model="row.fillFlag"
          ></el-checkbox>
        </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-group>
      <el-button size="small" type="primary" @click="setAreaTitle">标记标题</el-button>
      <el-button size="small" type="primary" @click="numFlagModalVisible = true"
        >设置拆分</el-button
      >
      <el-button size="small" type="primary" @click="setFill">设置填充</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>
    </el-button-group>

    <vxe-modal title="设置拆分" v-model="numFlagModalVisible" size="small">
      <el-form size="small" :model="numFlagForm" label-width="80px">
        <el-form-item label="特性名称">
          <el-input v-model="numFlagForm.numTitle"></el-input>
        </el-form-item>
        <el-form-item label="是否唯一">
          <el-checkbox false-label="N" true-label="Y" v-model="numFlagForm.isOnly">是</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="setNumFlag">确定</el-button>
          <el-button @click="numFlagModalVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </vxe-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, unref } from 'vue'
import { compareSameCell, getRangetxt, handleRangeCell, 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 numFlagModalVisible = ref(false)
const numFlagForm = reactive({
  numTitle: '尺码',
  isOnly: 'N'
})

/**设置拆分 */
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')
    Reflect.set(cell, 'isOnly', numFlagForm.isOnly)
    !cell.numTitle && Reflect.set(cell, 'numTitle', numFlagForm.numTitle)
  }
  numFlagModalVisible.value = false
}

/**设置填充 */
const setFill = () => {
  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, 'fillFlag', 'Y')
  }
}

const setAreaTitle = () => {
  const sheet = luckysheet.getSheet()
  // 判断是否在同一sheet
  if (sheet.order != props.currentAreaMark.sheetNum) {
    return ElMessage.error('请在同一sheet页中选择数据！')
  }
  const isPublic = props.currentAreaMark.excelAreaType == 'public_area'
  const [sr, er] = sheet.luckysheet_select_save[0].row
  const [sc, ec] = sheet.luckysheet_select_save[0].column
  const rangeData = luckysheet.getRangeValue()
  const titles = isPublic
    ? handleRangeCell(rangeData)
    : handleRangeTitle(rangeData).map((item) => {
        Reflect.set(item, 'numTitle', '')
        Reflect.set(item, 'numFlag', 'N')
        Reflect.set(item, 'fillFlag', 'N')
        Reflect.set(item, 'isOnly', '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).some((v) => v.numFlag == 'Y' && !v.numTitle)) {
    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>
