package controllers

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

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

	"eta/eta_api/models"
	"eta/eta_api/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/multiple_graph/chart/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},                                //图表另存为接口
}

var AdminOperateRecordMap = map[string]string{
	"/adminapi/pptv2/saveLog":                                        "/adminapi/pptv2/saveLog",
	"/adminapi/report/saveReportContent":                             "/adminapi/report/saveReportContent",
	"/adminapi/datamanage/chart_info/common/detail/from_unique_code": "/adminapi/datamanage/chart_info/common/detail/from_unique_code",
	"/adminapi/english_report/saveReportContent":                     "/adminapi/english_report/saveReportContent",
	"/adminapi/custom/message/listV2":                                "/adminapi/custom/message/listV2",
	"/adminapi/sysuser/check_pwd":                                    "/adminapi/sysuser/check_pwd",
	"/adminapi/system/menu/list":                                     "/adminapi/system/menu/list",
}

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

func (c *BaseAuthController) Prepare() {
	//fmt.Println("enter prepare")
	method := c.Ctx.Input.Method()
	uri := c.Ctx.Input.URI()
	//fmt.Println("Url:", uri)
	if method != "HEAD" {
		if method == "POST" || method == "GET" {
			// 当前语言
			{
				lang := c.Ctx.Input.Header("Lang")
				if lang == "" {
					lang = utils.ZhLangVersion
				}
				c.Lang = lang
			}

			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)
				}
			}
			if authorization == "" {
				c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权！", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
				c.StopRun()
				return
			}
			//authorizationArr := strings.Split(authorization, "$")
			//if len(authorizationArr) <= 1 {
			//	c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权！", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
			//	c.StopRun()
			//	return
			//}
			tokenStr := authorization
			tokenArr := strings.Split(tokenStr, "=")
			token := tokenArr[1]

			//accountStr := authorizationArr[1]
			//accountArr := strings.Split(accountStr, "=")
			//account := accountArr[1]

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

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

				if loginInfo != "1" {
					msg := `该账号于` + admin.LastLoginTime + "在其他网络登录。此客户端已退出登录。"
					c.JSON(models.BaseResponse{Ret: 408, Msg: msg, ErrMsg: msg}, false, false)
					c.StopRun()
					return
				}

				// 如果是ETA体验版-更新活跃时长/更新登录时长的接口请求, 则不更新Token时长
				if uri != `/adminapi/eta_trial/user/login_duration` && uri != `/adminapi/eta_trial/user/active` {
					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)
			c.SysUser = admin
			c.Session = session

			//接口权限校验
			roleId := admin.RoleId
			list, e := system.GetMenuButtonApisByRoleId(roleId)
			if e != nil {
				c.JSON(models.BaseResponse{Ret: 403, Msg: "获取接口权限出错！", ErrMsg: "获取接口权限出错！"}, false, false)
				c.StopRun()
				return
			}
			var api string
			for _, v := range list {
				api += v.Api + "&"
			}
			//处理uri请求，去除前缀和参数
			api = strings.TrimRight(api, "&")
			uri = strings.Replace(uri, "/adminapi", "", 1)
			uris := strings.Split(uri, "?")
			uri = uris[0]
			//fmt.Println("uri:", uri)
			apis := strings.Split(api, "&")
			apiMap := make(map[string]bool, 0)
			for _, s := range apis {
				apiMap[s] = true
			}
			if !apiMap[uri] {
				c.JSON(models.BaseResponse{Ret: 403, Msg: "无权访问！", ErrMsg: "无权访问！"}, false, false)
				c.StopRun()
				return
			}
		} else {
			c.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常，请联系客服!", ErrMsg: "POST之外的请求，暂不支持"}, false, false)
			c.StopRun()
			return
		}
	}
}

func (c *BaseAuthController) ServeJSON(encoding ...bool) {
	urlPath := c.Ctx.Request.URL.Path
	// 方法处理完后，需要后置处理的业务逻辑
	if handlerList, ok := AfterHandlerUrlMap[urlPath]; 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())
		}
	}

	if utils.ViperConfig != nil {
		if c.Lang == utils.EnLangVersion {
			msg := c.Data["json"].(*models.BaseResponse).Msg
			if utils.ViperConfig.InConfig(msg) {
				c.Data["json"].(*models.BaseResponse).Msg = utils.ViperConfig.GetString(msg)
			}
		}
	}


	//新增uuid记录
	{
		if _, ok := AdminOperateRecordMap[urlPath]; !ok && !strings.Contains(urlPath, "cygx") {
			var adminId int
			var realName, params, ip, uriStr string
			ip = c.Ctx.Input.IP()
			if c.SysUser != nil {
				adminId = c.SysUser.AdminId
				realName = c.SysUser.RealName
			}
			uuid := c.Ctx.Input.Header("Uuid")
			userAgent := c.Ctx.Input.Header("User-Agent")
			uri := c.Ctx.Input.URI()
			uriStr, _ = url.PathUnescape(uri)
			if uriStr != "" {
				uri = uriStr
			}
			if c.Ctx.Input.Method() == "GET" {
				paramsJson, _ := json.Marshal(c.Ctx.Input.Params())
				params = string(paramsJson)
			} else {
				params = string(c.Ctx.Input.RequestBody)
			}
			header := c.Ctx.Request.Header
			headerJson, _ := json.Marshal(header)
			headerStr := string(headerJson)
			go cache.AdminOperateRecord(adminId, realName, uuid, uri, params, ip, userAgent, headerStr)
		}
	}

	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
	// 设置Cookie为HTTPOnly
	c.Ctx.SetCookie("", "", -1, "/", "", false, true, "")
	//fmt.Println(c.Ctx.ResponseWriter.Header().Get("Set-Cookie"))

	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)
	// 如果不是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
}
