// Copyright (c) Shenyang Leading Edge Intelligent Technology Co., Ltd. All rights reserved.

package implments

import (
	dal "LAPP_ACURA_MOM_BACKEND/dao/base"
	"LAPP_ACURA_MOM_BACKEND/db"
	"LAPP_ACURA_MOM_BACKEND/global"
	"LAPP_ACURA_MOM_BACKEND/grmi"
	meta "LAPP_ACURA_MOM_BACKEND/meta/base"
	model "LAPP_ACURA_MOM_BACKEND/models/base"
	"LAPP_ACURA_MOM_BACKEND/utils"
	"errors"
	"golang.org/x/crypto/bcrypt"
)

/******************************************************************************
 *
 * @Description              : User的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-16 16:11:14
 *
 ******************************************************************************/
var DefaultConditionOfUser = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.User_UserId.UrlParameterName:     grmi.NewConditionItem(meta.User_UserId, grmi.Equal, true),
		meta.User_Name.UrlParameterName:       grmi.NewConditionItem(meta.User_Name, grmi.Equal, false),
		meta.User_NickName.UrlParameterName:   grmi.NewConditionItem(meta.User_NickName, grmi.Equal, false),
		meta.User_DepId.UrlParameterName:      grmi.NewConditionItem(meta.User_DepId, grmi.Equal, false),
		meta.User_Phone.UrlParameterName:      grmi.NewConditionItem(meta.User_Phone, grmi.Equal, false),
		meta.User_Avatar.UrlParameterName:     grmi.NewConditionItem(meta.User_Avatar, grmi.Equal, false),
		meta.User_Email.UrlParameterName:      grmi.NewConditionItem(meta.User_Email, grmi.Equal, false),
		meta.User_Status.UrlParameterName:     grmi.NewConditionItem(meta.User_Status, grmi.Equal, false),
		meta.User_Gender.UrlParameterName:     grmi.NewConditionItem(meta.User_Gender, grmi.Equal, false),
		meta.User_Position.UrlParameterName:   grmi.NewConditionItem(meta.User_Position, grmi.Equal, false),
		meta.User_Role.UrlParameterName:       grmi.NewConditionItem(meta.User_Role, grmi.Equal, false),
		meta.User_Remark.UrlParameterName:     grmi.NewConditionItem(meta.User_Remark, grmi.Equal, false),
		meta.User_Password.UrlParameterName:   grmi.NewConditionItem(meta.User_Password, grmi.Equal, false),
		meta.User_RoleId.UrlParameterName:     grmi.NewConditionItem(meta.User_RoleId, grmi.Equal, false),
		meta.User_LastModify.UrlParameterName: grmi.NewConditionItem(meta.User_LastModify, grmi.Approximate, false),
		meta.User_LastUser.UrlParameterName:   grmi.NewConditionItem(meta.User_LastUser, grmi.Equal, false),
		meta.User_CreateTime.UrlParameterName: grmi.NewConditionItem(meta.User_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : User的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-16 16:11:14
 *
 ******************************************************************************/
var DefaultConditionOfUserAndPaging = grmi.NewCondition(
	DefaultConditionOfUser.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : UserServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : User的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-16 16:11:14
 *
 ******************************************************************************/
type UserServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewUserDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个UserDAOImplement实例
 *
 * @Return Value             : UserDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-08-16 16:11:14
 *
 ******************************************************************************/
func NewUserServiceImplement() *UserServiceImplement {
	return &UserServiceImplement{}
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/UserService.InsertOne
 *
 ******************************************************************************/
func (impl *UserServiceImplement) InsertOne(user *global.User, entity *model.User) error {

	grmi.Log(user, "/services/base/implments/User.service.impl.go", "InsertOneUser", "插入一个User")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewUserDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.UserId)
	if err != nil {
		return err
	}
	if record != nil {
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}
	entity.Password = utils.Encrypt("123456")
	err = dao.InsertOne(entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/UserService.DeleteOne
 *
 ******************************************************************************/
func (impl *UserServiceImplement) DeleteOne(user *global.User, userId string) error {

	grmi.Log(user, "/services/base/implments/User.service.impl.go", "DeleteOneUser", "删除一个User")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewUserDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(userId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.DeleteOne(userId)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/UserService.SelectOne
 *
 ******************************************************************************/
func (impl *UserServiceImplement) SelectOne(user *global.User, userId string) (*model.User, error) {

	grmi.Log(user, "/services/base/implments/User.service.impl.go", "SelectOneUser", "查询一个User")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewUserDAO(session, user.PlantNr, user.UserId)
	result, err := dao.SelectOne(userId)
	if err != nil {
		return nil, err
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/UserService.UpdateOne
 *
 ******************************************************************************/
func (impl *UserServiceImplement) UpdateOne(user *global.User, entity *model.User) error {

	grmi.Log(user, "/services/base/implments/User.service.impl.go", "UpdateOneUser", "修改一个User")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewUserDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.UserId)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/UserService.Insert
 *
 ******************************************************************************/
func (impl *UserServiceImplement) Insert(user *global.User, entities *[]model.User) error {

	grmi.Log(user, "/services/base/implments/User.service.impl.go", "InsertUser", "插入多个User")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewUserDAO(session, user.PlantNr, user.UserId)

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.UserId)
		if err != nil {
			return err
		}
		if record != nil {
			return grmi.NewBusinessError("已经存在相同主键的记录!")
		}
	}

	err := dao.Insert(entities)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/UserService.Delete
 *
 ******************************************************************************/
func (impl *UserServiceImplement) Delete(user *global.User, entities *[]model.User) error {

	grmi.Log(user, "/services/base/implments/User.service.impl.go", "DeleteUser", "删除多个User")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewUserDAO(session, user.PlantNr, user.UserId)

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.UserId)
		if err != nil {
			return err
		}
		if record == nil {
			return grmi.NewBusinessError("不存在指定记录!")
		}
	}

	err := dao.Delete(entities)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/UserService.Select
 *
 ******************************************************************************/
func (impl *UserServiceImplement) Select(user *global.User, urlParameters map[string]string) ([]model.User, error) {

	grmi.Log(user, "/services/base/implments/User.service.impl.go", "SelectUser", "查询User")

	condition := DefaultConditionOfUserAndPaging
	engine := db.Eloquent.Master()
	engine.ShowSQL(true)
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return nil, err
	}
	dao := dal.NewUserDAO(session, user.PlantNr, user.UserId)
	result, err := dao.Select(predicates, condition.OrderByFields)
	if err != nil {
		return nil, err
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/UserService.SelectAndPaging
 *
 ******************************************************************************/
func (impl *UserServiceImplement) SelectAndPaging(user *global.User, urlParameters map[string]string) (grmi.PagingResult, error) {

	grmi.Log(user, "/services/base/implments/User.service.impl.go", "SelectUser", "查询User")

	condition := DefaultConditionOfUserAndPaging
	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	predicates, err := condition.BuildPredicates(urlParameters)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}
	dao := dal.NewUserDAO(session, user.PlantNr, user.UserId)
	condition.Fill(urlParameters)
	result, err := dao.SelectAndPaging(condition.Paging, predicates, condition.OrderByFields)
	if err != nil {
		return grmi.EmptyPagingResult, err
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/UserService.Update
 *
 ******************************************************************************/
func (impl *UserServiceImplement) Update(user *global.User, entities *[]model.User) error {

	grmi.Log(user, "/services/base/implments/User.service.impl.go", "UpdateUser", "修改多个User")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewUserDAO(session, user.PlantNr, user.UserId)

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.UserId)
		if err != nil {
			return err
		}
		if record == nil {
			return grmi.NewBusinessError("不存在指定记录!")
		}
	}

	err := dao.Update(entities)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/UserService.GetUserByUsername
 *
 ******************************************************************************/
func (impl *UserServiceImplement) GetUserByUsername(plantNr int, userId string) (*model.User, error) {

	grmi.Log(nil, "/services/base/implments/User.service.impl.go", "GetUserByUsername", "查询一个User")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewUserDAO(session, plantNr, userId)
	result, err := dao.GetUserByUsername(plantNr, userId)
	if err != nil {
		return nil, err
	}
	return result, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/UserService.GetUserByUsername
 *
 ******************************************************************************/
func (impl *UserServiceImplement) SetPwd(user *global.User, pwd *model.SysUserPwd) (bool, error) {

	grmi.Log(nil, "/services/base/implments/User.service.impl.go", "GetUserByUsername", "查询一个User")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewUserDAO(session, user.PlantNr, user.UserId)
	result, err := dao.SelectOne(user.UserId)
	if err != nil {
		return false, err
	}

	_, err = utils.CompareHashAndPassword(result.Password, pwd.OldPassword)
	if err != nil {
		return false, err
	}
	newPassword, err := impl.Encrypt(pwd.NewPassword)
	if err != nil {
		return false, err
	}
	result.Password = newPassword
	err = dao.UpdatePwd(result)
	if err != nil {
		return false, err
	}
	return true, nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/UserService.GetUserByUsername
 *
 ******************************************************************************/
func (impl *UserServiceImplement) GetUserInfo(user *global.User, userId string) (*model.UserViewInfo, error) {

	grmi.Log(nil, "/services/base/implments/User.service.impl.go", "GetUserByUsername", "查询一个User")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewUserDAO(session, user.PlantNr, user.UserId)
	result, err := dao.GetUserInfo(user.PlantNr, userId)
	if err != nil {
		return nil, err
	}
	if result == nil {
		return nil, errors.New("信息不存在")
	}
	return result, nil
}

//加密
func (impl *UserServiceImplement) Encrypt(password string) (newPassword string, err error) {
	if password == "" {
		return "", errors.New("密码不能为空!")
	}
	var hash []byte
	hash, err = bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return
	}
	return string(hash), nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/UserService.UpdateStatus
 *
 ******************************************************************************/
func (impl *UserServiceImplement) UpdateStatus(user *global.User, entity *model.User) error {

	grmi.Log(user, "/services/base/implments/User.service.impl.go", "UpdateStatus", "修改一个User状态")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewUserDAO(session, user.PlantNr, user.UserId)
	err := dao.UpdateStatus(entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/UserService.UpdatePic
 *
 ******************************************************************************/
func (impl *UserServiceImplement) UpdatePic(user *global.User, entity *model.User) error {

	grmi.Log(user, "/services/base/implments/User.service.impl.go", "UpdateStatus", "修改一个User状态")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewUserDAO(session, user.PlantNr, user.UserId)
	err := dao.UpdatePic(entity)
	if err != nil {
		return err
	}
	return nil
}
