package main

import (
	"fmt"

	_ "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 MeasureTitle struct {
	//	Id         int    `json:"id" xorm:"pk 'id' autoincr"`
	NeType      string `json:"neType"`
	KpiCode     string `json:"kpiCode"`
	KpiId       string `json:"kpiId" xorm:"kpi_id"`
	Pseudo      string `json:"pseudo" xorm:"pseudo"`
	ObjectType  string `json:"objectType" xorm:"object_type"`
	Period      string `json:"period" xorm:"period"`
	TitleJson   string `json:"titleJson" xorm:"title_json"`
	Description string `json:"description"`
}

func XormInsertMeasureTitle(row *MeasureTitle) (int64, error) {

	session := xEngine.NewSession()
	defer session.Close()
	_, err := session.
		Table("measure_title").
		Where("ne_type = ? and kpi_code = ? and kpi_id = ?", row.NeType, row.KpiCode, row.KpiId).
		Delete()
	if err != nil {
		fmt.Println("Failed to delete measure_title:", err)
	}
	affected, err := session.Table("measure_title").Insert(row)
	if err != nil {
		fmt.Println("Failed to insert measure_title:", err)
	}

	return affected, err
}
