package controllers

import (
	"sparrow/pkg/models"
	"sparrow/pkg/server"
	"sparrow/services/knowoapi/model"
	"sparrow/services/knowoapi/services"

	"github.com/kataras/iris/v12"
)

// UserController api
type UserController struct {
	Ctx     iris.Context
	Service services.UserService
	Token   Token
}

// PostLogin /login
func (a *UserController) PostLogin() {
	lr := models.LoginRequest{}
	if err := parseBody(a.Ctx, &lr); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	b, user, err := a.Service.Login(&lr)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, "用户名或密码错误")
		return
	}
	if !b {
		responseError(a.Ctx, model.ErrUserNameOrPassCode, "用户名或密码错误")
		return
	}
	result := map[string]interface{}{
		"user_id":      user.ID,
		"company":      user.Vendor.VendorName,
		"access_token": a.Token.TokenMaker(user),
		"user_role":    user.UserRoleID,
	}
	done(a.Ctx, result)
}

// PostRegistry 注册
// POST /registry
func (a *UserController) PostRegistry() {
	req := &models.Reqrequest{}
	if err := parseBody(a.Ctx, req); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	b, err := a.Service.CheckEmail(req.Email)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	if b {
		responseError(a.Ctx, -1, "Email已经被注册")
		return
	}
	b, err = a.Service.CheckPhone(req.Phone)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	if b {
		responseError(a.Ctx, -1, "手机号被注册")
		return
	}
	b, err = a.Service.CheckUserName(req.UserName)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	if b {
		responseError(a.Ctx, -1, "该用户名已经被使用")
		return
	}
	user, err := a.Service.Register(req)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, map[string]interface{}{
		"user_name": user.UserName,
		"user_key":  user.UserKey,
		"vendor_id": user.VendorID,
		"user_id":   user.ID,
	})
}

// PutChange 修改密码
// PUT /user/changepass
func (a *UserController) PutChange() {
	req := new(models.ChangePassWordRequest)
	if err := parseBody(a.Ctx, req); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	//req.OldPass = base64.StdEncoding.EncodeToString([]byte(req.OldPass))
	//req.NewPass = base64.StdEncoding.EncodeToString([]byte(req.NewPass))
	b, err := a.Service.ModifyPassword(a.Token.getRecorID(a.Ctx), req.OldPass, req.NewPass)
	if err != nil {
		server.Log.Error(err)
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	if !b {
		responseError(a.Ctx, ErrNormal, "原密码不正确")
		return
	}
	done(a.Ctx, "修改成功")
}

// GetMenu get user menu
// GET /user/menu
func (a *UserController) GetMenu() {
	roleid := a.Token.getRoleID(a.Ctx)
	role, err := a.Service.GetRole(roleid)
	if err != nil {
		responseError(a.Ctx, ErrNormal, "用户角色信息错误，请联系管理员")
		return
	}
	done(a.Ctx, map[string]interface{}{
		"menu_list": role.MenuList,
		"role_name": role.RoleName,
	})
}
