package conf

import (
	"fmt"
	"os"

	"pay/log"

	"github.com/spf13/viper"
)

const AppName = "sku3d"

type SinglePayParams struct {
	Name   string
	AliPay struct {
		AppId                string `json:"appId"`
		PrivateKey           string `json:"privateKey"`
		IsProd               bool   `json:"isProd"`
		ReturnUrl            string `json:"returnUrl"`
		NotifyUrl            string `json:"notifyUrl"`
		AppCertPath          string `json:"appCertPath"`
		AliPayRootCertPath   string `json:"aliPayRootCertPath"`
		AliPayPublicCertPath string `json:"aliPayPublicCertPath"`
	}

	WechatPay struct {
		AppId      string `json:"appId"`
		MchId      string `json:"mchId"`
		SerialNo   string `json:"serialNo"`
		ApiV3Key   string `json:"apiV3Key"`
		PrivateKey string `json:"privateKey"`
		NotifyUrl  string `json:"notifyUrl"`
	}
}

type MultiPayParam struct {
	Name   string
	AliPay struct {
		AppId                string `json:"appId"`
		SellerId             string `json:"sellerId"`
		AppAuthToken         string `json:"appAuthToken"`
		PrivateKey           string `json:"privateKey"`
		IsProd               bool   `json:"isProd"`
		ReturnUrl            string `json:"returnUrl"`
		NotifyUrl            string `json:"notifyUrl"`
		AppCertPath          string `json:"appCertPath"`
		AliPayRootCertPath   string `json:"aliPayRootCertPath"`
		AliPayPublicCertPath string `json:"aliPayPublicCertPath"`
	}

	WechatPay struct {
		AppId      string `json:"appId"`
		MchId      string `json:"mchId"`
		SubMchId   string `json:"subMchid"`
		SerialNo   string `json:"serialNo"`
		ApiV3Key   string `json:"apiV3Key"`
		PrivateKey string `json:"privateKey"`
		NotifyUrl  string `json:"notifyUrl"`
	}
}

type AppConf struct {
	Port     int32
	Name     string
	ShopName string
	Version  string

	Ssl     bool
	SslCert string
	SslKey  string

	Jwt struct {
		Realm       string
		Key         string
		TimeoutHour int
	}

	Log struct {
		FileName    string
		Level       int32
		ServiceName string
	}

	Debug struct {
		UserId    string
		UserPhone string
		UserRole  string
	}

	Nats struct {
		Url               string
		MaxReconnect      int
		ReconnDelaySecond int
	}

	Single []*SinglePayParams //企业收款
	Multi  []*MultiPayParam   //替其他企业收款
}

func LoadConfFile(filepath string) (*AppConf, error) {
	file, err := os.Open(filepath)
	if err != nil {
		log.Errorf("can not open file:%s", filepath)
		return nil, err
	}
	v := viper.New()
	v.SetConfigType("yaml")
	err = v.ReadConfig(file)
	if err != nil {
		return nil, err
	}
	c := new(AppConf)
	err = v.Unmarshal(c)
	return c, err
}

func NewAppConf(filePath string) (*AppConf, error) {

	c, err := LoadConfFile(filePath)
	if err != nil {
		return c, err
	}
	//初始化log
	_ = log.NewLoggerSugar(c.Log.ServiceName, c.Log.FileName, c.Log.Level)

	nats := os.Getenv("NATS")
	if len(nats) > 0 {
		c.Nats.Url = nats
	}
	fmt.Println("pay Env NATS=>", nats)
	fmt.Println("pay NATS ADDR => ", c.Nats.Url)
	AppConfig = c

	return c, nil
}

var AppConfig *AppConf = nil
