package service

import (
	"errors"
	"fmt"
	"strconv"
	"strings"

	"github.com/bytedance/sonic"
	"github.com/go-admin-team/go-admin-core/logger"
	"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"
	"go-admin/common/const/rediskey"
	cDto "go-admin/common/dto"
	commondto "go-admin/common/dto"
	"go-admin/common/helper"
)

type LineApiGroup struct {
	service.Service
}

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

	query := e.Orm.Model(&data)

	if c.ExchangeType != "" {
		query.Where("exchange_type = ?", c.ExchangeType)
	}

	err = query.
		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("LineApiGroupService GetPage error:%s \r\n", err)
		return err
	}

	for j, group := range *list {
		split := strings.Split(group.ApiUserId, ",")
		var (
			aApiUserName string
			bApiUserName string
		)
		for i, s := range split {
			if i == 0 {
				e.Orm.Model(&models.LineApiUser{}).Where("id = ?", s).Select("api_name").Scan(&aApiUserName)
				(*list)[j].AApiName = aApiUserName
			} else {
				e.Orm.Model(&models.LineApiUser{}).Where("id = ?", s).Select("api_name").Scan(&bApiUserName)
				(*list)[j].BApiName = bApiUserName
			}
		}

	}

	return nil
}

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

	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 GetLineApiGroup error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

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

	SetApiGroupCache(data)

	return nil
}

func SetApiGroupCache(data models.LineApiGroup) {
	apiUserId := 0
	childApiUserId := 0
	ids := strings.Split(data.ApiUserId, ",")

	if len(ids) == 2 {
		apiUserId, _ = strconv.Atoi(ids[0])
		childApiUserId, _ = strconv.Atoi(ids[1])

		groupCache := commondto.ApiGroupDto{
			Id:             data.Id,
			Name:           data.GroupName,
			ApiUserId:      apiUserId,
			ChildApiUserId: childApiUserId,
		}

		groupVal, _ := sonic.MarshalString(&groupCache)

		if groupVal != "" {
			if err := helper.DefaultRedis.SetString(fmt.Sprintf(rediskey.ApiGroup, data.Id), groupVal); err != nil {
				logger.Errorf("api group redis set error:%s", err)
			}
		}

		SaveApiInfo(apiUserId, data.Id)
		SaveApiInfo(childApiUserId, data.Id)
	}
}

func SaveApiInfo(apiUserId int, groupId int) {
	apiInfoVal, _ := helper.DefaultRedis.GetString(fmt.Sprintf(rediskey.API_USER, apiUserId))
	var data models.LineApiUser

	if apiInfoVal != "" {
		_ = sonic.UnmarshalString(apiInfoVal, &data)

		if data.Id > 0 {
			data.GroupId = int64(groupId)
		}

		apiInfoVal, _ := sonic.MarshalString(&data)

		if apiInfoVal != "" {
			if err := helper.DefaultRedis.SetString(fmt.Sprintf(rediskey.API_USER, apiUserId), apiInfoVal); err != nil {
				logger.Errorf("api user redis set error:%s", err)
			}
		}
	}
}

// Update 修改LineApiGroup对象
func (e *LineApiGroup) Update(c *dto.LineApiGroupUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = models.LineApiGroup{}
	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("LineApiGroupService Save error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}

	SetApiGroupCache(data)

	return nil
}

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

	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 RemoveLineApiGroup error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	userIds := make([]models.LineApiUser, 0)
	e.Orm.Model(&models.LineApiUser{}).Where("group_id in  ?  ", d.GetId()).Select("id").Find(&userIds)

	e.Orm.Model(&models.LineApiUser{}).Where("group_id in  ?  ", d.GetId()).Updates(map[string]interface{}{
		"subordinate": "0",
		"group_id":    0,
	})

	keys := make([]string, 0)
	for _, id := range d.Ids {
		key := fmt.Sprintf(rediskey.ApiGroup, id)
		keys = append(keys, key)
	}
	if _, err := helper.DefaultRedis.BatchDeleteKeys(keys); err != nil {
		e.Log.Error("删除用户组失败,err:", err)
	}

	for _, item := range userIds {
		if item.Id == 0 {
			continue
		}

		SaveApiInfo(item.Id, 0)
	}

	return nil
}
