package controllers

import (
	"crypto/sha1"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/dingdingapi"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/jxutils/ddmsg"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"time"

	"git.rosy.net.cn/jx-callback/globals/api"
	"github.com/astaxie/beego/server/web"
)

type DDAPIController struct {
	web.Controller
}

type DDAPI struct {
	Ticket    string
	ExpiresIn time.Time
}

var (
	ddapi *DDAPI
)

func init() {
	ddapi = &DDAPI{}
}

// @Title 得到门店用户信息
// @Description 得到门店用户信息
// @Param	token			header		string	true	"认证token"
// @Param	url				query		string	true	"当前网页的URL，不包含#及其后面部分"
// @Param	nonceStr		query		string	true	"随机串，自己定义"
// @Param	timeStamp		query		string	true	"时间戳"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /Sign [get]
func (c *DDAPIController) Sign() {
	c.callSign(func(params *tDdapiSignParams) (retVal interface{}, errCode string, err error) {
		if ddapi.Ticket == "" || time.Now().Sub(ddapi.ExpiresIn) >= -5*time.Minute {
			expiresIn, ticket, err2 := api.DingDingAPI.GetJSAPITicket("")
			if err = err2; err == nil {
				ddapi.Ticket = ticket
				ddapi.ExpiresIn = time.Now().Add(time.Duration(expiresIn) * time.Second)
			}
		}
		if err == nil {
			str := "jsapi_ticket=" + ddapi.Ticket +
				"&noncestr=" + params.NonceStr + "&timestamp=" + params.TimeStamp + "&url=" + params.Url
			retVal = fmt.Sprintf("%x", sha1.Sum([]byte(str)))
		}
		return retVal, "", err
	})
}

// @Title 发送钉钉消息
// @Description 发送钉钉消息
// @Param	token			header		string	true	"认证token"
// @Param	title			query		string	true	"消息标题"
// @Param	content			query		string	true	"消息内容"
// @Param	mobiles			query		string	true	"发送给谁,电话列表"
// @Success 200 {object} controllers.CallResult
// @Failure 200 {object} controllers.CallResult
// @router /SendDDmsgToUser [post]
func (c *DDAPIController) SendDDmsgToUser() {
	c.callSendDDmsgToUser(func(params *tDdapiSendDDmsgToUserParams) (retVal interface{}, errCode string, err error) {
		var (
			mobiles   []string
			mobileMap = make(map[string]string)
		)
		jxutils.Strings2Objs(params.Mobiles, &mobiles)
		for _, v := range mobiles {
			mobileMap[v] = v
		}
		for _, mobile := range mobileMap {
			if user, _ := dao.GetUserByID(dao.GetDB(), "mobile", mobile); user != nil {
				err = ddmsg.SendUserMessage(dingdingapi.MsgTyeText, user.UserID, params.Title, params.Content)
			}
		}
		return retVal, "", err
	})
}
