// 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"
	"strconv"
	"time"
)

/******************************************************************************
 *
 * @Description              : Person的默认查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-25 14:20:56
 *
 ******************************************************************************/
var DefaultConditionOfPerson = grmi.NewCondition(
	map[string]grmi.ConditionItem{
		meta.Person_PersonNr.UrlParameterName:     grmi.NewConditionItem(meta.Person_PersonNr, grmi.Equal, true),
		meta.Person_PersonId.UrlParameterName:     grmi.NewConditionItem(meta.Person_PersonId, grmi.Equal, false),
		meta.Person_Name.UrlParameterName:         grmi.NewConditionItem(meta.Person_Name, grmi.Equal, false),
		meta.Person_Status.UrlParameterName:       grmi.NewConditionItem(meta.Person_Status, grmi.Equal, false),
		meta.Person_CostCenterId.UrlParameterName: grmi.NewConditionItem(meta.Person_CostCenterId, grmi.Equal, false),
		meta.Person_DepartmentId.UrlParameterName: grmi.NewConditionItem(meta.Person_DepartmentId, grmi.Equal, false),
		meta.Person_SalaryGrpId.UrlParameterName:  grmi.NewConditionItem(meta.Person_SalaryGrpId, grmi.Equal, false),
		meta.Person_BonusGrpId.UrlParameterName:   grmi.NewConditionItem(meta.Person_BonusGrpId, grmi.Equal, false),
		meta.Person_EntryDate.UrlParameterName:    grmi.NewConditionItem(meta.Person_EntryDate, grmi.Approximate, false),
		meta.Person_BirthDate.UrlParameterName:    grmi.NewConditionItem(meta.Person_BirthDate, grmi.Approximate, false),
		meta.Person_PersonIPara1.UrlParameterName: grmi.NewConditionItem(meta.Person_PersonIPara1, grmi.Equal, false),
		meta.Person_PersonIPara2.UrlParameterName: grmi.NewConditionItem(meta.Person_PersonIPara2, grmi.Equal, false),
		meta.Person_PersonDPara1.UrlParameterName: grmi.NewConditionItem(meta.Person_PersonDPara1, grmi.Equal, false),
		meta.Person_PersonDPara2.UrlParameterName: grmi.NewConditionItem(meta.Person_PersonDPara2, grmi.Equal, false),
		meta.Person_Avatar.UrlParameterName:       grmi.NewConditionItem(meta.Person_Avatar, grmi.Equal, false),
		meta.Person_LastModify.UrlParameterName:   grmi.NewConditionItem(meta.Person_LastModify, grmi.Approximate, false),
		meta.Person_LastUser.UrlParameterName:     grmi.NewConditionItem(meta.Person_LastUser, grmi.Equal, false),
		meta.Person_CreateTime.UrlParameterName:   grmi.NewConditionItem(meta.Person_CreateTime, grmi.Approximate, false),
	},
	nil,
)

/******************************************************************************
 *
 * @Description              : Person的默认分页查询条件
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-25 14:20:56
 *
 ******************************************************************************/
var DefaultConditionOfPersonAndPaging = grmi.NewCondition(
	DefaultConditionOfPerson.Items,
	grmi.NewPaging(),
)

/******************************************************************************
 *
 * @Struct Name              : PersonServiceImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : Person的服务实现
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-25 14:20:56
 *
 ******************************************************************************/
type PersonServiceImplement struct {
}

/******************************************************************************
 *
 * @Function Name            : NewPersonDAOImplement
 *-----------------------------------------------------------------------------
 *
 * @Description              : 创建一个PersonDAOImplement实例
 *
 * @Return Value             : PersonDAOImplement实例
 *
 * @Author                   : 代码生成器创建
 *
 * @Date                     : 2021-04-25 14:20:56
 *
 ******************************************************************************/
func NewPersonServiceImplement() *PersonServiceImplement {
	return &PersonServiceImplement{}
}

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

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewPersonDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.PersonNr)
	if err != nil {
		session.Rollback()
		return err
	}
	if record != nil {
		session.Rollback()
		return grmi.NewBusinessError("已经存在相同主键的记录!")
	}

	err = dao.InsertOne(entity)
	if err != nil {
		session.Rollback()
		return err
	}
	Valst := make([]model.WorkPlacePersonLst, 0)
	/**处理数据**/
	for k, v := range entity.WorkPlaceValst {
		dataone := model.WorkPlacePersonLst{}
		dataone.PersonNr = entity.PersonNr
		dataone.Pos = k + 1
		dataone.WorkPlaceNr = v.WorkPlaceNr
		Valst = append(Valst, dataone)
	}
	lstdao := dal.NewWorkPlacePersonLstDAO(session, user.PlantNr, user.UserId)
	err = lstdao.Insert(&Valst)
	if err != nil {
		session.Rollback()
		return err
	}
	session.Commit()

	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/PersonService.DeleteOne
 *
 ******************************************************************************/
func (impl *PersonServiceImplement) DeleteOne(user *global.User, personNr int) error {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return err
	}
	dao := dal.NewPersonDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(personNr)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.DeleteOne(personNr)
	if err != nil {
		return err
	}
	lstdao := dal.NewWorkPlacePersonLstDAO(session, user.PlantNr, user.UserId)
	err = lstdao.DeleteWhere([]grmi.Predicate{meta.WorkPlacePersonLst_PersonNr.NewPredicate(grmi.Equal, personNr)})
	if err != nil {
		session.Rollback()
		return err
	}
	session.Commit()

	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/PersonService.SelectOne
 *
 ******************************************************************************/
func (impl *PersonServiceImplement) SelectOne(user *global.User, personNr int) (*model.Person, error) {

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewPersonDAO(session, user.PlantNr, user.UserId)
	result, err := dao.SelectOne(personNr)
	if err != nil {
		return nil, err
	}
	lstdao := dal.NewWorkPlacePersonLstDAO(session, user.PlantNr, user.UserId)
	list, err := lstdao.SelectAllot(personNr)
	if err != nil {
		return nil, err
	}
	if utils.ValueIsEmpty(result) {
		return nil, err
	}
	//获取已分配的属性集合
	var workPlaceNrs []int
	for _, v := range list {
		workPlaceNrs = append(workPlaceNrs, v.WorkPlaceNr)
	}
	unlist, err := lstdao.SelectUnAllot(workPlaceNrs)
	if err != nil {
		return nil, err
	}
	//查询已分配
	result.WorkPlaceValst = list
	//查询未分配
	result.WorkPlaceUnValst = unlist
	return result, nil
}

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

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

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		return err
	}
	dao := dal.NewPersonDAO(session, user.PlantNr, user.UserId)
	record, err := dao.SelectOne(entity.PersonNr)
	if err != nil {
		return err
	}
	if record == nil {
		return grmi.NewBusinessError("不存在指定记录!")
	}
	err = dao.UpdateOne(entity)
	if err != nil {
		session.Rollback()
		return err
	}
	/**处理数据**/
	workPlacePersonValst := make([]model.WorkPlacePersonLst, 0)
	for k, v := range entity.WorkPlaceValst {
		onedata := model.WorkPlacePersonLst{}
		onedata.PersonNr = entity.PersonNr
		onedata.WorkPlaceNr = v.WorkPlaceNr
		onedata.Pos = (k + 1)
		workPlacePersonValst = append(workPlacePersonValst, onedata)
	}
	lstdao := dal.NewWorkPlacePersonLstDAO(session, user.PlantNr, user.UserId)
	err = lstdao.DeleteWhere([]grmi.Predicate{
		meta.WorkPlacePersonLst_PersonNr.NewPredicate(grmi.Equal, entity.PersonNr),
	})
	if err != nil {
		session.Rollback()
		return err
	}
	err = lstdao.Insert(&workPlacePersonValst)
	if err != nil {
		session.Rollback()
		return err
	}
	session.Commit()
	return nil
}

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

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.PersonNr)
		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/PersonService.Delete
 *
 ******************************************************************************/
func (impl *PersonServiceImplement) Delete(user *global.User, entities *[]model.Person) error {

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.PersonNr)
		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/PersonService.Select
 *
 ******************************************************************************/
func (impl *PersonServiceImplement) Select(user *global.User, urlParameters map[string]string) (interface{}, error) {

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

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

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

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

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

	for _, entity := range *entities {
		record, err := dao.SelectOne(entity.PersonNr)
		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/PersonService.CheckLogin
 *
 ******************************************************************************/
func (impl *PersonServiceImplement) CheckLogin(user *global.User, personId string, workPlaceNr string) error {

	grmi.Log(user, "/services/base/implments/Person.service.impl.go", "CheckLogin", "判断登录")

	engine := db.Eloquent.Master()
	session := engine.NewSession()
	defer session.Close()
	dao := dal.NewPersonDAO(session, user.PlantNr, user.UserId)
	workPlaceDao := dal.NewWorkPlaceDAO(session, user.PlantNr, user.UserId)
	personLi, err := dao.Select([]grmi.Predicate{meta.Person_PersonId.NewPredicate(grmi.Equal, personId)}, nil)
	if err != nil {
		return err
	}
	if len(personLi) != 1 {
		return grmi.NewBusinessError("人员信息错误")
	}
	person := personLi[0]
	wpNr, err := strconv.Atoi(workPlaceNr)
	if err != nil {
		return err
	}
	workPlace, err := workPlaceDao.SelectOne(wpNr)
	if err != nil {
		return err
	}
	if workPlace == nil {
		return grmi.NewBusinessError("不存在登录的工位")
	}
	if workPlace.RequireSkillRank1 > person.PersonIPara1 {
		return grmi.NewBusinessError("该人员不符合登录工位的技能等级要求")
	}
	//dao := dal.NewWorkPlacePersonLstDAO(session, user.PlantNr, user.UserId)
	//result, err := dao.SelectPersonByWorkPlace(personId,workPlaceNr)
	//if err != nil {
	//	return err
	//}
	//if utils.ValueIsEmpty(result){
	//	return grmi.NewBusinessError("登录用户和工位不匹配!")
	//}
	/****添加登录记录****/
	history := dal.NewPersonLoginHistoryDAO(session, user.PlantNr, user.UserId)
	entity := model.PersonLoginHistory{}
	entity.PersonNr = person.PersonNr
	entity.WorkPlaceNr = workPlace.WorkPlaceNr
	entity.LoginTime = grmi.DateTime(time.Now())
	err = history.InsertOne(&entity)
	if err != nil {
		return err
	}
	return nil
}

/******************************************************************************
 *
 * @Reference LAPP_ACURA_MOM_BACKEND/services/base/PersonService.SelectOneByUserName
 *
 ******************************************************************************/
func (impl *PersonServiceImplement) SelectOneByUserName(user *global.User, userName string) (*model.Person, error) {

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

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

	record, err := dao.SelectOneByUserName(userName)
	if err != nil || record == nil {
		return nil, err
	}
	return record, nil
}
