// 模块模型操作接口-用户
// 秒寻科技
// zt 2024-01-04

package userapi

import (
	"errors"
	"ipsomc/core/company/companymodel"
	"ipsomc/core/dao/mysql/mysqlapi"
	"ipsomc/core/dao/mysql/mysqlmodel"
	"ipsomc/core/dbtable/dbtableapi"
	"ipsomc/core/user/usermodel"
	"ipsomc/util"
	"strconv"
	"strings"

	"github.com/jinzhu/gorm"
)

type UserApi struct {
	MySqlApi   mysqlapi.MySqlApi
	dbTableApi dbtableapi.DbTableApi
}

// 检查用户是否已经注册
func (obj *UserApi) CheckOperatorRegister(dataModel *usermodel.Operator) error {
	companyModel := new(companymodel.Company)
	ciphertext, err := util.EncryptAes([]byte(dataModel.Password)) //加密用户密码
	if err != nil {
		return err
	}

	if err := obj.MySqlApi.GetDb().Where("user_name=? and password=?", dataModel.UserName, ciphertext).First(dataModel).Error; err != nil {
		return err
	}
	if dataModel.ID <= 0 {
		return errors.New("登录失败，请先注册")
	}

	//获得公司名称
	if dataModel.CompanyID > 0 {
		if err := obj.MySqlApi.GetDb().Model(companyModel).Where("id=?", dataModel.CompanyID).First(companyModel).Error; err != nil {
			return err
		}
		dataModel.CompanyName = companyModel.Name
	} else {
		dataModel.CompanyName = "杭州秒寻科技有限公司"
	}

	return nil
}

// 系统管理员查重
func (obj *UserApi) CheckOperatorName(userName string) error {
	var count uint
	dataModel := new(usermodel.Operator)
	if err := obj.MySqlApi.GetDb().Model(dataModel).Where("user_name=?", userName).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("该用户名已经存在")
	}

	return nil
}

// 增加操作员
func (obj *UserApi) AddOperator(dataModel *usermodel.Operator) error {
	var count uint

	//查重
	if err := obj.MySqlApi.GetDb().Model(dataModel).Where("user_name=?", dataModel.UserName).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("新增失败，该用户名已存在")
	}

	//用户密码加密
	ciphertext, err := util.EncryptAes([]byte(dataModel.Password))
	if err != nil {
		return err
	}
	dataModel.Password = ciphertext

	dataModel.UserTypeID = 3 //项目管理员

	//保存数据
	if err := obj.MySqlApi.AddItem(dataModel); err != nil {
		return errors.New("新增失败，数据库操作失败")
	}

	return nil
}

// 修改
func (obj *UserApi) UpdateOperator(dataModel *usermodel.Operator, dataMap map[string]interface{}) error {
	var count uint
	var tmpModel usermodel.Operator

	//查重
	if err := obj.MySqlApi.GetDb().Model(&tmpModel).Where("id<>? and user_name=?", dataModel.ID, dataModel.UserName).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("该用户已经存在")
	}
	if err := obj.MySqlApi.UpdateItem(dataModel, dataMap); err != nil {
		return err
	}

	return nil
}

// 修改密码
func (obj *UserApi) UpdateOperatorPwd(dataModel *usermodel.Operator, dataMap map[string]interface{}) error {
	operatorModel := new(usermodel.Operator)
	db := obj.MySqlApi.GetDb()
	if err := db.Model(operatorModel).Where("id=?", dataModel.OwnerID).First(operatorModel).Error; err != nil {
		return err
	}

	//检查原密码是否正确
	ciphertextOld, err := util.EncryptAes([]byte(dataModel.Password))
	if err != nil {
		return err
	}
	if ciphertextOld != operatorModel.Password {
		return errors.New("输入的以前密码不正确")
	}

	//加密新改密码
	ciphertextNew, err := util.EncryptAes([]byte(dataModel.NewPassword))
	if err != nil {
		return err
	}

	//修改密码
	if err := db.Model(operatorModel).Update("password", ciphertextNew).Error; err != nil {
		return err
	}

	return nil
}

// 重置密码
func (obj *UserApi) ResetOperatorPwd(dataModel *usermodel.Operator) error {
	randomStr := util.GenRandomString(6)                  //生成6位随机密码
	ciphertext, err := util.EncryptAes([]byte(randomStr)) //对新密码进行加密
	if err != nil {
		return err
	}

	//修改密码
	if err := obj.MySqlApi.GetDb().Model(dataModel).Where("id=?", dataModel.ID).Update("password", ciphertext).Error; err != nil {
		return err
	}

	//将新改密码返回
	dataModel.Password = randomStr

	return nil
}

// 删除
func (obj *UserApi) DeleteOperator(dataModel *usermodel.Operator) error {
	if err := obj.MySqlApi.DeleteItem(dataModel); err != nil {
		return errors.New("删除记录失败")
	}
	return nil
}

// 查询单条记录
func (obj *UserApi) GetOperatorById(dataModel *usermodel.Operator) error {
	if err := obj.MySqlApi.GetItemByID(dataModel); err != nil {
		return errors.New("查询记录失败")
	}
	dataModel.Password = "******" //密码脱敏
	return nil
}

// 分页查询记录
func (obj *UserApi) GetOperatorPageList(dataModel *usermodel.Operator, pageListParam *mysqlmodel.PageListParam, dataList interface{}) (mysqlmodel.PageListData, error) {
	pageListData, err := obj.MySqlApi.GetPageItemList(dataModel, pageListParam, dataList)
	if err != nil {
		return pageListData, err
	}

	return pageListData, nil
}

// 获得用户角色列表
func (obj *UserApi) GetOperatorRoleList(dataModel *usermodel.Operator) ([]int, error) {
	roleList := make([]int, 0)
	//获得用户数据
	dataModel.ID = int(dataModel.OwnerID)
	if err := obj.MySqlApi.GetItemByID(dataModel); err != nil {
		return roleList, err
	}

	roleStrList := strings.Split(dataModel.Role, ",")

	for _, v := range roleStrList {
		roleId, _ := strconv.Atoi(v)
		roleList = append(roleList, roleId)
	}

	return roleList, nil
}

// 获得用户权限列表
func (obj *UserApi) GetOperatorPermissionList(roleIdList []int) (usermodel.RspOperatorPermission, error) {
	var tmpModel usermodel.Role
	roleList := []usermodel.Role{}
	idTmpList := make([]int, 0)
	idList := make([]int, 0)
	var pmsModel usermodel.Permission
	permissionListList := []usermodel.Permission{}
	var resPermission usermodel.RspOperatorPermission

	//获得角色记录
	if err := obj.MySqlApi.GetDb().Model(&tmpModel).Where("id in (?)", roleIdList).Scan(&roleList).Error; err != nil {
		return resPermission, err
	}

	//遍历列表，组织权限列表
	for _, v := range roleList {
		permissionStrList := strings.Split(v.Permission, ",")
		for _, strId := range permissionStrList {
			id, _ := strconv.Atoi(strId)
			idTmpList = append(idTmpList, id)
		}
	}

	//过滤重复的权限ID
	isExist := false
	for _, v := range idTmpList {
		isExist = false
		for _, id := range idList {
			if v == id {
				isExist = true
				break
			}
		}
		if !isExist {
			idList = append(idList, v)
		}
	}

	//获得权限记录
	if err := obj.MySqlApi.GetDb().Model(&pmsModel).Where("id in (?)", idList).Scan(&permissionListList).Error; err != nil {
		return resPermission, err
	}

	//组织菜单和按钮权限
	for _, v := range permissionListList {
		var item usermodel.MenuBtnPermission
		item.Pid = v.Pid
		item.TypeID = v.TypeID
		item.Name = v.Name
		item.Flag = v.Flag
		if v.TypeID == 1 {
			resPermission.Menus = append(resPermission.Menus, item)
		} else {
			resPermission.Btns = append(resPermission.Btns, item)
		}
	}

	return resPermission, nil
}

// 获得公司系统管理员，每家公司只有一个系统管理员
func (obj *UserApi) GetSysOperatorByCompanyId(companyId int) (*usermodel.Operator, error) {
	operatorModel := new(usermodel.Operator)

	//获得系统操作员
	if err := obj.MySqlApi.GetDb().Model(operatorModel).Where("company_id=? and user_type_id=2", companyId).First(operatorModel).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			return operatorModel, err
		}
	}

	//密码脱敏
	if len(operatorModel.Password) > 0 {
		operatorModel.Password = "******"
	}

	return operatorModel, nil
}

/**************************************上面是操作员接口***************************************/
/**************************************下面管理角色接口***************************************/

// 增加操作员
func (obj *UserApi) AddRole(dataModel *usermodel.Role) error {
	var count uint

	//查重
	if err := obj.MySqlApi.GetDb().Model(dataModel).Where("company_id=? and  name=?", dataModel.CompanyID, dataModel.Name).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("该角色已存在")
	}

	//保存数据
	if err := obj.MySqlApi.AddItem(dataModel); err != nil {
		return errors.New("数据库操作失败")
	}

	return nil
}

// 修改
func (obj *UserApi) UpdateRole(dataModel *usermodel.Role, dataMap map[string]interface{}) error {
	var count uint
	var tmpModel usermodel.Role

	//查重
	if err := obj.MySqlApi.GetDb().Model(&tmpModel).Where("id<>? and company_id=? and name=?", dataModel.ID, dataModel.CompanyID, dataModel.Name).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("该角色已存在")
	}
	if err := obj.MySqlApi.UpdateItem(dataModel, dataMap); err != nil {
		return err
	}

	return nil
}

// 删除
func (obj *UserApi) DeleteRole(dataModel *usermodel.Role) error {
	if err := obj.MySqlApi.DeleteItem(dataModel); err != nil {
		return errors.New("删除记录失败")
	}
	return nil
}

// 查询单条记录
func (obj *UserApi) GetRoleId(dataModel *usermodel.Role) error {
	if err := obj.MySqlApi.GetItemByID(dataModel); err != nil {
		return errors.New("查询记录失败")
	}
	return nil
}

// 分页查询记录
func (obj *UserApi) GetRolePageList(dataModel *usermodel.Role, pageListParam *mysqlmodel.PageListParam, dataList interface{}) (mysqlmodel.PageListData, error) {
	pageListData, err := obj.MySqlApi.GetPageItemList(dataModel, pageListParam, dataList)
	if err != nil {
		return pageListData, err
	}
	return pageListData, nil
}

/**************************************上面管理角色接口***************************************/
/**************************************下面管理权限接口***************************************/

// 增加操作员
func (obj *UserApi) AddPermission(dataModel *usermodel.Permission) error {
	var count uint

	//查重
	if err := obj.MySqlApi.GetDb().Model(dataModel).Where("flag=?", dataModel.Flag).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("该权限已存在")
	}

	//保存数据
	if err := obj.MySqlApi.AddItem(dataModel); err != nil {
		return errors.New("数据库操作失败")
	}

	return nil
}

// 修改
func (obj *UserApi) UpdatePermission(dataModel *usermodel.Permission, dataMap map[string]interface{}) error {
	var count uint
	var tmpModel usermodel.Permission

	//查重
	if err := obj.MySqlApi.GetDb().Model(&tmpModel).Where("id<>? and company_id=? and pid=? and flag=?", dataModel.ID, dataModel.CompanyID, dataModel.Pid, dataModel.Flag).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("该权限已存在")
	}

	if err := obj.MySqlApi.UpdateItem(dataModel, dataMap); err != nil {
		return err
	}

	return nil
}

// 删除
func (obj *UserApi) DeletePermission(dataModel *usermodel.Permission) error {
	if err := obj.MySqlApi.DeleteItem(dataModel); err != nil {
		return errors.New("删除记录失败")
	}
	return nil
}

// 查询单条记录
func (obj *UserApi) GetPermissionId(dataModel *usermodel.Permission) error {
	if err := obj.MySqlApi.GetItemByID(dataModel); err != nil {
		return errors.New("查询记录失败")
	}
	return nil
}

// 查询记录
func (obj *UserApi) GetPermissionList(dataModel *usermodel.Permission) ([]usermodel.Permission, error) {
	dataList := []usermodel.Permission{}
	operatorModel := new(usermodel.Operator)
	operatorModel.ID = int(dataModel.OwnerID)
	blackList := obj.dbTableApi.GetBlackPageList()

	//获得当前用户的类型
	if err := obj.GetOperatorById(operatorModel); err != nil {
		return dataList, err
	}

	//操作员是平台管理员
	if operatorModel.UserTypeID == 1 {
		//查询系统所有权限
		if err := obj.MySqlApi.GetDb().Model(dataModel).Where("company_id=0").Scan(&dataList).Error; err != nil {
			return dataList, err
		}
	} else {
		if err := obj.MySqlApi.GetDb().Model(dataModel).Where("flag not in (?)", blackList).Scan(&dataList).Error; err != nil {
			return dataList, err
		}
	}

	return dataList, nil
}

// 分页查询记录
func (obj *UserApi) GetPermissionPageList(dataModel *usermodel.Permission, pageListParam *mysqlmodel.PageListParam, dataList interface{}) (mysqlmodel.PageListData, error) {
	pageListData, err := obj.MySqlApi.GetPageItemList(dataModel, pageListParam, dataList)
	if err != nil {
		return pageListData, err
	}
	return pageListData, nil
}
