package main

import (
	"encoding/json"
	"fmt"
	"strings"

	"github.com/xuri/excelize/v2"
)

func main() {
	fmt.Println("========================= OMC loadpmxls startup =========================")
	fmt.Println("OMC loadpmxls version: %s %s %s", version, buildTime, goVer)

	for _, f := range pfiles {
		fmt.Println("f:", f)
		db := yamlConfig.Database
		sqlStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", db.User, db.Password, db.Host, db.Port, db.Name)
		XormConnectDatabaseWithUri(sqlStr)
		LoadPmIntoMeasureTitle(f)
	}

}

func LoadPmIntoMeasureTitle(file string) {
	fmt.Println("file len:", file, len(file))
	f, err := excelize.OpenFile(file)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	list := f.GetSheetList()
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	fmt.Println(list)
	dl := len(yamlConfig.PmFileDir) + 1
	neType := file[dl : dl+3]
	fmt.Println("neType:", neType)
	for _, s := range list {
		if s[0] == 'H' {
			rows, _ := f.GetRows(s)
			var kpiCode, desc, objectType string
			for _, row := range rows[1:] {
				if row[0] != "" {
					kpiCode = row[0]
				}
				if len(row) > 4 && row[4] != "" {
					desc = row[4]
				}
				if len(row) > 9 && row[9] != "" {
					objectType = row[9]
				}
				enKpiId := strings.Replace(row[2], " ", "", -1)
				enKpiId = strings.Replace(enKpiId, "\n", "", -1)
				isPseudo := "false"
				if strings.Contains(enKpiId, "_") {
					isPseudo = "true"
				}
				cnKpiId := strings.Replace(row[3], " ", "", -1)
				cnKpiId = strings.Replace(cnKpiId, "\n", "", -1)
				titleJson := map[string]string{"cn": cnKpiId, "en": enKpiId}
				tj, _ := json.Marshal(titleJson)
				measureTitle := MeasureTitle{neType, kpiCode, enKpiId, isPseudo, objectType, "15M", string(tj), desc}
				fmt.Println("measureTitle:", measureTitle)
				//fmt.Print(kpiCode, "\t", row[2], "\t", row[3], "\t", row[4], "\n")
				XormInsertMeasureTitle(&measureTitle)
			}
		}
	}
}
