package excel

import (
	"fmt"
	"sort"
)

// HandleTableCell 前端d毛需要我根据合并单元格处理掉多余的单元格
func HandleTableCell(oldTableData TableData) (newTableData TableData) {
	newTableData = oldTableData

	mergeList := oldTableData.MergeList
	lenMergeList := len(mergeList)
	if lenMergeList <= 0 {
		return
	}

	deleteRowMap := make(map[int]map[int]int)
	deleteRowList := make([]int, 0)
	deleteColumnMap := make(map[int][]int, 0)
	for i := lenMergeList - 1; i >= 0; i-- {
		tmpMerge := mergeList[i]

		//
		for rowIndex := tmpMerge.MergeRowNum; rowIndex >= 0; rowIndex-- {
			tmpColumnMap := make(map[int]int)
			if columnMap, ok := deleteRowMap[tmpMerge.StartRowIndex+rowIndex]; ok {
				tmpColumnMap = columnMap
			} else {
				deleteRowList = append(deleteRowList, tmpMerge.StartRowIndex+rowIndex)
			}

			deleteColumnList := make([]int, 0)
			if columnList, ok := deleteColumnMap[tmpMerge.StartRowIndex+rowIndex]; ok {
				deleteColumnList = columnList
			}

			for columnIndex := tmpMerge.MergeColumnNum; columnIndex >= 0; columnIndex-- {
				if rowIndex == 0 && columnIndex == 0 {
					continue
				}
				tmpColumnMap[tmpMerge.StartColumnIndex+columnIndex] = tmpMerge.StartColumnIndex + columnIndex
				deleteColumnList = append(deleteColumnList, tmpMerge.StartColumnIndex+columnIndex)
			}

			// 待删除的行
			deleteRowMap[tmpMerge.StartRowIndex+rowIndex] = tmpColumnMap
			// 该行待删除的列
			deleteColumnMap[tmpMerge.StartRowIndex+rowIndex] = deleteColumnList
		}
	}

	sort.Ints(deleteRowList)

	for i := len(deleteRowList) - 1; i >= 0; i-- {
		rowIndex := deleteRowList[i]
		deleteColumnList := deleteColumnMap[rowIndex]
		sort.Ints(deleteColumnList)
		for i := len(deleteColumnList) - 1; i >= 0; i-- {
			columnIndex := deleteColumnList[i]

			// 最后一行合并单元格时，就不再次移除合并的单元格，避免数组越界
			if rowIndex >= len(newTableData.TableDataList) {
				continue
			}
			tmpColumnDataList := newTableData.TableDataList[rowIndex]

			// 最后一列合并单元格时，就不再次移除合并的单元格，避免数组越界
			if columnIndex >= len(tmpColumnDataList) {
				continue
			}
			newTableData.TableDataList[rowIndex] = append(tmpColumnDataList[:columnIndex], tmpColumnDataList[columnIndex+1:]...) // 删除开头N个元素
			//fmt.Println("row:", rowIndex, "===column:", columnIndex)
		}
	}

	// 数据值处理
	for rowIndex, colList := range newTableData.TableDataList {
		for colIndex, v := range colList {
			v.Monitor = handleCellVal(v)
			colList[colIndex] = v
		}
		newTableData.TableDataList[rowIndex] = colList
	}
	return
}

// handleCellVal 处理单元格数据
func handleCellVal(tmpTableColData LuckySheetDataValue) (valueStr string) {
	valueStr = tmpTableColData.Monitor
	if valueStr == `` {
		//valueStr = fmt.Sprint(cellInfo.Value)
		if valueStr == `` && tmpTableColData.CellType.S != nil {
			//不是设置在单元格上面，而是设置在文本上
			for _, cellS := range tmpTableColData.CellType.S {
				valueStr += fmt.Sprint(cellS.Value)
			}
		}
	}
	return
}
