package service

import (
	"errors"
	"strconv"
	"strings"

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

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

type LineApiUserGroup struct {
	service.Service
}

// GetPage 获取LineApiUserGroup列表
func (e *LineApiUserGroup) GetPage(c *dto.LineApiUserGroupGetPageReq, p *actions.DataPermission, list *[]models.LineApiUserGroup, count *int64) error {
	var err error
	var data models.LineApiUserGroup

	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("LineApiUserGroupService GetPage error:%s \r\n", err)
		return err
	}

	for index := range *list {
		userIds := strings.Split((*list)[index].UserId, ",")
		var filteredUserIds []string
		for _, id := range userIds {
			if id != "" {
				filteredUserIds = append(filteredUserIds, id)
			}
		}

		(*list)[index].Count = len(filteredUserIds)
	}

	return nil
}

// Get 获取LineApiUserGroup对象
func (e *LineApiUserGroup) Get(d *dto.LineApiUserGroupGetReq, p *actions.DataPermission, model *models.LineApiUserGroup) error {
	var data models.LineApiUserGroup

	err := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).
		First(model, d.GetId()).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service GetLineApiUserGroup error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}

	userIds := []int{}

	for _, userId := range strings.Split(model.UserId, ",") {
		if userId == "" {
			continue
		}
		userIds = append(userIds, utility.ToInt(userId))
	}
	model.UserIds = userIds

	return nil
}

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

// Update 修改LineApiUserGroup对象
func (e *LineApiUserGroup) Update(c *dto.LineApiUserGroupUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = models.LineApiUserGroup{}
	e.Orm.Scopes(
		actions.Permission(data.TableName(), p),
	).First(&data, c.GetId())
	c.Generate(&data)

	db := e.Orm.Save(&data)
	if err = db.Error; err != nil {
		e.Log.Errorf("LineApiUserGroupService Save error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}
	return nil
}

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

	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 RemoveLineApiUserGroup error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

func (e *LineApiUserGroup) GetOptions(req *dto.LineApiUserGroupGetOptionsReq, data *[]dto.LineApiUserGroupOptions, p *actions.DataPermission) error {
	var err error
	var items []models.LineApiUserGroup

	e.Orm.Model(&models.LineApiUserGroup{}).
		Where("exchange_type =?", req.ExchangeType).
		Scopes(
			actions.Permission(models.LineApiUserGroup{}.TableName(), p),
		).Find(&items)

	for _, item := range items {
		ids := []int{}
		userIds := strings.Split(item.UserId, ",")

		for _, id := range userIds {
			val, _ := strconv.Atoi(id)
			ids = append(ids, val)
		}

		*data = append(*data, dto.LineApiUserGroupOptions{
			Label:    item.GroupName,
			Id:       item.Id,
			Value:    ids,
			Disabled: item.Status != 1,
		})
	}
	return err
}
