package mobile

import (
	"errors"
	"fmt"

	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/auth2"
	"git.rosy.net.cn/jx-callback/business/auth2/authprovider"
	"git.rosy.net.cn/jx-callback/globals"
	aliyunsmsclient "github.com/KenmyZhang/aliyun-communicate"
)

const (
	AuthType       = auth2.AuthTypeMobile
	TestVerifyCode = "123456"
)

var (
	warningMap = map[string]int{
		"isv.AMOUNT_NOT_ENOUGH": 1,
		"isv.ACCOUNT_ABNORMAL":  1,
		"isv.OUT_OF_SERVICE":    1,
		"isv.DAY_LIMIT_CONTROL": 1,
	}
)

var (
	ErrVerifyCodeIsWrong = errors.New("验证码错")
)

type Auther struct {
	authprovider.DefAuther
}

var (
	AutherObj *Auther
)

func init() {
	AutherObj = new(Auther)
	auth2.RegisterAuther(AuthType, AutherObj)
}

// 特殊接口
func (a *Auther) SendVerifyCode(mobileNumber string) (verifyCode string, err error) {
	verifyCode = a.GenerateVerifyCode(mobileNumber)
	smsClient := aliyunsmsclient.New("http://dysmsapi.aliyuncs.com/")
	response, err := smsClient.Execute(globals.AliKey, globals.AliSecret, mobileNumber, globals.SMSSignName, globals.SMSMobileVerifyTemplate, string(utils.MustMarshal(map[string]interface{}{
		"code": verifyCode,
	})))
	a.SaveVerifyCode(mobileNumber, verifyCode)
	if err == nil && response.Code == aliyunsmsclient.ResponseCodeOk {
		// a.SaveVerifyCode(mobileNumber, verifyCode)
	} else {
		if err == nil {
			if warningMap[response.Code] == 1 {
				globals.SugarLogger.Warnf("SendVerifyCode mobileNumber:%s failed with response:%s", mobileNumber, utils.Format4Output(response, false))
			} else {
				globals.SugarLogger.Infof("SendVerifyCode mobileNumber:%s failed with response:%s", mobileNumber, utils.Format4Output(response, false))
			}
			err = fmt.Errorf("发送短信出错:%s", response.Message)
		} else {
			globals.SugarLogger.Warnf("SendVerifyCode mobileNumber:%s failed with error:%v", mobileNumber, err)
		}
	}
	return verifyCode, err
}

func (a *Auther) VerifySecret(mobileNumber, code string) (authBindEx *auth2.AuthBindEx, err error) {
	err = ErrVerifyCodeIsWrong
	if (code == auth2.InternalAuthSecret ||
		auth2.TestMobileMap[mobileNumber] == 1 && code == TestVerifyCode) ||
		a.VerifyCode(mobileNumber, code) {
		err = nil
	}
	return nil, err
}

// 此函数为空
func (a *Auther) AddAuthBind(authBindEx *auth2.AuthBindEx, userName string) (err error) {
	return err
}

// 此函数为空
func (a *Auther) UnbindAuth(userID, authType, authTypeID, userName string) (err error) {
	return err
}
