package controllers

import (
	"encoding/json"
	"eta/eta_mini_crm_ht/models"
	"eta/eta_mini_crm_ht/utils"
	"fmt"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"

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

type BaseAuthController struct {
	web.Controller
	SysUser *models.SysUser
	Session *models.SysSession
}

func (c *BaseAuthController) Prepare() {
	method := c.Ctx.Input.Method()
	uri := c.Ctx.Input.URI()
	if method != "HEAD" {
		if method == "POST" || method == "GET" {
			authorization := c.Ctx.Input.Header("authorization")
			if authorization == "" {
				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, "=")
			if len(tokenArr) != 2 {
				c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权！", ErrMsg: "请重新授权:Token is fault"}, false, false)
				c.StopRun()
				return
			}
			token := tokenArr[1]

			session, err := models.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
			}
			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: "获取用户信息异常"}, false, false)
				c.StopRun()
				return
			}
			sysUser, err := models.GetSysUserById(session.SysUserId)
			if err != nil {
				if err.Error() == utils.ErrNoRow() {
					c.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆！", ErrMsg: "获取sysUser信息失败: " + strconv.Itoa(session.SysUserId)}, false, false)
					c.StopRun()
					return
				}
				c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常，请稍后重试!", ErrMsg: "获取sysUser信息异常，Err:" + err.Error()}, false, false)
				c.StopRun()
				return
			}
			if sysUser == nil {
				c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常，请稍后重试!", ErrMsg: "sysUser is empty"}, false, false)
				c.StopRun()
				return
			}
			if !sysUser.IsEnabled {
				c.JSON(models.BaseResponse{Ret: 408, Msg: "账户信息异常！", ErrMsg: "账户被禁用，不允许登陆!"}, false, false)
				c.StopRun()
				return
			}
			loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, session.SysSessionId)
			loginInfo, _ := utils.Rc.RedisString(loginKey)
			if loginInfo == `` {
				c.JSON(models.BaseResponse{Ret: 408, Msg: "超时未操作，系统自动退出！", ErrMsg: "超时未操作，系统自动退出！"}, false, false)
				c.StopRun()
				return
			}
			if loginInfo != "1" {
				msg := "在其他网络登录。此客户端已退出登录。"
				c.JSON(models.BaseResponse{Ret: 408, Msg: msg, ErrMsg: msg}, false, false)
				c.StopRun()
				return
			}
			c.SysUser = sysUser
			c.Session = session

			//接口权限校验
			roleId := sysUser.SysRoleId
			list, e := models.GetMenuButtonsByRoleId(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 + "&"
			}
			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] && !utils.NoAuthApiMap[uri] {
				c.JSON(models.BaseResponse{Ret: 403, Msg: "无权访问！", ErrMsg: "无权访问！"}, false, false)
				c.StopRun()
				return
			}

		}
	}
}

func (c *BaseAuthController) ServeJSON(encoding ...bool) {
	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 {
		body := "接口:" + "URI:" + c.Ctx.Input.URI() + ";无返回值"
		fmt.Println(body)
		utils.ApiLog.Notice(body)
		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 {
			body := "URI:" + c.Ctx.Input.URI() + "<br/> " + "Params" + requestBody + " <br/>" + "ErrMsg:" + baseRes.ErrMsg + ";<br/>Msg:" + baseRes.Msg + ";<br/> Body:" + string(body) + "<br/>" + c.SysUser.SysRealName
			fmt.Println(body)
			utils.ApiLog.Notice(body)
		}
	}

	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, "")

	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 {
		utils.ApiLog.Info("err:%s", err.Error())
	}
	c.logUri(content, requestBody, ip)
	if utils.RunMode != "debug" {
		content = utils.DesBase64Encrypt(content, utils.DesKey)
		content = []byte(`"` + string(content) + `"`)
	}
	if coding {
		content = []byte(utils.StringsToJSON(string(content)))
	}
	return c.Ctx.Output.Body(content)
}

func (c *BaseAuthController) logUri(respContent []byte, requestBody, ip string) {
	authorization := ""
	method := c.Ctx.Input.Method()
	uri := c.Ctx.Input.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
}
