package config

import (
	"database/sql"
	"fmt"
	"regexp"
	"runtime"
	"strings"

	"git.jiaxianghudong.com/go/logs"

	"gopkg.in/yaml.v2"

	"git.jiaxianghudong.com/go/utils"
)

var ostype = runtime.GOOS
var (
	DBHandle *sql.DB
	conf     ConfAPI
	Lottert  LottertConfig
)

type LottertConfig struct {
	LottertData map[int]interface{} `yaml:"data"`
}

//type Lotteryconfiginfo struct {
//	Id              int `yaml:"id"`
//	Dataidint       int `yaml:"data_idint"`
//	Countint        int `yaml:"countint"`
//	Weightint       int `yaml:"weightint"`
//	Typeint         int `yaml:"typeint"`
//	ConsumeValueint int `yaml:"consume_valueint"`
//	Frozenint       int `yaml:"frozenint"`
//	Probabilityint  int `yaml:"probabilityint"`
//}

type ConfAPI struct {
	Listen       int          `yaml:"listen"`  // 监听端口
	RunMode      string       `yaml:"runmode"` // 服务运行模式
	Gsdk         EntityGsdk   `yaml:"gsdk"`
	Logs         EntityLogs   `yaml:"logs"` // 日志
	RedisFifteen EntityRedis  `yaml:"redis_fifteen"`
	Redis0       EntityRedis  `yaml:"redis0"`
	Redis4       EntityRedis  `yaml:"redis4"`
	Redis5       EntityRedis  `yaml:"redis5"`
	Redis7       EntityRedis  `yaml:"redis7"`
	Redis8       EntityRedis  `yaml:"redis8"`
	MysqlMain    EntityMysql  `yaml:"mysql_main"`
	MysqlLog     EntityMysql  `yaml:"mysql_log"`
	MysqlExt     EntityMysql  `yaml:"mysql_ext"`
	MysqlAgent   EntityMysql  `yaml:"mysql_agent"`
	Brand        EntityBrand  `yaml:"brand"`
	Ymrt         EntityYmrt   `yaml:"ymrt"`
	AliOss       EntityAliOss `yaml:"alioss"`
}

type EntityLogs struct {
	Dir      string `yaml:"dir"`
	File     string `yaml:"file"`
	Level    int    `yaml:"level"`
	SaveFile bool   `yaml:"savefile"`
}

type EntityMysql struct {
	Addr     string `yaml:"addr"`
	UserName string `yaml:"user"`
	Password string `yaml:"password"`
	Database string `yaml:"db"`
	Charset  string `yaml:"charset"`
	MaxOpen  int    `yaml:"max_open"`
	MaxIdle  int    `yaml:"max_idle"`
}

type EntityRedis struct {
	Addr     string `yaml:"addr"`
	Pwd      string `yaml:"password"`
	DB       int    `yaml:"db"`
	PoolSize int    `yaml:"poolsize"`
}

// gsdk 服务配置
type EntityGsdk struct {
	IP      string `yaml:"ip"`
	Port    int    `yaml:"port"`
	AppID   string `yaml:"app_id"`   // 应用标识
	AuthKey string `yaml:"auth_key"` // 授权密钥
}
type EntityBrand struct {
	ID       int    `yaml:"id"`
	Tag      string `yaml:"tag"`
	Domain   string `yaml:"domain"`
	Name     string `yaml:"name"`
	Userfrom int    `yaml:"userfrom"`
	Client   int    `yaml:"client"`
	Tel      string `yaml:"tel"`
}
type EntityYmrt struct {
	Cdkey string   `yaml:"cdkey"`
	Pwd   string   `yaml:"pwd"`
	Data  Ymrtdata `yaml:"data"`
}
type Ymrtdata struct {
	Ename    string `yaml:"ename"`
	Linkman  string `yaml:"linkman"`
	Phonenum string `yaml:"phonenum"`
	Mobile   string `yaml:"mobile"`
	Email    string `yaml:"email"`
	Fax      string `yaml:"fax"`
	Address  string `yaml:"address"`
	Postcode string `yaml:"postcode"`
}

//
type EntityAliOss struct {
	Endpoint        string `yaml:"endpoint"`
	AccessKeyID     string `yaml:"access_key_id"`
	AccessKeySecret string `yaml:"access_key_secret"`
	Bucket          string `yaml:"bucket"`
	BucketUrl       string `yaml:"bucket_url"`
	Domain          string `yaml:"domain"`
	DomainUrl       string `yaml:"domain_url"`
	HttpHead        string `yaml:"http_head"`
}

func Init() {
	fmt.Println("--init config start")

	// 初始化日志
	str := utils.ReadConfFile("wapi.yaml")
	/* 替换注释 */
	reg := regexp.MustCompile(`\/\*[^(\*\/)]*\*\/`)
	str = reg.ReplaceAllString(str, "")

	/* 解析yaml */
	err := yaml.Unmarshal([]byte(str), &conf)

	//解析lottery配置
	lottery := utils.ReadConfFile("lottery.yaml")
	lotterystr := reg.ReplaceAllString(lottery, "")
	lotterterr := yaml.Unmarshal([]byte(lotterystr), &Lottert)
	logs.Debug(lotterterr)

	/* 配制全局变量 */
	if nil == err {
		// host config
		fmt.Println(fmt.Sprintf(" Listen:%d", conf.Listen))
		fmt.Println(fmt.Sprintf(" RunMode:%s", conf.RunMode))
		// gsdk
		fmt.Println(fmt.Sprintf(" Gsdk:{IP:%s\tPort:%d\tAppID:%s\tAppKey:%s}",
			conf.Gsdk.IP, conf.Gsdk.Port, conf.Gsdk.AppID, conf.Gsdk.AuthKey))
		// logs
		fmt.Println(fmt.Sprintf(" LOG:{Dir:%s\tFile:%s\tLevel:%d\tSaveFile:%t}",
			conf.Logs.Dir, conf.Logs.File, conf.Logs.Level, conf.Logs.SaveFile))
		// mysql
		fmt.Println(fmt.Sprintf(" Mysql_main:{Addr:%s\tUserName:%s\tPwd:%s\tDB:%s\tMaxOpen:%d\tMaxIdle:%d}}",
			conf.MysqlMain.Addr, conf.MysqlMain.UserName, conf.MysqlMain.Password,
			conf.MysqlMain.Database, conf.MysqlMain.MaxOpen, conf.MysqlMain.MaxIdle))

		fmt.Println(fmt.Sprintf(" Mysql_ext:{Addr:%s\tUserName:%s\tPwd:%s\tDB:%s\tMaxOpen:%d\tMaxIdle:%d}}",
			conf.MysqlExt.Addr, conf.MysqlExt.UserName, conf.MysqlExt.Password,
			conf.MysqlExt.Database, conf.MysqlExt.MaxOpen, conf.MysqlExt.MaxIdle))

		fmt.Println(fmt.Sprintf(" Mysql_log:{Addr:%s\tUserName:%s\tPwd:%s\tDB:%s\tMaxOpen:%d\tMaxIdle:%d}}",
			conf.MysqlLog.Addr, conf.MysqlLog.UserName, conf.MysqlLog.Password,
			conf.MysqlLog.Database, conf.MysqlLog.MaxOpen, conf.MysqlLog.MaxIdle))

		fmt.Println(fmt.Sprintf(" Mysql_agent:{Addr:%s\tUserName:%s\tPwd:%s\tDB:%s\tMaxOpen:%d\tMaxIdle:%d}}",
			conf.MysqlAgent.Addr, conf.MysqlLog.UserName, conf.MysqlLog.Password,
			conf.MysqlAgent.Database, conf.MysqlLog.MaxOpen, conf.MysqlLog.MaxIdle))

		// redis

		fmt.Println(fmt.Sprintf(" RedisFifteen:{Addr:%s\tPwd:%s\tDB:%d\t:PoolSize:%d\t}",
			conf.RedisFifteen.Addr, conf.RedisFifteen.Pwd, conf.RedisFifteen.DB, conf.RedisFifteen.PoolSize))
		fmt.Println("--init config end")

	} else {
		/* 打印日志 */
		fmt.Println("--init config err :", err.Error())
	}
}

func GetListen() int {
	return conf.Listen
}

func GetGsdk() *EntityGsdk {
	return &conf.Gsdk
}

// 获取日志配置
func GetLogs() *EntityLogs {
	if GetRunMode() == "debug" {
		conf.Logs.Dir = "../log"
		if ostype == "windows" {
			conf.Logs.Dir = "..\\log"
		}
	}
	return &conf.Logs
}

// 获取运行模式
func GetRunMode() string {
	return strings.TrimSpace(strings.ToLower(conf.RunMode))
}

func GetRedisFifteen() EntityRedis {
	return conf.RedisFifteen
}
func GetRedis0() EntityRedis {
	return conf.Redis0
}
func GetRedis4() EntityRedis {
	return conf.Redis4
}
func GetRedis5() EntityRedis {
	return conf.Redis5
}
func GetRedis7() EntityRedis {
	return conf.Redis7
}
func GetRedis8() EntityRedis {
	return conf.Redis8
}

func GetRedis15() EntityRedis {
	return conf.Redis4
}
func GetLottertConfig() LottertConfig {
	return Lottert
}

// GetMainDBConf 获取MYSQL
func GetMainDBConf() EntityMysql {
	return conf.MysqlMain
}

// GetLogDBConf Log
func GetLogDBConf() EntityMysql {
	return conf.MysqlLog
}

// GetExtDBConf Ext
func GetExtDBConf() EntityMysql {
	return conf.MysqlExt
}

func GetAgentDBConf() EntityMysql {
	return conf.MysqlAgent
}

//
func GetBrand() *EntityBrand {
	return &conf.Brand
}
func Getymrt() *EntityYmrt {
	return &conf.Ymrt
}

// GetAliOss 获取Redis对象
func GetAliOss() *EntityAliOss {
	return &conf.AliOss
}
func GetLottery() *EntityBrand {
	return &conf.Brand
}
