// import { createCellPos } from './translateNumToLetter'
const Excel = require('exceljs')

import FileSaver from 'file-saver'
export const testaaa = function (){
  console.log("...");
}

export const exportExcel = function(luckysheet, value) {
  // 参数为luckysheet.getluckysheetfile()获取的对象
  // 1.创建工作簿，可以为工作簿添加属性
  const workbook = new Excel.Workbook()
  // 设置工作簿属性
  workbook.creator = 'SF Cloud Web';
  workbook.lastModifiedBy = 'SF Cloud Web';
  workbook.created = new Date();
  workbook.modified = new Date();

  // 2.创建表格，第二个参数可以配置创建什么样的工作表
  if (Object.prototype.toString.call(luckysheet) === '[object Object]') {
    luckysheet = [luckysheet]
  }
  luckysheet.forEach(function(table) {
    if (table.data.length === 0) return  true

    // 创建工作表并设置属性
    const worksheet = workbook.addWorksheet(table.name, {
      properties: {
        defaultRowHeight: 20, // 默认行高
        tabColor: { argb: 'FFC0000' }
      },
      pageSetup: {
        paperSize: 9, // A4
        orientation: 'portrait' // 纵向
      }
    })

    const merge = (table.config && table.config.merge) || {}
    const borderInfo = (table.config && table.config.borderInfo) || {}
    const columnWidths = (table.config && table.config.columnlen) || {} // 获取列宽配置
    const rowHeights = (table.config && table.config.rowlen) || {} // 获取行高配置

    // 3.设置单元格合并,设置单元格边框,设置单元格样式,设置值
    setStyleAndValue(table.data, worksheet)
    setColumnWidths(worksheet, columnWidths) // 设置列宽
    setRowHeights(worksheet, rowHeights) // 设置行高
    setMerge(merge, worksheet)
    setBorder(borderInfo, worksheet)
    return true
  })

  // 4.写入 buffer
  const buffer = workbook.xlsx.writeBuffer().then(data => {
    const blob = new Blob([data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
    })
    console.log("导出成功！")
    FileSaver.saveAs(blob, `${value}.xlsx`)
  })
  return buffer
}

export const generateExcelBlob = function(luckysheet, fileName) {
  // 参数为luckysheet.getluckysheetfile()获取的对象，返回Blob对象
  const workbook = new Excel.Workbook()
  workbook.creator = 'SF Cloud Web';
  workbook.lastModifiedBy = 'SF Cloud Web';
  workbook.created = new Date();
  workbook.modified = new Date();

  if (Object.prototype.toString.call(luckysheet) === '[object Object]') {
    luckysheet = [luckysheet]
  }
  luckysheet.forEach(function(table) {
    if (table.data.length === 0) return  true

    const worksheet = workbook.addWorksheet(table.name, {
      properties: {
        defaultRowHeight: 20,
        tabColor: { argb: 'FFC0000' }
      },
      pageSetup: {
        paperSize: 9,
        orientation: 'portrait'
      }
    })

    const merge = (table.config && table.config.merge) || {}
    const borderInfo = (table.config && table.config.borderInfo) || {}
    const columnWidths = (table.config && table.config.columnlen) || {}
    const rowHeights = (table.config && table.config.rowlen) || {}

    setStyleAndValue(table.data, worksheet)
    setColumnWidths(worksheet, columnWidths)
    setRowHeights(worksheet, rowHeights)
    setMerge(merge, worksheet)
    setBorder(borderInfo, worksheet)
    return true
  })

  return workbook.xlsx.writeBuffer().then(data => {
    const blob = new Blob([data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
    })
    if (fileName) {
      blob.name = `${fileName}.xlsx`
    }
    return blob
  })
}

export const generateExcelFile = function(luckysheet, fileName) {
  // 参数为luckysheet.getluckysheetfile()获取的对象，返回File对象
  return generateExcelBlob(luckysheet, fileName).then(blob => {
    const file = new File([blob], `${fileName || 'export'}.xlsx`, {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
    })
    return file
  })
}

let setMerge = function(luckyMerge = {}, worksheet) {
  const mergearr = Object.values(luckyMerge)
  mergearr.forEach(function(elem) {
    // elem格式：{r: 0, c: 0, rs: 1, cs: 2}
    // 按开始行，开始列，结束行，结束列合并（相当于 K10:M12）
    worksheet.mergeCells(
      elem.r + 1,
      elem.c + 1,
      elem.r + elem.rs,
      elem.c + elem.cs
    )
  })
}

let setBorder = function(luckyBorderInfo, worksheet) {
  if (!Array.isArray(luckyBorderInfo)) return
  // console.log('luckyBorderInfo', luckyBorderInfo)
  luckyBorderInfo.forEach(function(elem) {
    // 现在只兼容到borderType 为range的情况
    // console.log('ele', elem)
    if (elem.rangeType === 'range') {
      // 添加对elem.borderType, elem.style, elem.color的检查
      if (!elem.borderType) return;

      let border = borderConvert(elem.borderType, elem.style, elem.color)
      let rang = elem.range[0]
      // console.log('range', rang)
      let row = rang.row
      let column = rang.column
      for (let i = row[0] + 1; i < row[1] + 2; i++) {
        for (let y = column[0] + 1; y < column[1] + 2; y++) {
          worksheet.getCell(i, y).border = border
        }
      }
    }
    if (elem.rangeType === 'cell') {
      // col_index: 2
      // row_index: 1
      // b: {
      //   color: '#d0d4e3'
      //   style: 1
      // }
      const { col_index, row_index } = elem.value
      // 添加对elem.value的检查
      if (!elem.value) return;

      const borderData = Object.assign({}, elem.value)
      delete borderData.col_index
      delete borderData.row_index

      // 添加对borderData的验证
      let hasValidBorder = false;
      for (const key in borderData) {
        if (borderData[key] && typeof borderData[key] === 'object' && borderData[key].color) {
          hasValidBorder = true;
          break;
        }
      }

      if (!hasValidBorder) return;

      let border = addborderToCell(borderData, row_index, col_index)
      // console.log('bordre', border, borderData)
      worksheet.getCell(row_index + 1, col_index + 1).border = border
    }
    // console.log(rang.column_focus + 1, rang.row_focus + 1)
    // worksheet.getCell(rang.row_focus + 1, rang.column_focus + 1).border = border
  })
}

// 新增：设置列宽
let setColumnWidths = function(worksheet, columnWidths) {
  if (!columnWidths || Object.keys(columnWidths).length === 0) {
    // 如果没有列宽配置，设置默认列宽
    worksheet.columns.forEach(column => {
      column.width = 15; // 默认宽度
    });
    return;
  }

  // 根据配置设置列宽
  Object.keys(columnWidths).forEach(colIndex => {
    const width = columnWidths[colIndex];
    // 转换为Excel的列宽单位（大约是字符宽度的倍数）
    const excelWidth = Math.max(8, Math.min(100, width / 7)); // 限制在合理范围内
    worksheet.getColumn(parseInt(colIndex) + 1).width = excelWidth;
  });
}

// 新增：设置行高
let setRowHeights = function(worksheet, rowHeights) {
  if (!rowHeights || Object.keys(rowHeights).length === 0) return;

  Object.keys(rowHeights).forEach(rowIndex => {
    const height = rowHeights[rowIndex];
    worksheet.getRow(parseInt(rowIndex) + 1).height = Math.max(15, Math.min(409, height)); // 限制在合理范围内
  });
}

let setStyleAndValue = function(cellArr, worksheet) {
  if (!Array.isArray(cellArr)) return

  cellArr.forEach(function(row, rowid) {
    row.every(function(cell, columnid) {
      if (!cell) return true

      let fill = fillConvert(cell.bg)
      let font = fontConvert(
        cell.ff,
        cell.fc,
        cell.bl,
        cell.it,
        cell.fs,
        cell.cl,
        cell.ul
      )
      let alignment = alignmentConvert(cell.vt, cell.ht, cell.tb, cell.tr)
      let value = ''

      // 处理不同类型的值
      if (cell.f) {
        value = { formula: cell.f, result: cell.v }
      } else if (!cell.v && cell.ct && cell.ct.s) {
        cell.ct.s.forEach(arr => {
          value += arr.v
        })
      } else {
        value = cell.v
      }

      let letter = createCellPos(columnid)
      let target = worksheet.getCell(letter + (rowid + 1))

      // 应用样式
      for (const key in fill) {
        target.fill = fill
        break
      }
      target.font = font
      target.alignment = alignment
      target.value = value

      // 处理数字格式
      if (cell.ct && cell.ct.fa) {
        target.numFmt = convertNumberFormat(cell.ct.fa)
      }

      return true
    })
  })
}

// 新增：转换数字格式
let convertNumberFormat = function(format) {
  const formatMap = {
    'General': 'General',
    '0': '0',
    '0.00': '0.00',
    '#,##0': '#,##0',
    '#,##0.00': '#,##0.00',
    '0%': '0%',
    '0.00%': '0.00%',
    '0.00E+00': '0.00E+00',
    '# ?/?': '# ?/?',
    '# ??/??': '# ??/??',
    'mm-dd-yy': 'mm-dd-yy',
    'd-mmm-yy': 'd-mmm-yy',
    'd-mmm': 'd-mmm',
    'mmm-yy': 'mmm-yy',
    'h:mm AM/PM': 'h:mm AM/PM',
    'h:mm:ss AM/PM': 'h:mm:ss AM/PM',
    'h:mm': 'h:mm',
    'h:mm:ss': 'h:mm:ss',
    'm/d/yy h:mm': 'm/d/yy h:mm',
    '#,##0 ;(#,##0)': '#,##0 ;(#,##0)',
    '#,##0 ;[Red](#,##0)': '#,##0 ;[Red](#,##0)',
    '#,##0.00;(#,##0.00)': '#,##0.00;(#,##0.00)',
    '#,##0.00;[Red](#,##0.00)': '#,##0.00;[Red](#,##0.00)',
    'mm:ss': 'mm:ss',
    '[h]:mm:ss': '[h]:mm:ss',
    'mmss.0': 'mmss.0',
    '##0.0E+0': '##0.0E+0',
    '@': '@'
  }

  return formatMap[format] || 'General'
}

let fillConvert = function(bg) {
  if (!bg) {
    return {}
  }

  // 处理不同的颜色格式
  let bgColor = bg;

  // 处理rgb()格式的颜色
  if (bg.startsWith('rgb(')) {
    const rgbMatch = bg.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
    if (rgbMatch) {
      const r = parseInt(rgbMatch[1]).toString(16).padStart(2, '0');
      const g = parseInt(rgbMatch[2]).toString(16).padStart(2, '0');
      const b = parseInt(rgbMatch[3]).toString(16).padStart(2, '0');
      bgColor = `#${r}${g}${b}`;
    }
  }

  // 处理十六进制颜色格式
  bgColor = bgColor.replace('#', '');
  if (bgColor.length === 8) {
    // 包含alpha通道，转换为ARGB
    const alpha = bgColor.substring(0, 2);
    const rgb = bgColor.substring(2);
    bgColor = alpha + rgb;
  } else if (bgColor.length === 6) {
    // RGB格式，添加不透明的alpha通道
    bgColor = 'FF' + bgColor;
  } else if (bgColor.length === 3) {
    // 简写格式 #RGB -> #RRGGBB
    bgColor = 'FF' + bgColor.split('').map(c => c + c).join('');
  }

  let fill = {
    type: 'pattern',
    pattern: 'solid',
    fgColor: { argb: bgColor.toUpperCase() }
  }
  return fill
}

let fontConvert = function(
  ff = 0,
  fc = '#000000',
  bl = 0,
  it = 0,
  fs = 10,
  cl = 0,
  ul = 0
) {
  // luckysheet：ff(样式), fc(颜色), bl(粗体), it(斜体), fs(大小), cl(删除线), ul(下划线)
  const luckyToExcel = {
    0: 'Microsoft YaHei', // 微软雅黑
    1: 'SimSun', // 宋体
    2: 'SimHei', // 黑体
    3: 'KaiTi', // 楷体
    4: 'FangSong', // 仿宋
    5: 'NSimSun', // 新宋体
    6: 'STXinwei', // 华文新魏
    7: 'STXingkai', // 华文行楷
    8: 'STLiti', // 华文隶书
    9: 'Arial',
    10: 'Times New Roman',
    11: 'Tahoma',
    12: 'Verdana',
    num2bl: function(num) {
      return num === 0 ? false : true
    }
  }

  // 处理字体颜色，支持rgb()格式
  let fontColor = fc || '#000000';
  if (fontColor.startsWith('rgb(')) {
    const rgbMatch = fontColor.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
    if (rgbMatch) {
      const r = parseInt(rgbMatch[1]).toString(16).padStart(2, '0');
      const g = parseInt(rgbMatch[2]).toString(16).padStart(2, '0');
      const b = parseInt(rgbMatch[3]).toString(16).padStart(2, '0');
      fontColor = `#${r}${g}${b}`;
    }
  }

  // 处理十六进制颜色格式
  fontColor = fontColor.replace('#', '');
  if (fontColor.length === 8) {
    // 包含alpha通道
    const alpha = fontColor.substring(0, 2);
    const rgb = fontColor.substring(2);
    fontColor = alpha + rgb;
  } else if (fontColor.length === 6) {
    // RGB格式
    fontColor = 'FF' + fontColor;
  } else if (fontColor.length === 3) {
    // 简写格式 #RGB -> #RRGGBB
    fontColor = 'FF' + fontColor.split('').map(c => c + c).join('');
  }

  let font = {
    name: typeof ff === 'number' ? luckyToExcel[ff] : ff,
    family: 2, // 修改为更通用的字体族
    size: Math.max(8, Math.min(72, fs)), // 限制字体大小范围
    color: { argb: fontColor.toUpperCase() },
    bold: luckyToExcel.num2bl(bl),
    italic: luckyToExcel.num2bl(it),
    underline: luckyToExcel.num2bl(ul),
    strike: luckyToExcel.num2bl(cl)
  }

  return font
}

let alignmentConvert = function(
  vt = 'default',
  ht = 'default',
  tb = 'default',
  tr = 'default'
) {
  const luckyToExcel = {
    vertical: {
      0: 'middle',
      1: 'top',
      2: 'bottom',
      default: 'middle' // 修改默认值为居中
    },
    horizontal: {
      0: 'center',
      1: 'left',
      2: 'right',
      default: 'left'
    },
    wrapText: {
      0: false,
      1: false,
      2: true,
      default: false
    },
    textRotation: {
      0: 0,
      1: 45,
      2: -45,
      3: 'vertical',
      4: 90,
      5: -90,
      default: 0
    }
  }

  let alignment = {
    vertical: luckyToExcel.vertical[vt],
    horizontal: luckyToExcel.horizontal[ht],
    wrapText: luckyToExcel.wrapText[tb],
    textRotation: luckyToExcel.textRotation[tr]
  }
  return alignment
}

let borderConvert = function(borderType, style = 1, color = '#000') {
  if (!borderType) {
    return {}
  }

  const luckyToExcel = {
    type: {
      'border-all': 'all',
      'border-top': 'top',
      'border-right': 'right',
      'border-bottom': 'bottom',
      'border-left': 'left'
    },
    style: {
      0: 'none',
      1: 'thin',
      2: 'hair',
      3: 'dotted',
      4: 'dashDot',
      5: 'dashDot',
      6: 'dashDotDot',
      7: 'double',
      8: 'medium',
      9: 'mediumDashed',
      10: 'mediumDashDot',
      11: 'mediumDashDotDot',
      12: 'slantDashDot',
      13: 'thick'
    }
  }

  // 处理边框颜色，添加边界检查
  let borderColor = color || '#000'; // 确保color有默认值
  if (typeof borderColor === 'string') {
    borderColor = borderColor.replace('#', '')
    if (borderColor.length === 8) {
      const alpha = borderColor.substring(0, 2)
      const rgb = borderColor.substring(2)
      borderColor = alpha + rgb
    } else if (borderColor.length === 6) {
      borderColor = 'FF' + borderColor
    }
  } else {
    borderColor = 'FF000000' // 默认黑色
  }

  let template = {
    style: luckyToExcel.style[style],
    color: { argb: borderColor }
  }
  let border = {}

  if (luckyToExcel.type[borderType] === 'all') {
    border['top'] = template
    border['right'] = template
    border['bottom'] = template
    border['left'] = template
  } else {
    border[luckyToExcel.type[borderType]] = template
  }

  return border
}

function addborderToCell(borders, row_index, col_index) {
  let border = {}
  const luckyExcel = {
    type: {
      l: 'left',
      r: 'right',
      b: 'bottom',
      t: 'top'
    },
    style: {
      0: 'none',
      1: 'thin',
      2: 'hair',
      3: 'dotted',
      4: 'dashDot',
      5: 'dashDot',
      6: 'dashDotDot',
      7: 'double',
      8: 'medium',
      9: 'mediumDashed',
      10: 'mediumDashDot',
      11: 'mediumDashDotDot',
      12: 'slantDashDot',
      13: 'thick'
    }
  }

  for (const bor in borders) {
    // 添加边界检查，确保borders[bor]存在且有color属性
    if (!borders[bor] || !borders[bor].color) {
      continue;
    }

    let borderColor = borders[bor].color
    if (borderColor.indexOf('rgb') === -1) {
      borderColor = borderColor.replace('#', '')
      if (borderColor.length === 8) {
        const alpha = borderColor.substring(0, 2)
        const rgb = borderColor.substring(2)
        borderColor = alpha + rgb
      } else if (borderColor.length === 6) {
        borderColor = 'FF' + borderColor
      }
    }

    border[luckyExcel.type[bor]] = {
      style: luckyExcel.style[borders[bor].style],
      color: { argb: borderColor }
    }
  }

  return border
}

function createCellPos(n) {
  let ordA = 'A'.charCodeAt(0)
  let ordZ = 'Z'.charCodeAt(0)
  let len = ordZ - ordA + 1
  let s = ''
  while (n >= 0) {
    s = String.fromCharCode((n % len) + ordA) + s
    n = Math.floor(n / len) - 1
  }
  return s
}
