package configs

import (
	"crypto/rsa"
	"fmt"
	"github.com/go-redis/redis/v8"
	_ "github.com/go-sql-driver/mysql"
	"github.com/spf13/cast"
	"github.com/spf13/viper"
	"github.com/wechatpay-apiv3/wechatpay-go/utils"
	"log"
	"os"
	"xorm.io/xorm"
)

var (
	Config  *viper.Viper
	Engine  *xorm.Engine
	RedisDb *redis.Client
	WxPay   WxPayConfig
)

//type User struct {
//	Id            int64  `xorm:"'id'" json:"id"`
//	Username      string `xorm:"'username'" json:"username"`
//	Password      string `xorm:"'password'" json:"password"`
//	Creation_time int    `xorm:"'creation_time'" json:"creation_Time"`
//	Login_time    int    `xorm:"'login_time'" json:"login_Time"`
//	Status        int    `xorm:"'status'" json:"status"`
//	Role_id       int    `xorm:"'role_id'" json:"role_id"`
//	Phone         string `xorm:"'phone'" json:"phone"`
//	Email         string `xorm:"'email'" json:"email"`
//	Name          string `xorm:"'name'" json:"name"`
//	Avatar        string `xorm:"'avatar'" json:"avatar"`
//	RecommendCode string `xorm:"'recommend_code'" json:"recommend_code"`
//}
//
//func (receiver User) String() string {
//	return fmt.Sprintf("User{Id:%d, Username:%s, Password:%s, Creation_time:%d, Login_time:%d, Status:%d, Role_id:%d, Phone:%s, Email:%s, Name:%s, Avatar:%s, RecommendCode:%s}", receiver.Id, receiver.Username, receiver.Password, receiver.Creation_time, receiver.Login_time, receiver.Status, receiver.Role_id, receiver.Phone, receiver.Email, receiver.Name, receiver.Avatar, receiver.RecommendCode)
//}
//
//type Role struct {
//	Id        int    `xorm:"'id'" json:"id"`
//	Role_name string `xorm:"'role_name'" json:"role_Name"`
//}
//type Role_authority struct {
//	Authority_id int `xorm:"'authority_id'" json:"authority_id"`
//	Role_id      int `xorm:"'role_id'" json:"role_id"`
//}
//type Authority struct {
//	Id             int    `xorm:"'id'" json:"id"`
//	Authority_name string `xorm:"'authority_name'" json:"authority_Name"`
//	Authority_path string `xorm:"'authority_path'" json:"authority_Path"`
//}
//
//type MysqlData struct {
//	User           `xorm:"extends"`
//	Role           `xorm:"extends"`
//	Role_authority `xorm:"extends"`
//	Authority      `xorm:"extends"`
//}

func ConfigInit() {
	//获取项目的执行路径
	path, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	config := viper.New()

	config.AddConfigPath(path + "/configs") //设置读取的文件路径
	config.SetConfigName("config")          //设置读取的文件名
	config.SetConfigType("yaml")            //设置文件的类型
	//尝试进行配置读取
	if err := config.ReadInConfig(); err != nil {
		panic(err)
	}
	fmt.Println(fmt.Sprintf("%s:%s@(%s:%s)/%s?charset=utf8", config.Get("mysql.user"), config.Get("mysql.password"), config.Get("mysql.host"), config.Get("mysql.port"), config.Get("mysql.database")))
	Engine, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@(%s:%s)/%s?charset=utf8", config.Get("mysql.user"), config.Get("mysql.password"), config.Get("mysql.host"), config.Get("mysql.port"), config.Get("mysql.database")))
	Engine.Ping() //连接测试
	//TODO  显示sql
	Engine.ShowSQL(true)
	Engine.Logger().ShowSQL(true)
	RedisDb = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%s", config.Get("redis.host"), config.Get("redis.port")), // Redis地址
		Password: "",                                                                       // Redis密码，如果没有则为空字符串
		DB:       0,                                                                        // 使用默认DB
	})
	//开启debug模式

	Config = config
	fmt.Println("xorm 数据库orm框架初始化成功")
	//PayConfigInit()
}
func ConfigInitByUrl(configUrl string) {
	//获取项目的执行路径
	config := viper.New()

	config.AddConfigPath(configUrl + "\\configs") //设置读取的文件路径
	config.SetConfigName("config")                //设置读取的文件名
	config.SetConfigType("yaml")                  //设置文件的类型
	//尝试进行配置读取
	if err := config.ReadInConfig(); err != nil {
		panic(err)
	}
	fmt.Println(fmt.Sprintf("%s:%s@(%s:%s)/%s?charset=utf8", config.Get("mysql.user"), config.Get("mysql.password"), config.Get("mysql.host"), config.Get("mysql.port"), config.Get("mysql.database")))
	Engine, _ := xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@(%s:%s)/%s?charset=utf8", config.Get("mysql.user"), config.Get("mysql.password"), config.Get("mysql.host"), config.Get("mysql.port"), config.Get("mysql.database")))
	Engine.Ping() //连接测试
	//TODO  显示sql
	Engine.ShowSQL(true)
	Engine.Logger().ShowSQL(true)
	RedisDb = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%s", config.Get("redis.host"), config.Get("redis.port")), // Redis地址
		Password: "",                                                                       // Redis密码，如果没有则为空字符串
		DB:       0,                                                                        // 使用默认DB
	})

	Config = config
	fmt.Println("xorm 数据库orm框架初始化成功")
}

type WxPayConfig struct {
	MchID                      string
	MchCertificateSerialNumber string
	MchAPIv3Key                string
	PrivateKey                 *rsa.PrivateKey
}

func (w WxPayConfig) String() string {
	return fmt.Sprintf("MchID:%s, MchCertificateSerialNumber:%s, MchAPIv3Key:%s",
		w.MchID, w.MchCertificateSerialNumber, w.MchAPIv3Key)
}

// PayConfigInit 微信支付配置
func PayConfigInit() {
	WxPay.MchID = cast.ToString(Config.Get("pay.wx.mchID"))
	WxPay.MchCertificateSerialNumber = cast.ToString(Config.Get("pay.wx.mchCertificateSerialNumber"))
	WxPay.MchAPIv3Key = cast.ToString(Config.Get("pay.wx.mchAPIv3Key"))
	var err error
	WxPay.PrivateKey, err = utils.LoadPrivateKeyWithPath(cast.ToString(Config.Get("pay.wx.mchPrivateKeyPath")))
	if err != nil {
		//load merchant private key error =>加载商户私钥错误
		log.Fatal("load merchant private key error")
	}
	fmt.Println("wx_pay 微信支付配置初始化成功")
}
