package utils

import (
	"bytes"
	"fmt"
	"mime/multipart"
	"strconv"

	"github.com/xuri/excelize/v2"
)

// GetColumnName 获取Excel列名 (1->A, 2->B, ..., 27->AA)
func GetColumnName(n int) string {
	columnName := ""
	for n > 0 {
		n--
		columnName = string(rune('A'+n%26)) + columnName
		n /= 26
	}
	return columnName
}

// CreateExcelFile 创建Excel文件
func CreateExcelFile() *excelize.File {
	return excelize.NewFile()
}

// OpenExcelFile 打开Excel文件
func OpenExcelFile(file *multipart.FileHeader) (*excelize.File, error) {
	src, err := file.Open()
	if err != nil {
		return nil, err
	}
	defer src.Close()
	return excelize.OpenReader(src)
}

// WriteExcelRows 写入Excel行数据
func WriteExcelRows(f *excelize.File, sheetName string, rows [][]interface{}) error {
	for i, row := range rows {
		for j, cell := range row {
			cellName := fmt.Sprintf("%s%d", GetColumnName(j+1), i+1)
			if err := f.SetCellValue(sheetName, cellName, cell); err != nil {
				return err
			}
		}
	}
	return nil
}

// WriteExcelRow 写入单行数据
func WriteExcelRow(f *excelize.File, sheetName string, rowIndex int, row []interface{}) error {
	for j, cell := range row {
		cellName := fmt.Sprintf("%s%d", GetColumnName(j+1), rowIndex)
		if err := f.SetCellValue(sheetName, cellName, cell); err != nil {
			return err
		}
	}
	return nil
}

// ExcelToBuffer 将Excel文件写入Buffer
func ExcelToBuffer(f *excelize.File) (*bytes.Buffer, error) {
	return f.WriteToBuffer()
}

// ReadExcelRows 读取Excel所有行
func ReadExcelRows(f *excelize.File, sheetName string) ([][]string, error) {
	return f.GetRows(sheetName)
}

// SetCellValueAuto 自动类型设置单元格值
func SetCellValueAuto(f *excelize.File, sheetName, cell string, value string) error {
	// 尝试解析为数字
	if v, err := strconv.ParseFloat(value, 64); err == nil {
		return f.SetCellValue(sheetName, cell, v)
	}
	if v, err := strconv.ParseInt(value, 10, 64); err == nil {
		return f.SetCellValue(sheetName, cell, v)
	}
	return f.SetCellValue(sheetName, cell, value)
}
