import type { Recordable } from '@/types/global'

export function chatatABC(n: number) {
  var orda = 'a'.charCodeAt(0)

  var ordz = 'z'.charCodeAt(0)

  var len = ordz - orda + 1

  var s = ''

  while (n >= 0) {
    s = String.fromCharCode((n % len) + orda) + s

    n = Math.floor(n / len) - 1
  }

  return s.toUpperCase()
}

export function getRangetxt(row0: number, row1: number, column0: number, column1: number) {
  // let row0 = range["row"][0], row1 = range["row"][1];
  // let column0 = range["column"][0], column1 = range["column"][1];

  if (row0 == null && row1 == null) {
    return chatatABC(column0) + ':' + chatatABC(column1)
  } else if (column0 == null && column1 == null) {
    return row0 + 1 + ':' + (row1 + 1)
  } else {
    if (column0 == column1 && row0 == row1) {
      return chatatABC(column0) + (row0 + 1)
    } else {
      return chatatABC(column0) + (row0 + 1) + ':' + chatatABC(column1) + (row1 + 1)
    }
  }
}

export function getRangeState(range: any) {
  let rowLen = range.length
  let columnLen = range[0].length
  let isOneRow = !(rowLen > 1)
  let isOneColumn = !(columnLen > 1)

  return {
    rowLen,
    columnLen,
    isOneRow,
    isOneColumn
  }
}

export function handleRangeTitle(range: any, dataArea: Recordable) {
  const { isOneColumn, isOneRow, rowLen, columnLen } = getRangeState(range)
  const { beginColum, beginRow, endRow, endColum, sheetNum } = dataArea
  const titles: Recordable[] = []
  let isVertical = false

  if (rowLen - 1 === endRow - beginRow && columnLen - 1 !== endColum - beginColum) {
    isVertical = true
  }

  /**
   * 横向：以列为单位取值，多值取最后有值单元格
   * 
   * 纵向：以行为单位，多值取最后有值单元格
   */
  for (let c = 0; c < (isVertical ? rowLen : columnLen); c++) {
    const title = {
      title: '',
      sheet: sheetNum,
      row: 0,
      colum: 0
    }
    for (let r = 0; r < (isVertical ? columnLen : rowLen); r++) {
      const cell = isVertical ? range[c][r] : range[r][c]
      let v = ''
      // 如果获取值报错，那么断定单元格值为空，继续执行
      try {
        v = cell.v || cell?.ct?.s.map((itm) => itm.v).join('')
      } catch {}
      if (v != '') {
        title.title = v.replaceAll(' ', '')
        title.colum = +beginColum + (isVertical ? r : c)
        title.row = +beginRow + (isVertical ? c : r)
      }
      // 如果有单元格合并，跳过单元格
      if (cell?.mc) {
        r += isVertical ? cell.mc.rs - 1 : cell.mc.cs - 1
        c += isVertical ? cell.mc.cs - 1 : cell.mc.rs - 1
      }
    }
    titles.push(title)
  }

  return titles
}
