package services

import (
	"encoding/json"
	"eta/eta_data_init/models"
	"eta/eta_data_init/utils"
	"fmt"
	"github.com/xuri/excelize/v2"
	"os"
	"path/filepath"
	"strings"
	"time"
)

const (
	MethodClassifyReset = "edb_info/classify_reset"
)

func ResetHzEdbClassify() {
	fmt.Println("start ResetHzEdbClassify")
	for _, v := range []string{"ETA基础指标0821整理", "ETA计算指标0821整理"} {
		time.Sleep(5 * time.Second)
		ResetEdbClassify(v)
	}
	fmt.Println("end ResetHzEdbClassify")
}

// ResetEdbClassify 重置指标分类
func ResetEdbClassify(fileName string) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println("ResetBaseEdbAndClassify Err: " + err.Error())
		}
	}()

	path, e := filepath.Abs(os.Args[0])
	if e != nil {
		err = fmt.Errorf("path abs err: %s", e.Error())
		return
	}
	dir := filepath.Dir(path)
	//dataPath := dir + "/docs/ETA计算指标0821整理.xlsx"
	dataPath := fmt.Sprintf("%s/docs/%s.xlsx", dir, fileName)
	fmt.Println("dataPath:" + dataPath)

	f, e := excelize.OpenFile(dataPath)
	if e != nil {
		err = fmt.Errorf("open file err: %s", e.Error())
		return
	}
	defer func() {
		if e = f.Close(); e != nil {
			fmt.Println("file close err: " + e.Error())
		}
	}()

	rows, e := f.GetRows("Sheet1")
	if e != nil {
		err = fmt.Errorf("get rows err: %s", e.Error())
		return
	}
	if len(rows) == 0 {
		err = fmt.Errorf("empty rows")
		return
	}

	// 读取行
	utils.FileLog.Info("开始初始化")
	for rk, row := range rows {
		if rk == 0 {
			continue
		}

		var indexCode, classifyFirst, classifySecond, classifyThird string
		// 读取单元格
		for ck, cell := range row {
			switch ck {
			case 2:
				indexCode = strings.TrimSpace(cell)
			case 7:
				classifyFirst = strings.TrimSpace(cell)
			case 8:
				classifySecond = strings.TrimSpace(cell)
			case 9:
				classifyThird = strings.TrimSpace(cell)
			}
		}
		if indexCode == "" || classifyFirst == "" || classifySecond == "" || classifyThird == "" {
			utils.FileLog.Info("忽略第%d行, IndexCode: %s, ClassifyFirst: %s, ClassifySecond: %s, ClassifyThird: %s", rk+1, indexCode, classifyFirst, classifySecond, classifyThird)
			continue
		}
		utils.FileLog.Info("第%d行, IndexCode: %s", rk+1, indexCode)

		params := make(map[string]interface{})
		params["IndexCode"] = indexCode
		params["ClassifyFirst"] = classifyFirst
		params["ClassifySecond"] = classifySecond
		params["ClassifyThird"] = classifyThird
		result, e := PostEdbLib(params, MethodClassifyReset)
		if e != nil {
			b, _ := json.Marshal(params)
			utils.FileLog.Info("重置指标分类失败, err: %s, params: %s", e.Error(), string(b))
			return
		}
		resp := new(models.EdbInfoResp)
		if e := json.Unmarshal(result, &resp); e != nil {
			utils.FileLog.Info("MethodClassifyReset Unmarshal err: %s", e.Error())
			return
		}
		if resp.Ret != 200 {
			utils.FileLog.Info("重置指标分类失败, Msg: %s, ErrMsg: %s", resp.Msg, resp.ErrMsg)
			continue
		}
	}
	utils.FileLog.Info("初始化结束")
}
