package excel

import (
	"fmt"
	"reflect"

	"github.com/360EntSecGroup-Skylar/excelize"
)

// WriteXlsx 生成表格到本地服务器
func WriteXlsx(sheet string, records interface{}) *excelize.File {
	f := excelize.NewFile()    // new file
	index := f.NewSheet(sheet) // new sheet
	f.SetActiveSheet(index)    // set active (default) sheet
	firstCharacter := 65       // start from 'A' line
	t := reflect.TypeOf(records)

	if t.Kind() != reflect.Slice {
		return f
	}

	s := reflect.ValueOf(records)
	for i := 0; i < s.Len(); i++ {
		elem := s.Index(i).Interface()
		elemType := reflect.TypeOf(elem)
		elemValue := reflect.ValueOf(elem)
		for j := 0; j < elemType.NumField(); j++ {
			field := elemType.Field(j)
			// 结构体中xlsx 类似json
			tag := field.Tag.Get("xlsx")
			name := tag
			column := string(firstCharacter + j)
			if tag == "" {
				continue
			}
			// 设置表头
			if i == 0 {
				f.SetCellValue(sheet, fmt.Sprintf("%s%d", column, i+1), name)
			}
			// 设置列宽
			f.SetColWidth(sheet, "A", fmt.Sprintf("%s", column), 20)

			// 设置内容
			f.SetCellValue(sheet, fmt.Sprintf("%s%d", column, i+2), elemValue.Field(j).Interface())
		}
	}
	return f
}
