package main

import (
	"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)
		LoadCmIntoCmTitle(f)
	}

}

func LoadCmIntoCmTitle(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.CmFileDir) + 1
	neType := file[dl : dl+3]
	fmt.Println("neType:", neType)
	objectMap := make(map[string]string, 0)
	for _, s := range list {

		if s[0] == 'I' {
			rows, _ := f.GetRows(s)
			for _, row := range rows[1:] {
				//				fmt.Println("row:", row)
				if len(row) > 1 {
					fmt.Println("row[0]:", row[0], "row[1]", row[1])
					objectMap[row[0]] = row[1]
				}
			}
			fmt.Println("objectMap:", objectMap)
		}
		if s[0] == 'A' {
			rows, _ := f.GetRows(s)
			var code, desc, object string
			object = objectMap[s]
			fmt.Println("object:", object, "s:", s)
			for _, row := range rows[1:] {
				if row[0] != "" {
					code = row[0]
				}
				if len(row) > 4 && row[4] != "" {
					desc = row[4]
				}
				cmEn := strings.Replace(row[2], " ", "", -1)
				cmEn = strings.Replace(cmEn, "\n", "", -1)
				cmCn := strings.Replace(row[3], " ", "", -1)
				cmCn = strings.Replace(cmCn, "\n", "", -1)
				cmTitle := CmTitle{neType, object, code, cmEn, cmCn, desc}
				fmt.Println("cmTitle:", cmTitle)
				XormInsertCmTitle(&cmTitle)
			}
		}
	}
}
