package card_apple_account

import (
	"context"
	"kami/api/commonApi"
	"kami/utility/utils"

	"github.com/duke-git/lancet/v2/slice"
	"github.com/gogf/gf/v2/os/glog"

	"kami/internal/dao"
	"kami/internal/model"
	"kami/internal/model/do"
	"kami/internal/model/entity"
	"kami/utility/config"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
)

// AddWalletHistory 添加账户历史明细
func (a *sAppleAccount) AddWalletHistory(ctx context.Context, input model.AppleCardAccountHistoryInput, tx gdb.TX) (err error) {
	m := dao.V1CardAppleAccountInfoHistory.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	err = m.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		m2 := dao.V1CardAppleAccountInfo.Ctx(ctx).TX(tx).DB(config.GetDatabaseV1()).
			WherePri(input.AccountId)
		accountEntity := entity.V1CardAppleAccountInfo{}
		if err2 := m2.Scan(&accountEntity); err2 != nil {
			return err2
		}
		if accountEntity.Id == "" {
			err = gerror.NewCode(gcode.CodeNotFound)
		}
		_, err2 := m.TX(tx).Insert(do.V1CardAppleAccountInfoHistory{
			AccountId:                  accountEntity.Id,
			OrderNo:                    input.OrderNo,
			Amount:                     input.Amount,
			AccountName:                accountEntity.Account,
			CreatedUserId:              input.CreatedUserId,
			BalanceBeforeItunes:        input.BalanceFromItunes - input.Amount,
			BalanceAfterItunes:         input.BalanceFromItunes,
			BalanceBeforeAutoIncrement: accountEntity.Balance,
			BalanceAfterAutoIncrement:  accountEntity.Balance + input.Amount,
			TransactionType:            input.TransactionType,
			Description:                input.Description,
		})
		return err2
	})
	return
}

// GetWalletHistory 获取单账户钱包明细
func (a *sAppleAccount) GetWalletHistory(ctx context.Context, input model.CardAppleAccountHistoryQueryInput) (total int, data []entity.V1CardAppleAccountInfoHistory, err error) {
	data = make([]entity.V1CardAppleAccountInfoHistory, 0)
	m := dao.V1CardAppleAccountInfoHistory.Ctx(ctx).DB(config.GetDatabaseV1())
	if input.AccountId != "" {
		m = m.Where(dao.V1CardAppleAccountInfoHistory.Columns().AccountId, input.AccountId)
	}
	if input.AccountName != "" {
		m = m.WhereLike(dao.V1CardAppleAccountInfoHistory.Columns().AccountName, utils.OrmLike(input.AccountName))
	}
	if input.UserId != "" {
		_, list, _ := a.ListUnscoped(ctx, &model.CardInfoParamsInput{
			UploadUserId: input.UserId,
		})
		ids := slice.Map(list, func(index int, item model.AppleAccountListOutput) string {
			return item.Id
		})
		m = m.WhereIn(dao.V1CardAppleAccountInfoHistory.Columns().AccountId, ids)
	}
	err = m.Page(input.Current, input.PageSize).
		OrderDesc(dao.V1CardAppleAccountInfoHistory.Columns().CreatedAt).
		ScanAndCount(&data, &total, false)
	return
}

// CheckWalletHistoryNormal 检查账户流水是否跟iTunes余额一致，如果不一致，就手动添加添加差额
func (a *sAppleAccount) CheckWalletHistoryNormal(ctx context.Context, accountId string) {
	dataList := make([]entity.V1CardAppleAccountInfoHistory, 0)
	if err := dao.V1CardAppleAccountInfoHistory.Ctx(ctx).DB(config.GetDatabaseV1()).
		Where(dao.V1CardAppleAccountInfoHistory.Columns().AccountId, accountId).
		OrderAsc(dao.V1CardAppleRechargeInfo.Columns().CreatedAt).
		Scan(&dataList); err != nil {
		glog.Error(ctx, "检查用户钱包错误", err)
	}
	if len(dataList) <= 1 {
		return
	}
	//itunes刚添加时候余额
	baseItunes := dataList[0].BalanceAfterItunes - dataList[0].Amount
	needCheckData := dataList[len(dataList)-1]
	//如果自然充值金额比itunes充值金额大，就把差额添加进去
	if (needCheckData.BalanceAfterItunes - needCheckData.BalanceAfterAutoIncrement) > baseItunes {
		if _, err := a.AddWalletAmount(ctx, &model.AppleCardWalletInfo{
			Amount:            needCheckData.BalanceAfterItunes - needCheckData.BalanceAfterAutoIncrement - baseItunes,
			BalanceFromItunes: needCheckData.BalanceAfterItunes,
			Remark:            "余额自动矫正，如有问题，请联系管理员查单",
			CommonStrId: commonApi.CommonStrId{
				ID: accountId,
			},
		}, nil); err != nil {
			glog.Error(ctx, "添加到用户余额错误", err)
		}
	}
}
