package contextcheckMgr

import (
	"encoding/json"
	"fmt"
	"math/rand"
	"sort"
	"strconv"
	"time"

	"goutil/logUtil"
	"goutil/securityUtil"
	"goutil/webUtil"
)

var (
	//接口密钥Id
	msecretId string = "c98276c73c122eaa65163fe431cbf7d4"
	//接口密钥key
	msecretKey string = "3d2b39f824fa2f992494e17be500e303"
	//业务ID
	mbusinessId string = "9559ce74b5c5d24f6b124799a53c7431"
	//接口请求地址
	mapiurl string = "http://as.dun.163.com/v3/text/check"
	//版本号
	mversion string = "v3.1"
)

//参数设置
func SetPara(secretId, secretKey, businessId, apiurl, version string) {
	msecretId = secretId
	msecretKey = secretKey
	mbusinessId = businessId
	mapiurl = apiurl
	mversion = version
}

//content:用户发表内容
//account:玩家账号（用户唯一标识）
//nickname:角色名称
//extStr1:角色区服名称
//extStr2:UserId
//ip:用户IP地址，建议抄送，辅助机审策略精准调优
//extLon1:区服ID
//返回值 code: 0：通过， 1：嫌疑，2：不通过
//文本内容检测
func TextCheck(content, account, nickname, extStr1, extStr2, ip string, extLon1 int64) (code int, err error) {
	//构造请求参数
	postDataDict := make(map[string]string)
	postDataDict["secretId"] = msecretId
	postDataDict["businessId"] = mbusinessId
	postDataDict["timestamp"] = strconv.FormatInt(time.Now().Unix(), 10)
	postDataDict["nonce"] = strconv.FormatInt(rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(10000000000), 10)
	rawString := fmt.Sprintf("%v%v%v", account, postDataDict["timestamp"], content)
	postDataDict["dataId"] = securityUtil.Md5String(rawString, false)
	postDataDict["content"] = content
	postDataDict["version"] = mversion
	postDataDict["account"] = account
	postDataDict["nickname"] = nickname
	postDataDict["extLon1"] = strconv.FormatInt(extLon1, 10)
	// postDataDict["extLon2"] = extLon2
	postDataDict["extStr1"] = extStr1
	postDataDict["extStr2"] = extStr2
	postDataDict["ip"] = ip
	postDataDict["signature"] = getSignature(postDataDict)

	//请求url,请求头
	header := webUtil.GetFormHeader()
	transport := webUtil.NewTransport()
	transport.DisableKeepAlives = true
	transport = webUtil.GetTimeoutTransport(transport, 30)

	//请求接口
	statusCode, result, err := webUtil.PostMapData(mapiurl, postDataDict, header, transport)
	//定义错误信息
	var logMessage string

	//post请求错误
	if err != nil {
		logMessage = fmt.Sprintf("TextCheck:，错误信息为：%s", err.Error())
		logUtil.ErrorLog(logMessage)
		return
	}
	if statusCode != 200 {
		logMessage = fmt.Sprintf("TextCheck:%d is wrong", statusCode)
		logUtil.ErrorLog(logMessage)
		err = fmt.Errorf("TextCheck:%d is wrong", statusCode)
		return
	}

	//反序列化结果
	var checkResponseObj *ResultModel
	err = json.Unmarshal(result, &checkResponseObj)
	if err != nil {
		logMessage = fmt.Sprintf("json.Unmarshal(checkResponseObj),err：%s", err.Error())
		logUtil.ErrorLog(logMessage)
		return
	}

	//判断接口是否调用成功
	if checkResponseObj.Code != 200 {
		logMessage = fmt.Sprintf("TextCheck接口调用失败,ResultStatus %d", checkResponseObj.Code)
		err = fmt.Errorf("TextCheck接口调用失败，code：%d", checkResponseObj.Code)
		return
	}

	//返回检测结果
	code = checkResponseObj.Result.Action
	return
}

//生成签名字符串
func getSignature(postDataDict map[string]string) string {
	var paramStr string
	keys := make([]string, 0, len(postDataDict))
	for k := range postDataDict {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, key := range keys {
		paramStr += key + postDataDict[key]
	}
	paramStr += msecretKey

	return securityUtil.Md5String(paramStr, false)
}
