package grmi

import (
	"LAPP_LF_MOM_BACKEND/utils"
	"errors"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"reflect"
	"strings"
)

/******************************************************************************
 *
 * @Function Name            : SaveExcelFile
 *-----------------------------------------------------------------------------
 *
 * @Description              : 把传入的[]interface 数据保存成excel
 *
 * @Function Parameters      : []interface{} 需要保存的数据切片
 *
 * @Function Parameters      : sheetName excel sheet名称
 *
 * @Function Parameters      : prefixFilename 保存文件的前缀名称 后面会有自动添加时间和文件类型后缀
 *
 * @Return Value             : filepath 文件路径
 *
 * @Return Value             : err 执行出现的错误
 *
 * @Author                   : zhangxin
 *
 * @Date                     : 2021-03-19
 *
 ******************************************************************************/
func SaveExcelFile(list []interface{}, titleList []string, sheetName string, prefixFilename string) (filepath string, err error) {
	file := excelize.NewFile()
	if sheetName != "Sheet1" {
		file.NewSheet(sheetName)
		file.DeleteSheet("Sheet1")
	}
	streamWriter, err := file.NewStreamWriter(sheetName)
	if err != nil {
		return "", err
	}
	for index, item := range list {
		if index == 0 {
			typeOfS := reflect.TypeOf(item)
			row := make([]interface{}, typeOfS.NumField())
			if len(titleList) != 0 {
				if len(titleList) != typeOfS.NumField() {
					return "", errors.New("titleList和item字段数量不相等")
				}
				for i := 0; i < typeOfS.NumField(); i++ {
					row[i] = titleList[i]
				}

			} else {
				for i := 0; i < typeOfS.NumField(); i++ {
					row[i] = typeOfS.Field(i).Name
				}
			}

			cell, _ := excelize.CoordinatesToCellName(1, 1)
			if err := streamWriter.SetRow(cell, row); err != nil {
				return "", err
			}
		}
		reflectValue := reflect.ValueOf(item)
		row := make([]interface{}, reflectValue.NumField())
		for i := 0; i < reflectValue.NumField(); i++ {
			var date Date
			var datetime DateTime
			if reflect.TypeOf(date) == reflectValue.Field(i).Type() {
				filed := reflectValue.Field(i).Interface().(Date)
				row[i] = filed.ToString()
			} else if reflect.TypeOf(datetime) == reflectValue.Field(i).Type() {
				filed := reflectValue.Field(i).Interface().(DateTime)
				row[i] = filed.ToString()
			} else {
				row[i] = reflectValue.Field(i)
			}
		}
		cell, _ := excelize.CoordinatesToCellName(1, index+2)
		if err := streamWriter.SetRow(cell, row); err != nil {
			return "", err
		}
	}
	if err := streamWriter.Flush(); err != nil {
		return "", err
	}
	filename := utils.MakeOrderSn(prefixFilename) + ".xlsx"
	dirname, err := utils.GetCurrentPath("web/public/uploadxlsx")
	if err != nil {
		return "", err
	}
	filepath = dirname + "/" + filename
	err = file.SaveAs(filepath)
	if err != nil {
		return "", err
	}
	pathLi := strings.Split(filepath, "web\\")
	if len(pathLi) != 2 {
		return "", errors.New("导出失败,请重试")
	}
	return pathLi[1], nil
}
