// Package excel -----------------------------
// @file      : writer.go
// @author    : JJXu
// @contact   : wavingbear@163.com
// @time      : 2023/9/1 14:11
// -------------------------------------------
package excel

import (
	"errors"
	"fmt"
	"reflect"
)

var writerMap = map[reflect.Kind]func(exc *Excel, sheetObj Sheet, SheetData reflect.Value, SheetType reflect.Type, firstRow int) error{
	reflect.Slice:  sliceWriter,
	reflect.Struct: structWriter,
}

func RegisterWriter(dataKind reflect.Kind, function func(exc *Excel, sheetObj Sheet, SheetData reflect.Value, SheetType reflect.Type, firstRow int) error) error {
	if _, exists := writerMap[dataKind]; exists {
		return errors.New(fmt.Sprintf("dataKind: %v has existed", dataKind))
	}
	writerMap[dataKind] = function
	return nil
}

func sliceWriter(exc *Excel, sheetObj Sheet, SheetData reflect.Value, SheetDataType reflect.Type, firstRow int) error {
	var cellNameList = sheetObj.GetJsonFiledList()
	if cellNameList == nil {
		cellNameList = exc.getJsonFieldList(SheetDataType)
	}
	var rowLen = SheetData.Len()
	for i := 0; i < rowLen; i++ {
		var dataMap = exc.dataToMap(SheetData.Index(i), SheetDataType)
		for column, v := range cellNameList {
			var axis = GetCellIndex(i+firstRow+1, column+1)
			err := exc.ex.SetCellValue(sheetObj.SheetName(), axis, dataMap[v])
			if err != nil {
				return err
			}
		}
	}
	//设置数据格式
	dataStyleID, errs := exc.ex.NewStyle(NewDefaultDataStyle())
	if errs != nil {
		return errs
	}
	if err := exc.ex.SetCellStyle(sheetObj.SheetName(), GetCellIndex(firstRow+1, 1), GetCellIndex(rowLen+1, len(sheetObj.SheetHeaders())), dataStyleID); err != nil {
		return err
	}
	//设置默认列宽
	//exc.ex.SetColWidth(sheetObj.SheetName(), GetColumnIndex(1), GetColumnIndex(len(sheetObj.SheetHeaders())), 12.0)
	exc.autoResetCellWidth(sheetObj)
	return nil
}

func structWriter(exc *Excel, sheetObj Sheet, SheetData reflect.Value, SheetType reflect.Type, firstRow int) error {
	var cellNameList = exc.getJsonFieldList(SheetType)
	var dataMap = exc.dataToMap(SheetData, SheetType)
	for column, v := range cellNameList {
		var axis = GetCellIndex(firstRow+1, column+1)
		err := exc.ex.SetCellValue(sheetObj.SheetName(), axis, dataMap[v])
		if err != nil {
			fmt.Println(err.Error())
			return err
		}
	}
	//设置数据格式
	dataStyleID, err := exc.ex.NewStyle(NewDefaultDataStyle())
	if err != nil {
		return err
	}
	if err = exc.ex.SetCellStyle(sheetObj.SheetName(), GetCellIndex(firstRow, 1), GetCellIndex(firstRow+1, len(sheetObj.SheetHeaders())), dataStyleID); err != nil {
		return err
	}
	//设置默认列宽
	//exc.ex.SetColWidth(sheetObj.SheetName(), GetColumnIndex(1), GetColumnIndex(len(sheetObj.SheetHeaders())), 12.0)
	exc.autoResetCellWidth(sheetObj)
	return nil
}
