package controllers

import (
	"errors"
	"net/http"
	"spaceofcheng/services/service"
	"spaceofcheng/services/utils"
	"strings"

	"github.com/astaxie/beego"
)

// Authenticate 权限验证
func (c *BaseController) authenticate() {

	// 默认 service
	serv := service.NewSysServ(c.Context)

	orgID := c.GetString(":org")
	if orgID == "" {
		c.ResponseError(errors.New("接口地址访问不正确"))
	}
	serv.SetOrgByID(orgID)

	// 客户端类型
	clientType := utils.GetClientType(c.Ctx.Request)

	switch clientType {
	case utils.ClientAdmin:
		c.authPCAdmin(serv)
	case utils.ClientWechat:
		c.authWechat(serv)
	default:
		c.ResponseError(
			errors.New("暂不支持的 API 场景"),
			http.StatusBadRequest,
		)
	}
}

// authPCAdmin PC管理端
func (c *BaseController) authPCAdmin(serv *service.SysServ) {
	if !c.needAuth() {
		return
	}

	// 用户ID
	userID := ""
	userIDRaw := c.GetSession(SNUserID)
	if userIDRaw != nil {
		userID = userIDRaw.(string)
	}

	if userID == "" {
		c.ResponseError(
			errors.New("用户未登录"),
			http.StatusUnauthorized,
		)
	}

	if err := serv.SetUserProfile(userID); err != nil {
		// utils.LogError(err.Error())

		c.ResponseError(
			utils.LogError(err.Error()),
			http.StatusInternalServerError,
		)
	}

	// 设置 Session
	c.SetSession(SNUserID, userID)
}

// authWechat 微信端
func (c *BaseController) authWechat(serv *service.SysServ) {
	custID := ""
	custIDRaw := c.GetSession(SNCustID)
	if custIDRaw != nil {
		custID = custIDRaw.(string)
	}

	// 机构ID - 后面再思考机构问题
	var orgID = "1"
	// 微信配置
	wxConf, err := serv.GetWeChatConfig(orgID)
	if err != nil {
		utils.LogError("查询微信配置失败: " + err.Error())
		c.ResponseError(
			errors.New("没有找到微信相关配置"),
			http.StatusBadRequest,
		)
	}
	utils.WxClientSingleton(orgID, wxConf)

	// 用户微信信息
	var wxDetail map[string]interface{}

	detailRaw := c.GetSession("wechat_user")
	if detailRaw != nil {
		wxDetail = detailRaw.(map[string]interface{})
	} else {
		// DEV MODE
		if c.RunMode == "dev" {
			wxDetail = map[string]interface{}{
				"openid":     "OPENID",
				"nickname":   "NICKNAME",
				"sex":        "1",
				"province":   "PROVINCE",
				"city":       "CITY",
				"country":    "COUNTRY",
				"headimgurl": "http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
				"unionid":    "o6_bmasdasdsad6_2sgVt7hMZOPfL",
			}
		} else {
			wxDetail = c.getWechatDetail(orgID, serv)
		}

		c.SetSession("wechat_user", wxDetail)
	}

	c.Context.Set("wxInfo", wxDetail)

	// 用户映射检查
	userMap, err := serv.CheckWechatUserMapping(wxDetail)
	if err != nil {
		c.ResponseError(
			utils.LogError("获取人员映射账户失败: "+err.Error()),
			http.StatusInternalServerError,
		)
	}
	c.Context.Set("userMap", *userMap)

	if !c.needAuth() {
		return
	}

	// 未登录或者绑定, 返回 401
	if custID == "" && userMap.UserId == "" {
		c.ResponseData(
			map[string]interface{}{
				"appid": wxConf["appid"],
			},
			errors.New("用户未登录或绑定"),
			http.StatusUnauthorized,
		)
	}

	if custID == "" {
		custID = userMap.UserId
	}

	if err := serv.SetCustomer(custID); err != nil {
		utils.LogError(err.Error())

		c.ResponseError(
			errors.New("内部错误, 请重试"),
			http.StatusInternalServerError,
		)
	}

	// 设置 Session
	c.SetSession(SNCustID, custID)
}

func (c *BaseController) needAuth() bool {
	route := c.Ctx.Input.URL()
	apiPrefix := beego.AppConfig.String("api::prefix")
	guestAPI := beego.AppConfig.String("api::guest")

	if strings.Index(route, apiPrefix+guestAPI) > -1 {
		return false
	}

	return true
}

// getWechatDetail 获取微信个人信息详情
func (c *BaseController) getWechatDetail(org string, serv *service.SysServ) map[string]interface{} {
	// 微信 code
	code := c.GetString("code")
	if code == "" {
		c.ResponseError(
			errors.New("没有接收到微信 code"),
			http.StatusUnauthorized,
		)
	}

	usr, err := utils.WxClientFor(org).GetUserInfo(code)
	if err != nil {
		c.ResponseError(
			utils.LogError("获取微信个人信息失败: "+err.Error()),
			http.StatusInternalServerError,
		)
	}

	return usr
}
