package sys_user_channel_config

import (
	"context"
	"kami/internal/consts"
	"kami/internal/dao"
	"kami/internal/model/do"
	"kami/internal/model/entity"
	"kami/internal/service"
	"kami/utility/config"
	"kami/utility/utils"
)

func init() {
	service.RegisterSysUserChannelConfig(New())
}

type sSysUserChannelConfig struct {
}

func New() *sSysUserChannelConfig {
	return &sSysUserChannelConfig{}
}

// GetAll 获取所有用户渠道配置
func (c *sSysUserChannelConfig) GetAll(ctx context.Context) (data []*entity.V1SysUserConfigChannel, err error) {
	data = make([]*entity.V1SysUserConfigChannel, 0)
	err = dao.V1SysUserConfigChannel.Ctx(ctx).DB(config.GetDatabaseV1()).Scan(&data)
	err = utils.HandleNoRowsError(err)
	return
}

// GetOneByUserID 根据用户ID获取用户渠道配置
func (c *sSysUserChannelConfig) GetOneByUserID(ctx context.Context, userID string) (data *entity.V1SysUserConfigChannel, err error) {
	err = dao.V1SysUserConfigChannel.Ctx(ctx).DB(config.GetDatabaseV1()).Where(dao.V1SysUserConfigChannel.Columns().SysUserId, userID).Scan(&data)
	err = utils.HandleNoRowsError(err)
	return
}

// GetOneByChannelID 根据渠道ID获取用户渠道配置
func (c *sSysUserChannelConfig) GetOneByChannelID(ctx context.Context, channelName consts.CardRedeemAccountCategory, userID string) (data *entity.V1SysUserConfigChannel, err error) {
	err = dao.V1SysUserConfigChannel.Ctx(ctx).DB(config.GetDatabaseV1()).Where(dao.V1SysUserConfigChannel.Columns().Name, channelName).
		Where(dao.V1SysUserConfigChannel.Columns().SysUserId, userID).
		Scan(&data)
	err = utils.HandleNoRowsError(err)
	return
}

// DeleteOne 删除用户渠道配置
func (c *sSysUserChannelConfig) DeleteOne(ctx context.Context, userID string, channelName consts.CardRedeemAccountCategory) (err error) {
	_, err = dao.V1SysUserConfigChannel.Ctx(ctx).DB(config.GetDatabaseV1()).Where(dao.V1SysUserConfigChannel.Columns().SysUserId, userID).
		Where(dao.V1SysUserConfigChannel.Columns().Name, channelName).Delete()
	return
}

// Init 新建用户后初始化用户渠道配置
func (c *sSysUserChannelConfig) Init(ctx context.Context, userID string) (err error) {
	for _, channel := range consts.ChannelTypeList {
		_, err = dao.V1SysUserConfigChannel.Ctx(ctx).DB(config.GetDatabaseV1()).Insert(&do.V1SysUserConfigChannel{
			SysUserId: userID,
			Name:      channel,
			Num:       consts.DefaultExchangeConcurrentNum,
		})
		if err != nil {
			return
		}
	}
	return
}

// AddOrUpdateOne 添加一个用户渠道配置
func (c *sSysUserChannelConfig) AddOrUpdateOne(ctx context.Context, userID string, channelName consts.CardRedeemAccountCategory, num int) (err error) {
	_, err = dao.V1SysUserConfigChannel.Ctx(ctx).DB(config.GetDatabaseV1()).
		OnDuplicate(dao.V1SysUserConfigChannel.Columns().Num, dao.V1SysUserConfigChannel.Columns().UpdatedAt).
		Save(&do.V1SysUserConfigChannel{
			SysUserId: userID,
			Name:      channelName,
			Num:       num,
		})
	return
}
