<template>
  <div class="set-attch-table">
    <el-button size="small" @click="back">上一步</el-button>

    <p style="font-size: 12px">
      附加区域：<el-tag>{{
        getRangetxt(formState.beginRow, formState.endRow, formState.beginColum, formState.endColum)
      }}</el-tag>
    </p>

    <vxe-table
      style="margin-top: 8px"
      :row-config="{ isCurrent: true }"
      border
      :data="groupTitles"
      size="mini"
      max-height="200"
      :edit-config="{ trigger: 'click', mode: 'cell' }"
    >
      <vxe-column title="别称" field="title" :edit-render="{}">
        <template #edit="{ row }">
          <el-input size="small" v-model="row.title"></el-input>
        </template>
      </vxe-column>
      <vxe-column title="单元格" field="area" width="100">
        <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="delGroupTitle($rowIndex)"
            >删除</el-link
          >
        </template>
      </vxe-column>
    </vxe-table>

    <vxe-table
      style="margin-top: 8px"
      :row-config="{ isCurrent: true }"
      border
      :data="areaTitles"
      size="mini"
      max-height="200"
      :edit-config="{ trigger: 'click', mode: 'cell' }"
    >
      <vxe-column 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="100">
        <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-group class="mt-2">
      <el-button type="primary" size="small" @click="setAttch">设置附加信息</el-button>
      <el-button type="primary" size="small" @click="setNickName">设置别称</el-button>
      <el-button type="primary" size="small" @click="setAttchTitle">设置标题</el-button>
      <el-button type="primary" size="small" @click="setNumFlag">设置拆分</el-button>
      <el-button type="success" size="small" @click="save">保存</el-button>
    </el-button-group>
  </div>
</template>

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

const luckysheet = (window as any).luckysheet
const emits = defineEmits(['next'])
const formState = reactive<Recordable>({
  beginRow: '',
  beginColum: '',
  endRow: '',
  endColum: '',
  sheetNum: ''
})
const areaTitles = ref<Recordable[]>([])
const groupTitles = ref<Recordable[]>([])

/**
 * 设置附加信息
 */
const setAttch = () => {
  const position = getRangePosition()
  if (!position) return
  if (formState.beginRow != '') {
    luckysheet.menuButton.customUpdateFormat(
      null,
      'bg',
      areaMarksColor['data'],
      formState.beginRow,
      formState.endRow,
      formState.beginColum,
      formState.endColum,
      false
    )
  }

  luckysheet.setRangeFormat('bg', areaMarksColor['attch'])
  Object.assign(formState, position)
}

const numFlagChange = ([val], row: any) => {
  if (val == 'Y') {
    !row.numTitle && (row.numTitle = '尺码')
  } else {
    row.numTitle = ''
  }
}

/**
 * 设置附加信息标题
 */
const setAttchTitle = () => {
  if (formState.beginRow == '') {
    return ElMessage.error('请先设置附加信息区域！')
  }
  const position = getRangePosition()
  if (!position) return
  // 清除颜色
  if (areaTitles.value.length) {
    areaTitles.value.forEach((item) => {
      luckysheet.menuButton.customUpdateFormat(
        null,
        'bg',
        areaMarksColor['attch'],
        item.row,
        item.row,
        item.colum,
        item.colum,
        false
      )
    })
  }

  const rangeData = luckysheet.getRangeValue()
  const aTitles = handleRangeTitle(rangeData).map((item) => {
    Reflect.set(item, 'numTitle', '')
    Reflect.set(item, 'numFlag', 'N')
    return item
  })
  areaTitles.value = aTitles

  luckysheet.setRangeFormat('bg', areaMarksColor['attch_title'])
}

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

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

/**
 * 设置附加信息别称
 * @param row
 */
const setNickName = () => {
  if (formState.beginRow == '') {
    return ElMessage.error('请先设置附加信息区域！')
  }
  const position = getRangePosition()
  if (!position) return
  console.log(groupTitles)
  // 清除颜色
  if (groupTitles.value.length) {
    groupTitles.value.forEach((item) => {
      luckysheet.menuButton.customUpdateFormat(
        null,
        'bg',
        areaMarksColor['attch'],
        item.row,
        item.row,
        item.colum,
        item.colum,
        false
      )
    })
  }

  const rangeData = luckysheet.getRangeValue()
  const gTitles = handleRangeTitle(rangeData, unref(formState))
  groupTitles.value = gTitles

  luckysheet.setRangeFormat('bg', areaMarksColor['attch_head'])
}

// 删除附加信息别称
const delGroupTitle = (index: number) => {
  groupTitles.value.splice(index, 1)
}
// 删除区域标题
const delAreaTitle = (index: number) => {
  areaTitles.value.splice(index, 1)
}
const save = () => {
  // 如果设置了附加信息，必须要设置别称
  if (formState.beginRow != '') {
    if (!groupTitles.value.length) {
      return ElMessage.error('请设置附加信息区域的别称！')
    }
  }
  emits('next', -2, {
    desGroups: {
      ...formState,
      areaTitles: unref(areaTitles),
      groupTitles: unref(groupTitles)
    }
  })
}

// 重置附加信息颜色
const resetAttchBg = () => {
  if (formState.beginRow != '') {
    luckysheet.menuButton.customUpdateFormat(
      null,
      'bg',
      areaMarksColor['data'],
      formState.beginRow,
      formState.endRow,
      formState.beginColum,
      formState.endColum,
      false
    )
  }
}
const resetFormState = () => {
  Object.assign(formState, {
    beginRow: '',
    endRow: '',
    beginColum: '',
    endColum: '',
    sheetNum: 0
  })
  groupTitles.value = []
  areaTitles.value = []
}
const back = () => {
  // 清空颜色
  resetAttchBg()
  resetFormState()
  emits('next', -1)
}
defineExpose({
  resetFormState
})
</script>
<style lang="scss" scoped>
.set-attch-table {
  padding: 8px;
}
</style>
