package excel

import (
	"bswas/utilities"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
)

const SHEET  = "Sheet1"

func CreateFile(row []interface{},list [][]interface{}, mergeRow map[string]string, mergeColumn []string) (excel *excelize.File) {
    /* 生成文件 */
	file := excelize.NewFile()
	streamWriter, err := file.NewStreamWriter(SHEET)
	if err != nil {
		utilities.WriteLog("/excel/export.go:15   文件生成失败!","ERROR")
	}

	/* 换行 */
    styleID, err := file.NewStyle(&excelize.Style{
        Alignment: &excelize.Alignment{
            WrapText: true,
        },
    })
    if err != nil {
        utilities.WriteLog("/excel/export.go:25  创建换行样式失败!","ERROR")
    }
    end, _ := excelize.ColumnNumberToName(len(row))
    err = file.SetColStyle(SHEET, "A:"+end, styleID)
    if err != nil {
        utilities.WriteLog("/excel/export.go:30  设置换行格式失败!","ERROR")
        return
    }

    /* 写入表头 */
	cell, _ := excelize.CoordinatesToCellName(1, 1)
	if err := streamWriter.SetRow(cell, row); err != nil {
		utilities.WriteLog("/excel/export.go:37  写入表头失败!","ERROR")
	}
	/* 流式写入数据 */
	for index := 0; index < len(list); index++ {
		cell, _ := excelize.CoordinatesToCellName(1, index+2)
		if err := streamWriter.SetRow(cell, list[index]); err != nil {
			utilities.WriteLog("/excel/export.go:43  数据写入文件失败!","ERROR")
		}
	}
	/* 合并操作 */
	if mergeRow != nil && mergeColumn != nil {
		for start,end := range mergeRow {
			for i := 0;i<len(mergeColumn); i++ {
				err := file.MergeCell(SHEET,mergeColumn[i]+start,mergeColumn[i]+end)
				if err != nil {
					utilities.WriteLog("/excel/export.go:52  合并单元格失败!","ERROR")
					return
				}
			}
		}
	}

	if err := streamWriter.Flush(); err != nil {
		utilities.WriteLog("/excel/export.go:60  文件流关闭失败!","ERROR")
	}
	return file
}
