import type { Recordable } from '@/types/global'
import { ElMessage } from 'element-plus'
const luckysheet = (window as any).luckysheet

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) {
  if (row0 == 0 && row1 == 0 && column0 == 0 && column1 == 0) {
    return 'A1'
  }
  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) {
  const sheet = luckysheet.getSheet()
  const [beginRow, endRow] = sheet.luckysheet_select_save[0].row
  const [beginColum, endColum] = sheet.luckysheet_select_save[0].column
  let rowLen = range.length
  let columnLen = range[0].length
  let isOneRow = !(rowLen > 1)
  let isOneColumn = !(columnLen > 1)

  return {
    rowLen,
    columnLen,
    beginRow,
    endRow,
    sheetNum: sheet.order,
    beginColum,
    endColum,
    isOneRow,
    isOneColumn
  }
}

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

  // 只有一行，只能横向
  if (rowLen == 1) {
    isVertical = false
  } else if (
    rowLen - 1 === endRow - beginRow &&
    (columnLen - 1 !== endColum - beginColum || columnLen == 1)
  ) {
    isVertical = true
  }
  /**
   * 由底向上循环
   * 横向 -> row 不变  纵向 -> column 不变
   *
   */
  for (let c = 0; c < (isVertical ? rowLen : columnLen); c++) {
    const title = {
      title: '',
      sheet: sheetNum,
      row: !isVertical ? +beginRow + rowLen - 1 : endRow - rowLen - 1,
      colum: isVertical ? +beginColum + columnLen - 1 : endColum - columnLen - 1
    }
    for (let r = (isVertical ? columnLen : rowLen) - 1; r >= 0; r--) {
      const cell = isVertical ? range[c][r] : range[r][c]

      isVertical ? (title.row = +beginRow + c) : (title.colum = +beginColum + c)
      // 如果获取值报错，那么断定单元格值为空，直接取上一个单元格的值
      try {
        title.title = (cell.m || cell.v || cell?.ct?.s.map((itm) => itm.v).join('')).replaceAll(
          /(\s+)/g,
          ''
        )
        // 如果有值那么直接进入下一列或者下一行
        if (title.title) {
          // 如果有合并单元格，直接跳过合并的单元格
          if (cell?.mc?.rs > 1 || cell?.mc?.cs > 1) {
            c += (isVertical ? cell.mc.rs : cell.mc.cs) - 1
          }
          break
        }
      } catch {
        continue
      }
    }
    titles.push(title)
  }

  return titles
}

export function handleRangeCell(range: any, cb?: any, skipEmpty: boolean = true) {
  console.log(luckysheet.getRangeValue(), 'range-----')
  // return
  const { beginRow, beginColum, endRow, sheetNum, endColum, columnLen, rowLen } =
    getRangeState(range)
  const titles = []
  const mergeCells: any = []
  for (let c = 0; c < columnLen; c++) {
    for (let r = 0; r < rowLen; r++) {
      const t = {
        title: '',
        sheet: sheetNum,
        row: +beginRow + r,
        colum: +beginColum + c
      }
      if (mergeCells.includes(`${t.row}_${t.colum}`)) {
        continue
      }
      const cell = range[r][c]

      try {
        t.title = (cell.m || cell.v || cell?.ct?.s?.map((itm) => itm.v)?.join('')).replaceAll(
          /(\s+)/g,
          ''
        )
        // 如果有合并单元格，直接跳过合并的单元格
        if (cell?.mc?.rs > 1) {
          Array.from({ length: cell.mc.rs - 1 }, (_, i) => {
            mergeCells.push(`${t.row + i + 1}_${t.colum}`)
          })
        }
        if (cell?.mc?.cs > 1) {
          Array.from({ length: cell.mc.cs - 1 }, (_, i) => {
            mergeCells.push(`${t.row}_${t.colum + i + 1}`)
          })
        }
        titles.push(t)
        cb && cb(t)
      } catch (e) {
        console.log(r, c, t, e, cell, 'error')
        if (!skipEmpty) {
          titles.push(t)
          cb && cb(t)
        }
      }
    }
  }
  console.log('----titles', titles)
  return titles
}
/**
 * 获取当前选取的坐标
 * @returns
 */
export function getRangePosition() {
  const sheet = luckysheet.getSheet()
  if (sheet.luckysheet_select_save.length == 1) {
    const [beginRow, endRow] = sheet.luckysheet_select_save[0].row
    const [beginColum, endColum] = sheet.luckysheet_select_save[0].column
    return {
      endRow,
      beginRow,
      endColum,
      beginColum,
      sheetNum: sheet.order
    }
  } else {
    ElMessage.error('请选择一个区域！')
    return
  }
}

/**
 * 是否是当前sheet
 * @param sheetNum 当前sheet order
 * @returns
 */
export function isCurrentSheet(sheetNum: number | string) {
  return luckysheet.getSheet().order == sheetNum
}

/**
 * 设置显示sheet页
 * @param sheetNum 显示sheet的order值
 * @returns
 */
export function setCurrentSheet(sheetNum: number | string) {
  if (isCurrentSheet(sheetNum)) {
    return
  }
  luckysheet.setSheetActive(sheetNum)
}

/**
 * 设置单元格背景颜色
 * @param range
 * @param bg
 * @param isChangeSheet 是否切换当前sheet
 */
export function setRangeBackground(range: Recordable, bg: string, isChangeSheet: boolean = true) {
  const r = {
    beginRow: '',
    endRow: '',
    beginColum: '',
    endColum: '',
    sheetNum: ''
  }
  if (Reflect.has(range, 'beginRow')) {
    Object.assign(r, range)
  } else {
    r.beginRow = range.row
    r.endRow = range.row
    r.beginColum = range.colum
    r.endColum = range.colum
    r.sheetNum = range.sheet
  }

  isChangeSheet && setCurrentSheet(r.sheetNum)

  luckysheet.menuButton.customUpdateFormat(
    null,
    'bg',
    bg,
    r.beginRow,
    r.endRow,
    r.beginColum,
    r.endColum,
    false
  )
}

/**
 * 解析后数据，处理表头和表格数据
 * @param data
 */
export function filterRunData(data: any, config: boolean = false) {
  const res: Recordable[] = []
  const titles: Set<string> = new Set()
  // 映射字段配置生成
  const configs: Recordable = {}
  const temConf = {
    // title: '',
    // content: '',
    // mapField: '',
    // scriptName: '',
    // groupTitle: '',
    // templateFileId: '',
    // excelOrderFiledConfId: '',
    // params: {},
    // orderFiled: {},
    excelOrderFiledConfId: '',
    title: '',
    orderFiledConfs: [],
    templateFileId: ''
  }

  console.log(data, 'data-----')

  data.forEach((row: any) => {
    const rw: Recordable = {}
    row.order.forEach((itm: any) => {
      Reflect.set(rw, itm.title, itm.value)
      titles.add(itm.title)
      if (!Reflect.has(configs, itm.title) && config) {
        configs[itm.title] = { ...structuredClone(temConf), title: itm.title }
      }
    })
    // 是否有附加信息
    // if (row?.groups?.length) {
    //   Reflect.set(rw, 'expendData', {})
    //   row.groups.forEach((itm: any) => {
    //     rw['expendData'][itm.title] = []
    //     const r: Recordable = {}
    //     itm.item.forEach((v: any) => {
    //       r[v.title] = v.value
    //     Reflect.set(configs, itm.title+'__'+v.title, temConf)

    //     })
    //     rw['expendData'][itm.title].push(r)
    //   })
    // }

    res.push(rw)
  })

  console.log('----res', res)

  return {
    res,
    titles: [...titles],
    configs
  }
}

/**
 * 解析后数据，处理表头和表格数据
 * @param data
 */
export function filterRunData2(data: any, config: boolean = false) {
  const res: Recordable[] = []
  const titles: Set<string> = new Set()
  // 映射字段配置生成
  const configs: Recordable = {}
  const temConf = {
    excelOrderFiledConfId: '',
    title: '',
    filedConfs: [],
    templateFileId: ''
  }

  data.forEach((row: any) => {
    const rw: Recordable = {}
    row.order.forEach((itm: any) => {
      Reflect.set(rw, itm.title, itm.value)
      titles.add(itm.title)
      if (!Reflect.has(configs, itm.title) && config) {
        configs[itm.title] = { ...structuredClone(temConf), title: itm.title }
      }
    })

    res.push(rw)
  })
  return {
    res,
    titles: [...titles],
    configs
  }
}

export function filterVarData(data: any) {
  const res: Recordable[] = []
  const titles: Set<string> = new Set()
  const baseFieldMap = {
    imageName: '底图名称',
    orderCodeNo: '销售单号+行项次',
    orderNum: '参考数',
    brandName: '品牌名称',
    customerName: '客户名称',
    quarter: '季度',
    productCode: '产品编码'
  }
  titles
    .add('底图名称')
    .add('销售单号+行项次')
    .add('参考数')
    .add('品牌名称')
    .add('客户名称')
    .add('季度')
    .add('产品编码')

  data.forEach((row: any) => {
    const rw: Recordable = {}
    Reflect.set(rw, '底图名称', row['imageName'])
    Reflect.set(rw, '销售单号+行项次', row['orderCodeNo'])
    Reflect.set(rw, '参考数', row['orderNum'])
    Reflect.set(rw, '品牌名称', row['brandName'])
    Reflect.set(rw, '客户名称', row['customerName'])
    Reflect.set(rw, '季度', row['quarter'])
    Reflect.set(rw, '产品编码', row['productCode'])

    // 变量信息
    row.varOrder.order.forEach((itm: any) => {
      Reflect.set(rw, itm.title, itm.value)
      titles.add(itm.title)
    })

    res.push(rw)
  })
  return {
    res,
    titles: [...titles]
  }
}

/**比较两个单元格是否是同一个 */
export function compareSameCell(c1, c2) {
  return c1.sheet == c2.sheet && c1.row == c2.row && c1.colum == c2.colum
}
