package service

import (
	"errors"
	"spaceofcheng/services/models"
	"spaceofcheng/services/models/cases"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/models/system"
	"spaceofcheng/services/utils"

	"github.com/astaxie/beego"
	"github.com/yl10/kit/encrypt"
)

// UserServ 系统处理
type UserServ struct {
	ctx     *utils.Context
	dao     *system.UserDAO
	casedao *cases.CaseDAO
}

// NewUserServ 初始化
func NewUserServ(ctx *utils.Context) *UserServ {
	return &UserServ{
		ctx:     ctx,
		dao:     system.NewUserDAO(ctx),
		casedao: cases.NewCaseDAO(ctx),
	}
}

// GetUserList 获取用户列表
func (s *UserServ) GetUserList(username, typeid, caseids string, page int, pageSize int) (map[string]interface{}, error) {
	if pageSize == 0 {
		pageSize = PAGENUM
	}
	if page == 0 {
		page = 1
	}
	userList, err := s.dao.GetUserList(username, typeid, caseids, page, pageSize)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	total, err := s.dao.GetUserCount(username, typeid, caseids)
	if err != nil {
		beego.Error(err)
		return nil, err
	}

	return map[string]interface{}{
		"list":     userList,
		"pagesize": pageSize,
		"pagenum":  total,
		"page":     page,
	}, nil
}

// GetCurrentEnvVars 获取当前环境相关变量
func (s *UserServ) GetCurrentEnvVars() (map[string]interface{}, error) {
	// 当前用户信息
	user := s.ctx.Get("user").(model.SysUser)
	user.Pwd = ""
	// 当前用户案场
	cases := s.ctx.Get("cases").([]model.SysUserCase)
	// 当前用户角色
	roles, err := s.dao.GetUserRole(user.UserId)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	// 当前用户菜单
	menus, err := s.dao.GetUserMenu(user.UserId)
	if err != nil {
		beego.Error(err)
		return nil, err
	}

	rtn := map[string]interface{}{
		"user":  user,
		"cases": cases,
		"roles": roles,
		"menus": menus,
	}

	return rtn, nil
}

// GetUserByID 根据用户ID获取用户信息
func (s *UserServ) GetUserByID(userid string) (*system.UserInfo, error) {
	userinfo, err := s.dao.GetUserByID(userid)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	userinfo.Pwd = ""
	usertype, err := s.dao.GetUserType(userid)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	userinfo.UserType = usertype

	usertag, err := s.dao.GetUserTag(userid)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	userinfo.UserTag = usertag

	usercase, err := s.dao.GetUserCase(userid)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	userinfo.UserCase = usercase

	// userrole, err := s.dao.GetUserRole(userid)
	// if err != nil {
	// 	return nil, err
	// }
	// userinfo.UserRole = userrole

	// usermenu, err := s.dao.GetUserMenu(userid)
	// if err != nil {
	// 	return nil, err
	// }
	// userinfo.UserMenu = usermenu

	return userinfo, nil
}

// SaveUser 用户保存
func (s *UserServ) SaveUser(user system.SysUserForm) (*model.SysUser, error) {
	var userInfo model.SysUser
	userInfo.UserId = user.UserId
	userInfo.UserId = user.UserId

	userInfo.UserId = user.UserId
	userInfo.UserName = user.UserName
	userInfo.RealName = user.RealName
	userInfo.OrgId = user.OrgId
	userInfo.Sex = user.Sex
	userInfo.WorkNo = user.WorkNo
	userInfo.Email = user.Email
	userInfo.Phone = user.Phone
	userInfo.Headimgurl = user.Headimgurl

	var err error
	var newUSer *model.SysUser
	if user.UserId != "" {
		err = s.dao.UpdateUser(userInfo)
		if err != nil {
			beego.Error(err)
			return nil, err
		}
		// 删除用户对应的标签、用户类型及所属案场
		err = s.dao.DelUserTag(user.UserId)
		if err != nil {
			beego.Error(err)
			return nil, err
		}
		err = s.dao.DelUserType(user.UserId)
		if err != nil {
			beego.Error(err)
			return nil, err
		}
		err = s.dao.DelUserBelongCase(user.UserId)
		if err != nil {
			beego.Error(err)
			return nil, err
		}
		newUSer = &userInfo
	} else {
		newUSer, err = s.dao.AddUser(userInfo)
		if err != nil {
			beego.Error(err)
			return nil, err
		}
	}

	// 保存用户的标签、用户类型及所属案场
	err = s.dao.SaveUserTag(newUSer.UserId, user.TagIds)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	err = s.dao.SaveUserType(newUSer.UserId, user.TypeId)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	caseInfo, err := s.casedao.GetCaseByID(user.BelongCaseId)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	if caseInfo == nil {
		return nil, errors.New("所属案场不存在！")
	}
	var userCase model.SysUserCase
	userCase.CaseId = user.BelongCaseId
	userCase.CaseName = caseInfo.CaseName
	userCase.IsBelong = 1
	userCase.UserId = newUSer.UserId
	err = s.dao.SaveUserCase(userCase)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	newUSer.Pwd = ""
	return newUSer, err
}

// UpdatePassword 密码修改
func (s *UserServ) UpdatePassword(oriPasswd, newPasswd string, user *model.SysUser) error {
	if !s.dao.ValidatePassword(user, oriPasswd) {
		return errors.New("密码错误！")
	}

	if err := s.dao.UpdatePassword(user.UserId, newPasswd); err != nil {
		return err
	}

	return nil
}

// ResetPassword 重设密码
func (s *UserServ) ResetPassword(userid string) error {
	newPasswd := encrypt.Md5("123456")
	if err := s.dao.UpdatePassword(userid, newPasswd); err != nil {
		return err
	}

	return nil
}

// UserMapping 用户隐射
func (s *UserServ) UserMapping(userMapping model.TaUserMapping) error {
	err := s.dao.SaveUserMapping(&userMapping)
	if err != nil {
		return err
	}
	// info := make(map[string]string)
	// err = json.Unmarshal([]byte(userMapping.AccountInfo), &info)
	// if err != nil {
	// 	beego.Error("Umarshal failed:", err)
	// 	return err
	// }
	// // 根据用户类型更新用户表中的数据
	// switch userMapping.UserType {
	// case USERTYPE_USER:
	// 	err = s.dao.UpdateUserHeadImg(userMapping.UserId, info["headimgurl"])
	// 	break
	// case USERTYPE_CUSTOMER:
	// 	err = s.dao.UpdateCustomerHeadImg(userMapping.UserId, info["nickname"], info["headimgurl"])
	// 	break
	// }
	return nil
}

// DelUser 删除用户
func (s *UserServ) DelUser(userid string) error {
	err := s.dao.DelUser(userid)
	return err
}

// GetUserTypes 获取用户类型
func (s *UserServ) GetUserTypes(orgid string) ([]model.TdUserType, error) {
	types, err := s.dao.GetUserTypes(orgid)
	return types, err
}

// GetUserRoles 获取用户角色
func (s *UserServ) GetUserRoles(userid string) ([]model.SysRole, error) {
	if userid == "" {
		return nil, utils.LogError("没有对应的用户信息！")
	}
	userroles, err := s.dao.GetUserRole(userid)
	return userroles, err
}

// SaveUserRole 保存用户对应角色
func (s *UserServ) SaveUserRole(userid, roleids string) error {
	if userid == "" {
		return utils.LogError("没有对应的用户信息！")
	}
	if roleids == "" {
		return utils.LogError("没有对应的角色信息！")
	}
	err := s.dao.DelUserRole(userid)
	if err != nil {
		return err
	}
	err = s.dao.SaveUserRole(userid, roleids)
	if err != nil {
		return err
	}
	err = s.dao.DelUserMenu(userid)
	if err != nil {
		return err
	}
	err = s.dao.SaveUserMenu(userid)
	return err
}

// GetUserCustomer 获取我的推荐客户
func (s *UserServ) GetUserCustomer(userid string, page int, pageSize int) ([]model.TaCustomer, error) {
	if pageSize == 0 {
		pageSize = PAGENUM
	}
	if page == 0 {
		page = 1
	}
	customers, err := s.dao.GetUserCustomer(userid, page, pageSize)
	return customers, err
}

// CheckUserSignIn 校验用户登录
func (s *UserServ) CheckUserSignIn(userName, userPassword string) (*model.SysUser, error) {
	user, err := s.dao.GetUserByName(userName)
	if err != nil {
		beego.Error(err)
		return nil, err
	}

	if user == nil {
		return nil, errors.New("账户不存在")
	}

	if user.Status != models.STATUS_NORMAL {
		return nil, errors.New("用户账户异常")
	}

	if !s.dao.ValidatePassword(user, userPassword) {
		return nil, errors.New("用户密码不正确")
	}

	return user, nil
}
