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 CmTitle struct {
	//	Id         int    `json:"id" xorm:"pk 'id' autoincr"`
	NeType      string `json:"neType"`
	Object      string `json:"object" xorm:"object"`
	Code        string `json:"code"`
	CmEn        string `json:"cmEn" xorm:"cm_en"`
	CmCn        string `json:"cmCn" xorm:"cm_cn"`
	Description string `json:"description"`
}

func XormInsertCmTitle(row *CmTitle) (int64, error) {

	session := xEngine.NewSession()
	defer session.Close()
	_, err := session.
		Table("cm_title").
		Where("ne_type = ? and code = ? and cm_en = ?", row.NeType, row.Code, row.CmEn).
		Delete()
	if err != nil {
		fmt.Println("Failed to delete cm_title:", err)
	}
	affected, err := session.Table("cm_title").Insert(row)
	if err != nil {
		fmt.Println("Failed to insert cm_title:", err)
	}

	return affected, err
}
