ai_scheduler/internal/tools/bbxt/bbxt.go

134 lines
2.9 KiB
Go

package bbxt
import (
"ai_scheduler/internal/pkg"
"fmt"
"reflect"
"time"
"github.com/xuri/excelize/v2"
)
type BbxtTools struct {
cacheDir string
excelTempDir string
ct []string
}
func NewBbxtTools() (*BbxtTools, error) {
cache, err := pkg.GetCacheDir()
if err != nil {
return nil, err
}
tempDir, err := pkg.GetTmplDir()
if err != nil {
return nil, err
}
now := time.Now()
return &BbxtTools{
cacheDir: cache,
excelTempDir: fmt.Sprintf("%s/excel_temp", tempDir),
ct: []string{
time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Format("2006-01-02 15:04:05"),
time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, now.Location()).Format("2006-01-02 15:04:05"),
},
}, nil
}
func (b *BbxtTools) DailyReport() (err error) {
err = b.StatisOursProductLossSumTotal()
if err != nil {
return
}
return
}
// OursProductLossSum 负利润分析
func (b *BbxtTools) StatisOursProductLossSumTotal() (err error) {
data, err := StatisOursProductLossSumApi(&StatisOursProductLossSumReq{
Ct: b.ct,
})
if err != nil {
return
}
var (
total [][]string
gt [][]string
)
for _, v := range data.List {
if v.Loss <= -100 {
total = append(total, []string{
v.OursProductName,
fmt.Sprintf("%.2f", v.Loss),
})
}
if v.Loss <= -500 {
gt = append(gt, []string{
v.OursProductName,
fmt.Sprintf("%.2f", v.Loss),
})
}
}
//总量生成excel
if len(total) > 0 {
filePath := b.cacheDir + "/kshj_total" + fmt.Sprintf("%d", time.Now().Unix()) + ".xlsx"
err = b.SimpleFillExcel(b.excelTempDir+"/"+"kshj_total.xlsx", filePath, total)
}
return err
}
// 最简单的通用函数
func (b *BbxtTools) SimpleFillExcel(templatePath, outputPath string, dataSlice interface{}) error {
// 1. 打开模板
f, err := excelize.OpenFile(templatePath)
if err != nil {
return err
}
defer f.Close()
sheet := f.GetSheetName(0)
// 2. 反射获取切片数据
v := reflect.ValueOf(dataSlice)
if v.Kind() != reflect.Slice {
return fmt.Errorf("dataSlice must be a slice")
}
// 3. 从第2行开始填充
row := 2
for i := 0; i < v.Len(); i++ {
item := v.Index(i).Interface()
currentRow := row + i
// 4. 将item转换为一行数据
var rowData []interface{}
// 如果是切片
if reflect.TypeOf(item).Kind() == reflect.Slice {
itemV := reflect.ValueOf(item)
for j := 0; j < itemV.Len(); j++ {
rowData = append(rowData, itemV.Index(j).Interface())
}
} else if reflect.TypeOf(item).Kind() == reflect.Struct {
itemV := reflect.ValueOf(item)
for j := 0; j < itemV.NumField(); j++ {
if itemV.Field(j).CanInterface() {
rowData = append(rowData, itemV.Field(j).Interface())
}
}
} else {
rowData = []interface{}{item}
}
// 5. 填充到Excel
for col, value := range rowData {
cell := fmt.Sprintf("%c%d", 'A'+col, currentRow)
f.SetCellValue(sheet, cell, value)
}
}
// 6. 保存
return f.SaveAs(outputPath)
}