package card_redeem_account

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

	"github.com/duke-git/lancet/v2/slice"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gmlock"
	"github.com/gogf/gf/v2/text/gstr"
)

func (a *sCardRedeemAccount) GroupAdd(ctx context.Context, input *model.RedeemAccountGroup, tx gdb.TX) (id int64, err error) {
	m := dao.V1CardRedeemAccountGroup.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	id, err = m.InsertAndGetId(do.V1CardRedeemAccountGroup{
		Name:          input.Name,
		CreatedUserId: input.CreatedUserId,
		Category:      input.Category,
		Notes:         input.Notes,
	})
	return
}

// GroupAddOrGetId 如果没有这个分组，就新建分组，否则返回这个分组的id
func (a *sCardRedeemAccount) GroupAddOrGetId(ctx context.Context, input *model.RedeemAccountGroup, tx gdb.TX) (id int64, err error) {
	gmlock.Lock("RedeemAccountGroupAddOrGetId")
	defer gmlock.Unlock("RedeemAccountGroupAddOrGetId")
	m := dao.V1CardRedeemAccountGroup.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	data := entity.V1CardRedeemAccountGroup{}
	_ = m.Where(dao.V1CardRedeemAccountGroup.Columns().Name, gstr.TrimAll(input.Name)).Scan(&data)
	if data.Id == 0 {
		id, err = a.GroupAdd(ctx, input, tx)
		if err != nil {
			return 0, err
		}
		return id, nil
	}
	return int64(data.Id), nil
}

// GroupCheck 判断当前用户上传的name分组是不是已经存在
func (a *sCardRedeemAccount) GroupCheck(ctx context.Context, name string, createdUserId string, tx gdb.TX) (isExist bool, err error) {
	m := dao.V1CardRedeemAccountGroup.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	isExist, err = m.Where(dao.V1CardRedeemAccountGroup.Columns().Name, name).Where(dao.V1CardRedeemAccountGroup.Columns().CreatedUserId, createdUserId).Exist()
	return
}

// GroupUpdate 添加修改函数
func (a *sCardRedeemAccount) GroupUpdate(ctx context.Context, input *model.RedeemAccountGroup, id uint, tx gdb.TX) (err error) {
	m := dao.V1CardRedeemAccountGroup.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	_, err = m.Where(dao.V1CardRedeemAccountGroup.Columns().Id, id).Update(do.V1CardRedeemAccountGroup{
		Name:  input.Name,
		Notes: input.Notes,
	})
	return
}

// GroupList 查询分组列表
func (a *sCardRedeemAccount) GroupList(ctx context.Context, input *model.RedeemAccountGroupList, tx gdb.TX) (total int, data []*entity.V1CardRedeemAccountGroup, err error) {
	data = []*entity.V1CardRedeemAccountGroup{}
	m := dao.V1CardRedeemAccountGroup.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	if input.CreatedUserId != "" {
		m = m.Where(dao.V1CardRedeemAccountGroup.Columns().CreatedUserId, input.CreatedUserId)
	}
	if input.Name != "" {
		m = m.WhereLike(dao.V1CardRedeemAccountGroup.Columns().Name, utils.OrmLike(input.Name))
	}
	err = m.Where(dao.V1CardRedeemAccountGroup.Columns().Category, input.Category).
		Page(input.Current, input.PageSize).
		OrderDesc(dao.V1CardRedeemAccountGroup.Columns().CreatedAt).ScanAndCount(&data, &total, false)
	return
}

// GroupAll 查询分组列表
func (a *sCardRedeemAccount) GroupAll(ctx context.Context, input *model.RedeemAccountGroupAll, tx gdb.TX) (total int, data []*entity.V1CardRedeemAccountGroup, err error) {
	data = []*entity.V1CardRedeemAccountGroup{}
	m := dao.V1CardRedeemAccountGroup.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	if input.CreatedUserId != "" {
		m = m.Where(dao.V1CardRedeemAccountGroup.Columns().CreatedUserId, input.CreatedUserId)
	}
	if len(input.GroupIds) > 0 {
		m = m.WhereIn(dao.V1CardRedeemAccountGroup.Columns().Id, input.GroupIds)
	}
	err = m.Where(dao.V1CardRedeemAccountGroup.Columns().Category, input.Category).
		OrderDesc(dao.V1CardRedeemAccountGroup.Columns().CreatedAt).ScanAndCount(&data, &total, false)
	return
}

// GroupDelete 删除某个分组
func (a *sCardRedeemAccount) GroupDelete(ctx context.Context, id uint, createdUserId string, tx gdb.TX) (err error) {
	m := dao.V1CardRedeemAccountGroup.Ctx(ctx).DB(config.GetDatabaseV1()).
		Where(dao.V1CardRedeemAccountGroup.Columns().CreatedUserId, createdUserId)
	if tx != nil {
		m = m.TX(tx)
	}
	_, _ = m.Where(dao.V1CardRedeemAccountGroup.Columns().Id, id).Delete()
	//清空账号关联
	m2 := dao.V1CardRedeemAccountInfo.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m2 = m2.TX(tx)
	}
	_, err = m2.Where(dao.V1CardRedeemAccountInfo.Columns().GroupId, id).Where(dao.V1CardRedeemAccountInfo.Columns().CreateUserId, createdUserId).
		Update(g.Map{
			dao.V1CardRedeemAccountInfo.Columns().GroupId: nil,
		})
	return
}

// GroupStatsOverview 获取分组统计概览
func (a *sCardRedeemAccount) GroupStatsOverview(ctx context.Context, input *model.RedeemAccountGroupStatsOverviewReq, tx gdb.TX) (output *model.RedeemAccountGroupStatsOverviewRes, err error) {
	m := dao.V1CardRedeemAccountInfo.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	if input.AccountId != "" {
		m = m.Where(dao.V1CardRedeemAccountInfo.Columns().Id, input.AccountId)
	}
	if input.GroupId != 0 {
		m = m.Where(dao.V1CardRedeemAccountInfo.Columns().GroupId, input.GroupId)
	}
	if input.DateRange != nil && len(input.DateRange) == 2 {
		m = m.WhereBetween(dao.V1CardRedeemAccountInfo.Columns().CreatedAt, input.DateRange[0], input.DateRange[1])
	}
	if input.Category != "" {
		m = m.Where(dao.V1CardRedeemAccountInfo.Columns().Category, input.Category)
	}
	if input.UserId != "" {
		m = m.Where(dao.V1CardRedeemAccountInfo.Columns().CreateUserId, input.UserId)
	}
	// 账号个数
	accountList := []*entity.V1CardRedeemAccountInfo{}
	totalAccount := 0
	err = m.ScanAndCount(&accountList, &totalAccount, false)
	if err != nil {
		return nil, err
	}

	// 账号个数（包含已删除）
	totalAccountWithDelete, err := m.Unscoped().Count()
	if err != nil {
		return nil, err
	}

	totalAccountIds := slice.Map(accountList, func(index int, item *entity.V1CardRedeemAccountInfo) string {
		return item.Id
	})

	m = dao.V1CardRedeemOrderInfo.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	if input.UserId != "" {
		m = m.Where(dao.V1CardRedeemOrderInfo.Columns().CreatedUserId, input.UserId)
	}
	if input.GroupId != 0 {
		m = m.WhereIn(dao.V1CardRedeemOrderInfo.Columns().AccountId, totalAccountIds)
	}
	if input.AccountId != "" {
		m = m.Where(dao.V1CardRedeemOrderInfo.Columns().AccountId, input.AccountId)
	}
	if input.DateRange != nil && len(input.DateRange) == 2 {
		m = m.WhereBetween(dao.V1CardRedeemOrderInfo.Columns().CreatedAt, input.DateRange[0], input.DateRange[1])
	}
	if input.Category != "" {
		m = m.Where(dao.V1CardRedeemAccountInfo.Columns().Category, input.Category)
	}

	totalOrderCount, err := m.Count()
	if err != nil {
		return nil, err
	}
	totalOrderAmount, err := m.Sum(dao.V1CardRedeemOrderInfo.Columns().ActualAmount)
	if err != nil {
		return nil, err
	}
	totalOrderCountSuccess, err := m.WhereIn(dao.V1CardRedeemAccountInfo.Columns().Status, []consts.RedeemOrderStatus{consts.RedeemOrderSuccessWithDifferentAmount, consts.RedeemOrderSuccess}).Count()
	if err != nil {
		return nil, err
	}
	totalOrderAmountSuccess, err := m.WhereIn(dao.V1CardRedeemAccountInfo.Columns().Status, []consts.RedeemOrderStatus{consts.RedeemOrderSuccessWithDifferentAmount, consts.RedeemOrderSuccess}).Sum(dao.V1CardRedeemOrderInfo.Columns().ActualAmount)
	if err != nil {
		return nil, err
	}

	return &model.RedeemAccountGroupStatsOverviewRes{
		TotalActiveAccountCount: totalAccount,
		TotalAccountCount:       totalAccountWithDelete,
		TotalOrderAmount:        totalOrderAmount,
		TotalOrderCount:         totalOrderCount,
		TotalOrderCountSuccess:  totalOrderCountSuccess,
		TotalOrderAmountSuccess: totalOrderAmountSuccess,
	}, nil
}
