package hdl

import (
	implement2 "applet/app/db/implement"
	"applet/app/e"
	"applet/app/lib/validate"
	"applet/app/md"
	"applet/app/svc"
	"code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/sms"
	"code.fnuoos.com/zhimeng/model.git/src/implement"
	"github.com/gin-gonic/gin"
	"github.com/tidwall/gjson"
)

// Sms
// @Summary    	 短信发送
// @Tags         短信
// @Description  短信-短信发送
// @param Authorization header string false "验证参数Bearer和token空格拼接"
// @Accept       json
// @Produce      json
// @Param        args 	body      md.SmsReq   true   "请求参数"
// @Success      200   {string}		   "success"
// @Failure      400   {object}   md.Response              "具体错误"
// @Router       /api/sms [POST]
func Sms(c *gin.Context) {
	var args md.SmsReq
	err := c.ShouldBindJSON(&args)
	if err != nil {
		err = validate.HandleValidateErr(err)
		err1 := err.(e.E)
		e.OutErr(c, err1.Code, err1.Error())
		return
	}
	if args.Type == "fast_login" {
		NewAdminDb := implement.NewAdminDb(svc.MasterDb(c))
		admin, _ := NewAdminDb.GetAdminByUserName(args.Phone)
		if admin == nil {
			e.OutErr(c, 400, e.NewErr(400, "账号未注册"))
			return
		}
	}
	if args.Type == "update_password" {
		admin, _ := svc.CheckUser(c)
		if admin == nil {
			e.OutErr(c, 400, e.NewErr(400, "账号未注册"))
			return
		}
		args.Phone = admin.Username
	}
	NewSysCfgDb := implement2.NewSysCfgDb(svc.MasterDb(c), c.GetString("mid"))
	key := NewSysCfgDb.SysCfgGetWithDb("mob_app_key")
	if key == "" {
		e.OutErr(c, 400, e.NewErr(400, "appkey不存在"))
		return
	}
	where := map[string]interface{}{
		"appkey": key,
		"zone":   "86",
		"phone":  args.Phone,
	}
	send, err := sms.SmsMobApiSend(where)
	if err != nil {
		e.OutErr(c, 400, err.Error())
		return
	}
	status := gjson.Get(send, "status").Int()
	msg := gjson.Get(send, "error").String()
	if status == 471 {
		e.OutErr(c, 400, e.NewErr(400, "发送的ip不在白名单中"))
		return
	}
	if status == 406 {
		e.OutErr(c, 400, e.NewErr(400, "appkey不存在"))
		return
	}
	if status != 200 {
		e.OutErr(c, 400, e.NewErr(400, msg))
		return
	}
	e.OutSuc(c, "success", nil)
	return
}