package controllers

import (
	call "git.rosy.net.cn/baseapi/utils/weworkapi_golang-master"
	"git.rosy.net.cn/jx-callback/business/enterprise"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
	"github.com/astaxie/beego/server/web"
	"io/ioutil"
	"net/http"
	"strings"
)

type EnterpriseController struct {
	web.Controller
}


// EnterpriseCallback 在发生授权、通讯录变更、ticket变化等事件时，企业微信服务器会向应用的“指令回调URL”推送相应的事件消息。
// 消息结构体将使用创建应用时的EncodingAESKey进行加密（特别注意, 在第三方回调事件中使用加解密算法，receiveid的内容为suiteid）
// ，请参考接收消息解析数据包。
func (e *EnterpriseController) EnterpriseCallback() {
	r := e.Ctx.Request
	switch e.Ctx.Request.Method {
	case http.MethodPost:
		httpstr := r.URL.RawQuery
		start := strings.Index(httpstr, "msg_signature=")
		start += len("msg_signature=")
		var msg_signature string
		next := call.GetString(httpstr, "&timestamp=", start, &msg_signature)
		var timestamp string
		next = call.GetString(httpstr, "&nonce=", next, &timestamp)
		nonce := httpstr[next:len(httpstr)]
		body, _ := ioutil.ReadAll(r.Body)

		wxcpt := call.NewWXBizMsgCrypt(call.Token, call.EncodingAeskey, call.ReceiverId, call.JsonType)
		msg, err_ := wxcpt.DecryptMsg(msg_signature, timestamp, nonce, body)
		if err_ != nil {
			e.Abort("404")
			return
		}

		//var msgContent call.MsgContent
		//err := json.Unmarshal(msg, &msgContent)
		//if nil != err {
		//	globals.SugarLogger.Debug("Unmarshal fail", err)
		//} else {
		//}
		//
		//globals.SugarLogger.Debug(msgContent, err)
		//ToUsername := msgContent.ToUsername
		//msgContent.ToUsername = msgContent.FromUsername
		//msgContent.FromUsername = ToUsername
		//replayJson, err := json.Marshal(&msgContent)
		//
		//encryptMsg, cryptErr := wxcpt.EncryptMsg(string(replayJson), timestamp, nonce)
		//if nil != cryptErr {
		//	globals.SugarLogger.Debug("DecryptMsg fail", cryptErr)
		//}
		//
		if strings.Contains(string(msg), "SuiteTicket") {
			data, err := api.EnterpriseChatHeadApi.GetEnterpriseMsg(msg)
			if err != nil {
				globals.SugarLogger.Debug("Unmarshal SuiteTicket err : ", err)
			} else {
				if err := enterprise.UpdateEnterpriseSuite(data); err != nil {
					globals.SugarLogger.Debug("UpdateEnterpriseSuite err :", err)
				}
			}
		}

		e.Ctx.ResponseWriter.Write([]byte("success"))
	case http.MethodGet:
		call.VerifyURL(e.Ctx.ResponseWriter, e.Ctx.Request)
	default:
		e.Abort("404")
	}
}
