package controllers

import (
	"encoding/json"
	"eta/eta_mobile/cache"
	"eta/eta_mobile/models/system"
	"eta/eta_mobile/services/alarm_msg"
	"eta/eta_mobile/services/data"
	"fmt"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"

	"github.com/beego/beego/v2/server/web"

	"eta/eta_mobile/models"
	"eta/eta_mobile/utils"
)

type AfterHandle func(bodyByte []byte) error

// AfterHandlerUrlMap 结束后待处理的url
var AfterHandlerUrlMap = map[string][]AfterHandle{
	"/adminapi/datamanage/chart_info/save": {data.DeleteChartInfoDataRedis, data.DeleteChartClassifyRedis}, //图表保存接口
	//"/adminapi/datamanage/chart_info/detail": data.DeleteChartInfoDataRedis,
	"/adminapi/datamanage/chart_info/edit":       {data.DeleteChartInfoDataRedis, data.DeleteChartClassifyRedis}, //图表编辑接口
	"/adminapi/datamanage/chart_info/refresh":    {data.DeleteChartInfoDataRedis},                                //图表刷新接口
	"/adminapi/datamanage/chart_info/add":        {data.DeleteChartClassifyRedis},                                //图表添加接口
	"/adminapi/datamanage/chart_classify/delete": {data.DeleteChartInfoDataRedis, data.DeleteChartClassifyRedis}, //图表删除、图表分类删除
	"/adminapi/datamanage/chart_classify/add":    {data.DeleteChartClassifyRedis},                                //新增图表分类接口
	"/adminapi/datamanage/chart_classify/edit":   {data.DeleteChartClassifyRedis},                                //编辑图表分类接口
	"/adminapi/datamanage/chart_classify/move":   {data.DeleteChartClassifyRedis},                                //移动图表分类接口
	"/adminapi/datamanage/chart_info/move":       {data.DeleteChartClassifyRedis},                                //移动图表接口
	"/adminapi/datamanage/chart_info/copy":       {data.DeleteChartClassifyRedis},                                //图表另存为接口
}

type BaseAuthController struct {
	web.Controller
	SysUser *system.Admin
	Session *system.SysSession
	Lang    string `description:"当前语言类型，中文：zh；英文：en；默认：zh"`
}

func (this *BaseAuthController) Prepare() {
	//fmt.Println("enter prepare")
	method := this.Ctx.Input.Method()
	uri := this.Ctx.Input.URI()
	//fmt.Println("Url:", uri)
	if method != "HEAD" {
		if method == "POST" || method == "GET" {
			// 当前语言
			{
				lang := this.Ctx.Input.Header("Lang")
				if lang == "" {
					lang = utils.ZhLangVersion
				}
				this.Lang = lang
			}
			authorization := this.Ctx.Input.Header("authorization")
			if authorization == "" {
				authorization = this.Ctx.Input.Header("Authorization")
			}
			if authorization == "" {
				newAuthorization := this.GetString("authorization")
				if newAuthorization != `` {
					authorization = "authorization=" + newAuthorization
				} else {
					newAuthorization = this.GetString("Authorization")
					authorization = "authorization=" + newAuthorization
				}
			} else {
				if strings.Contains(authorization, ";") {
					authorization = strings.Replace(authorization, ";", "$", 1)
				}
			}
			if authorization == "" {
				strArr := strings.Split(uri, "?")
				//for k, v := range strArr {
				//	fmt.Println(k, v)
				//}
				if len(strArr) > 1 {
					authorization := strArr[1]
					authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
					//fmt.Println(authorization)
				}
			}
			if authorization == "" {
				this.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权！", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
				this.StopRun()
				return
			}
			authorizationArr := strings.Split(authorization, "$")
			if len(authorizationArr) <= 1 {
				this.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权！", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
				this.StopRun()
				return
			}
			tokenStr := authorizationArr[0]
			tokenArr := strings.Split(tokenStr, "=")
			token := tokenArr[1]

			accountStr := authorizationArr[1]
			accountArr := strings.Split(accountStr, "=")
			account := accountArr[1]
			//校验token是否合法
			// JWT校验Token和Account
			if !utils.CheckToken(account, token) {
				this.JSON(models.BaseResponse{Ret: 408, Msg: "鉴权失败，请重新登录！", ErrMsg: "登录失效，请重新登陆!,CheckToken Fail"}, false, false)
				this.StopRun()
				return
			}
			session, err := system.GetSysSessionByToken(token)
			if err != nil {
				if err.Error() == utils.ErrNoRow() {
					this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆！", ErrMsg: "Token 信息已变更:Token: " + token}, false, false)
					this.StopRun()
					return
				}
				this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常，请稍后重试!", ErrMsg: "获取用户信息异常，Eerr:" + err.Error()}, false, false)
				this.StopRun()
				return
			}
			if session == nil {
				this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常，请稍后重试!", ErrMsg: "sesson is empty "}, false, false)
				this.StopRun()
				return
			}
			if time.Now().After(session.ExpiredTime) {
				this.JSON(models.BaseResponse{Ret: 408, Msg: "请重新登录!", ErrMsg: "获取用户信息异常，Eerr:" + err.Error()}, false, false)
				this.StopRun()
				return
			}
			admin, err := system.GetSysUserById(session.SysUserId)
			if err != nil {
				if err.Error() == utils.ErrNoRow() {
					this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆！", ErrMsg: "获取admin 信息失败 " + strconv.Itoa(session.SysUserId)}, false, false)
					this.StopRun()
					return
				}
				this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常，请稍后重试!", ErrMsg: "获取admin信息异常，Eerr:" + err.Error()}, false, false)
				this.StopRun()
				return
			}
			if admin == nil {
				this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常，请稍后重试!", ErrMsg: "admin is empty "}, false, false)
				this.StopRun()
				return
			}
			//如果不是启用状态
			if admin.Enabled != 1 {
				this.JSON(models.BaseResponse{Ret: 408, Msg: "账户信息异常！", ErrMsg: "账户被禁用，不允许登陆!,CheckToken Fail"}, false, false)
				this.StopRun()
				return
			}

			// 如果当前登录态是不可信设备的，那么需要做过期校验
			if session.IsRemember != 1 {
				loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, session.Id)
				loginInfo, _ := utils.Rc.RedisString(loginKey)
				if loginInfo == `` {
					this.JSON(models.BaseResponse{Ret: 408, Msg: "超时未操作，系统自动退出！", ErrMsg: "超时未操作，系统自动退出！"}, false, false)
					this.StopRun()
					return
				}

				if loginInfo != "1" {
					msg := `该账号于` + admin.LastLoginTime + "在其他网络登录。此客户端已退出登录。"
					this.JSON(models.BaseResponse{Ret: 408, Msg: msg, ErrMsg: msg}, false, false)
					this.StopRun()
					return
				}
				utils.Rc.Put(loginKey, "1", utils.LoginCacheTime*time.Minute)
				// 不信任名单也同步更新
				noTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN_NO_TRUST, admin.AdminId)
				utils.Rc.Put(noTrustLoginKey, session.Id, utils.LoginCacheTime*time.Minute)
			}

			admin.RoleTypeCode = GetSysUserRoleTypeCode(admin.RoleTypeCode)
			this.SysUser = admin
			this.Session = session
		} else {
			this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常，请联系客服!", ErrMsg: "POST之外的请求，暂不支持"}, false, false)
			this.StopRun()
			return
		}
	}
}

func (c *BaseAuthController) ServeJSON(encoding ...bool) {
	// 方法处理完后，需要后置处理的业务逻辑
	if handlerList, ok := AfterHandlerUrlMap[c.Ctx.Request.URL.Path]; ok {
		for _, handler := range handlerList {
			handler(c.Ctx.Input.RequestBody)
		}
	}

	var (
		hasIndent   = false
		hasEncoding = false
	)
	if web.BConfig.RunMode == web.PROD {
		hasIndent = false
	}
	if len(encoding) > 0 && encoding[0] == true {
		hasEncoding = true
	}
	if c.Data["json"] == nil {
		//go utils.SendEmail("异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
		body := "接口:" + "URI:" + c.Ctx.Input.URI() + ";无返回值"
		go alarm_msg.SendAlarmMsg(body, 1)
		return
	}
	baseRes := c.Data["json"].(*models.BaseResponse)
	if baseRes != nil && baseRes.Ret != 408 {
		body, _ := json.Marshal(baseRes)
		var requestBody string
		method := c.Ctx.Input.Method()
		if method == "GET" {
			requestBody = c.Ctx.Request.RequestURI
		} else {
			//requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
			requestBody = string(c.Ctx.Input.RequestBody)
		}
		if baseRes.Ret != 200 && baseRes.IsSendEmail {
			//go utils.SendEmail(utils.APPNAME+"【"+utils.RunMode+"】"+"失败提醒", "URI:"+c.Ctx.Input.URI()+"<br/> "+"Params"+requestBody+" <br/>"+"ErrMsg:"+baseRes.ErrMsg+";<br/>Msg:"+baseRes.Msg+";<br/> Body:"+string(body)+"<br/>"+c.SysUser.RealName, utils.EmailSendToUsers)
			body := "URI:" + c.Ctx.Input.URI() + "<br/> " + "Params" + requestBody + " <br/>" + "ErrMsg:" + baseRes.ErrMsg + ";<br/>Msg:" + baseRes.Msg + ";<br/> Body:" + string(body) + "<br/>" + c.SysUser.RealName
			go alarm_msg.SendAlarmMsg(body, 1)
		}
		if baseRes.IsAddLog && c.SysUser != nil {
			go cache.RecordNewLogs(c.SysUser.AdminId, requestBody, string(body), c.SysUser.RealName, c.Ctx.Input.IP(), c.Ctx.Input.URI())
		}
	}

	c.JSON(c.Data["json"], hasIndent, hasEncoding)
}

func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
	c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
	desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
	c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
	var content []byte
	var err error
	if hasIndent {
		content, err = json.MarshalIndent(data, "", "  ")
	} else {
		content, err = json.Marshal(data)
	}
	if err != nil {
		http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
		return err
	}
	ip := c.Ctx.Input.IP()
	requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
	if err != nil {
		requestBody = string(c.Ctx.Input.RequestBody)
	}
	if requestBody == "" {
		requestBody = c.Ctx.Input.URI()
	}
	c.logUri(content, requestBody, ip)
	if coding {
		content = []byte(utils.StringsToJSON(string(content)))
	}

	// 如果不是debug分支的话，那么需要加密返回
	if utils.RunMode != "debug" {
		content = utils.DesBase64Encrypt(content, utils.DesKey)
		// get请求时，不加双引号就获取不到数据，不知道什么原因，所以还是在前后加上双引号吧
		content = []byte(`"` + string(content) + `"`)
	}
	if coding {
		content = []byte(utils.StringsToJSON(string(content)))
	}

	return c.Ctx.Output.Body(content)
}

func GetSysUserRoleTypeCode(roleTypeCode string) string {
	if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER ||
		roleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT {
		return utils.ROLE_TYPE_CODE_FICC_SELLER
	}

	if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER ||
		roleTypeCode == utils.ROLE_TYPE_CODE_RAI_DEPARTMENT {
		return utils.ROLE_TYPE_CODE_RAI_SELLER
	}

	if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
		return utils.ROLE_TYPE_CODE_RAI_GROUP
	}

	if roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
		return utils.ROLE_TYPE_CODE_ADMIN
	}
	if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
		return utils.ROLE_TYPE_CODE_FICC_ADMIN
	}
	if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM {
		return utils.ROLE_TYPE_CODE_FICC_TEAM
	}
	if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
		return utils.ROLE_TYPE_CODE_FICC_GROUP
	}
	if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
		return utils.ROLE_TYPE_CODE_RAI_ADMIN
	}
	if roleTypeCode == utils.ROLE_TYPE_CODE_RESEARCHR {
		return utils.ROLE_TYPE_CODE_FICC_RESEARCHR
	}
	if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_RESEARCHR {
		return utils.ROLE_TYPE_CODE_FICC_RESEARCHR
	}
	if roleTypeCode == utils.ROLE_TYPE_CODE_RAI_RESEARCHR {
		return utils.ROLE_TYPE_CODE_RAI_RESEARCHR
	}
	//合规
	if roleTypeCode == utils.ROLE_TYPE_CODE_COMPLIANCE {
		return utils.ROLE_TYPE_CODE_COMPLIANCE
	}
	//财务
	if roleTypeCode == utils.ROLE_TYPE_CODE_FINANCE {
		return utils.ROLE_TYPE_CODE_FINANCE
	}
	return ""
}

func (c *BaseAuthController) logUri(respContent []byte, requestBody, ip string) {
	authorization := ""
	method := c.Ctx.Input.Method()
	uri := c.Ctx.Input.URI()
	//fmt.Println("Url:", uri)
	if method != "HEAD" {
		if method == "POST" || method == "GET" {
			authorization = c.Ctx.Input.Header("authorization")
			if authorization == "" {
				authorization = c.Ctx.Input.Header("Authorization")
			}
			if authorization == "" {
				newAuthorization := c.GetString("authorization")
				if newAuthorization != `` {
					authorization = "authorization=" + newAuthorization
				} else {
					newAuthorization = c.GetString("Authorization")
					authorization = "authorization=" + newAuthorization
				}
			} else {
				if strings.Contains(authorization, ";") {
					authorization = strings.Replace(authorization, ";", "$", 1)
				}
			}
			if authorization == "" {
				strArr := strings.Split(uri, "?")
				//for k, v := range strArr {
				//	fmt.Println(k, v)
				//}
				if len(strArr) > 1 {
					authorization = strArr[1]
					authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
					//fmt.Println(authorization)
				}
			}
		}
	}

	utils.ApiLog.Info("uri:%s, authorization:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), authorization, requestBody, respContent, ip)
	return
}
