package main

import (
	"encoding/json"
	"fmt"

	"strings"

	_ "github.com/go-sql-driver/mysql"
	"xorm.io/xorm"
)

var xEngine *xorm.Engine

func XormConnectDatabaseWithUri(sql string) (*xorm.Engine, error) {
	//	sqlStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=true&loc=Local", db.User, db.Password, db.Host, db.Port, db.Name)
	sqlStr := fmt.Sprintf("%s?charset=utf8&parseTime=true&loc=Local", sql)
	//	fmt.Printf("sqlStr:%s:******@tcp(%s:%s)/%s?charset=utf8&parseTime=true&loc=Local", db.User, db.Host, db.Port, db.Name)
	var err error
	xEngine, err = xorm.NewEngine("mysql", sqlStr) //1、Create xorm engine
	if err != nil {
		fmt.Println("Failed to connect database:", err)
		return nil, err
	}
	xEngine.ShowSQL(true)
	return xEngine, nil
}

type ParamConfig struct {
	//	Id         int    `json:"id" xorm:"pk 'id' autoincr"`
	NeType     string `json:"neType"`
	NeId       string `json:"neId"`
	TopTag     string `json:"topTag"`
	TopDisplay string `json:"topDisplay"`
	ParamJson  string `json:"paramJson"`
}

func XormInsertParamConfig(mapJson *map[string]interface{}) (int64, error) {
	var affected, a int64
	var err error
	paramConfig := new(ParamConfig)
	for n, d := range *mapJson {
		if d == nil {
			break
		}
		fmt.Printf("n: %s", n)

		for t, p := range d.(map[string]interface{}) {
			if p == nil {
				break
			}
			fmt.Println("t:", t)
			fmt.Println("p:", p)
			for k, v := range p.(map[string]interface{}) {
				fmt.Println("k, v: ", k, v)
				if k == "display" {
					paramConfig.TopDisplay = fmt.Sprintf("%v", v)

				} else {
					pc, _ := json.Marshal(v)
					paramConfig.ParamJson = fmt.Sprintf("{\"%v\":%v}", k, string(pc))
				}
			}

			paramConfig.NeType = strings.ToUpper(n)
			paramConfig.NeId = ""
			paramConfig.TopTag = t
			//			paramConfig.TopDisplay = p["display"]
			//			paramConfig.ParamJson = p.(string)

			fmt.Println("paramConfig:", paramConfig)

			session := xEngine.NewSession()
			defer session.Close()
			_, err = session.Table("param_config").Where("ne_type = ? and top_tag = ?", paramConfig.NeType, paramConfig.TopTag).Delete()
			if err != nil {
				fmt.Println("Failed to delete param_config:", err)
			}
			a, err = session.Insert(paramConfig)
			if err != nil {
				fmt.Println("Failed to insert param_config:", err)
			}
			affected += a
		}
	}

	return affected, err
}
