package service

import (
	"errors"
	"strconv"

	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"

	"go-admin/app/operate/models"
	"go-admin/app/operate/service/dto"
	"go-admin/common/actions"
	cDto "go-admin/common/dto"
)

type OrgTeamUser struct {
	service.Service
}

// GetPage 获取OrgTeamUser列表
func (e *OrgTeamUser) GetPage(c *dto.OrgTeamUserGetPageReq, p *actions.DataPermission, list *[]dto.OrgTeamUserGetPageReply, count *int64) error {
	var err error
	var data models.OrgTeamUser
	field := "otu.id, oc.club_name, ot.team_name, otu.name, otu.sex, sr.role_name, su.status"

	err = e.Orm.Table("org_team_user as otu").
		Select(field).
		Joins("left join org_team as ot on otu.team_id=ot.id").
		Joins("left join org_club as oc on otu.club_id=oc.id").
		Joins("left join sys_user as su on otu.user_id=su.user_id").
		Joins("left join sys_role as sr on su.role_id=sr.role_id").
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
			cDto.PassDel("otu"),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("OrgTeamUserService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

// Get 获取OrgTeamUser对象
func (e *OrgTeamUser) Get(d *dto.OrgTeamUserGetReq, p *actions.DataPermission, model *dto.OrgTeamUserGetReply) error {
	field := "otu.id,oc.club_name, otu.team_id, ot.team_name, otu.name, otu.sex, otu.user_img, otu.sign_img, sr.role_id, sr.role_name, su.username, su.status"

	err := e.Orm.Table("org_team_user as otu").
		Select(field).
		Joins("left join org_team as ot on otu.team_id=ot.id").
		Joins("left join org_club as oc on otu.club_id=oc.id").
		Joins("left join sys_user as su on otu.user_id=su.user_id").
		Joins("left join sys_role as sr on su.role_id=sr.role_id").
		First(model, d.GetId()).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service GetOrgTeamUser error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// Insert 创建OrgTeamUser对象
func (e *OrgTeamUser) Insert(c *dto.OrgTeamUserInsertReq) error {
	var err error
	var data models.OrgTeamUser
	c.Generate(&data)
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("OrgTeamUserService Insert error:%s \r\n", err)
		return err
	}

	c.Id = data.Id
	return nil
}

// Update 修改OrgTeamUser对象
func (e *OrgTeamUser) Update(c *dto.OrgTeamUserUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = models.OrgTeamUser{}
	e.Orm.Scopes(
		actions.Permission(data.TableName(), p),
	).First(&data, c.GetId())
	userId := data.UserId
	c.Generate(&data)
	db := e.Orm.Updates(&data)
	if db.Error != nil {
		e.Log.Errorf("OrgTeamUserService Save error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}

	c.UserId = userId
	return nil
}

// Remove 删除OrgTeamUser
func (e *OrgTeamUser) Remove(d *dto.OrgTeamUserDeleteReq, p *actions.DataPermission) error {
	var data models.OrgTeamUser

	db := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).Delete(&data, d.GetId())
	if err := db.Error; err != nil {
		e.Log.Errorf("Service RemoveOrgTeamUser error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

// GetPage 获取OrgTeamUser列表
func (e *OrgTeamUser) GetUserIds(ids []int) (error, []int) {
	list := make([]models.OrgTeamUser, 0)
	field := "user_id"

	e.Orm.Select(field).Where("id IN(?)", ids).Find(&list)

	userIds := make([]int, 0)
	userid := 0
	for _, v := range list {
		userid, _ = strconv.Atoi(v.UserId)
		userIds = append(userIds, userid)
	}
	return nil, userIds
}

// 根据teamId获取userId
func (e *OrgTeamUser) GetClubId(teamId string) (error, string) {
	data := new(models.OrgTeam)

	err := e.Orm.Table("org_team").
		Select("club_id").
		Where("id=?", teamId).
		First(&data).Error
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err, ""
	}
	return nil, data.ClubId
}

// 根据userId获取teamId
func (e *OrgTeamUser) GetTeamId(userId int) (error, string) {
	data := new(models.OrgTeamUser)

	err := e.Orm.Table("org_team_user").
		Select("team_id").
		Where("user_id=?", userId).
		First(&data).Error
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err, ""
	}
	return nil, data.TeamId
}

// 根据工作人员id获取userId
func (e *OrgTeamUser) GetUserId(teamUserId int) (error, string) {
	data := new(models.OrgTeamUser)

	err := e.Orm.Table("org_team_user").
		Select("user_id").
		Where("id=?", teamUserId).
		First(&data).Error
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err, ""
	}
	return nil, data.UserId
}

func (e *OrgTeamUser) GetParentDeptId(teamId string) (error, int) {
	data := dto.Dept{}

	err := e.Orm.Table("org_team_dept").
		Select("dept_id").
		Where("team_id=?", teamId).
		First(&data).Error
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err, 0
	}
	return nil, data.DeptId
}

// 根据userId获取teamId
func (e *OrgTeamUser) GetTeamUser(userId int) (error, *models.OrgTeamUser) {
	data := new(models.OrgTeamUser)

	err := e.Orm.Table("org_team_user").
		Select("*").
		Where("user_id=?", userId).
		First(&data).Error
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err, nil
	}
	return nil, data
}
