package card_apple_account

import (
	"context"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/net/gtrace"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gtime"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/trace"
	"kami/internal/consts"
	"kami/internal/dao"
	"kami/internal/model/do"
	"kami/internal/model/entity"
	"kami/utility/config"
	"kami/utility/integration/apple"
	"math"
)

func (a *sAppleAccount) CronHealthCheck(ctx context.Context) {
	m := dao.V1CardAppleAccountInfo.Ctx(ctx).DB(config.GetDatabaseV1()).Where(dao.V1CardAppleAccountInfo.Columns().Status, consts.AppleAccountNormal)
	count, _ := m.Count()
	if count <= 0 {
		return
	}
	tracer2 := gtrace.NewTracer("sAppleOrder.CronHealthCheck")
	ctx, span := tracer2.Start(ctx, "CronHealthCheck", trace.WithNewRoot(), trace.WithLinks(trace.LinkFromContext(ctx)))
	defer span.End()
	for i := 0; i < int(math.Ceil(float64(count)/100.0)); i++ {
		var accountInfos []*entity.V1CardAppleAccountInfo
		_ = m.Page(i+1, 100).Scan(&accountInfos)
		for _, accountInfo := range accountInfos {
			span.AddEvent("处理账号", trace.WithAttributes(attribute.String("account", accountInfo.Account)))
			resp, err := apple.NewClient().Heartbeat(ctx, &apple.HeartBeatReq{
				Account:  accountInfo.Account,
				Password: accountInfo.Password,
				OrderId:  accountInfo.Id,
			})
			if err != nil {
				span.AddEvent("请求错误", trace.WithAttributes(attribute.String("error", err.Error())))
				glog.Error(ctx, "请求错误", err)
				continue
			}
			span.AddEvent("请求结果", trace.WithAttributes(attribute.String("code", resp.Code.String())))
			if resp.Code == apple.CodeApplePasswordError {
				_ = a.ModifyStatus(ctx, accountInfo.Id, consts.AppleAccountWrongPassword, nil)
			}
		}
	}
}

// CronResetStatus 重置账号状态
func (a *sAppleAccount) CronResetStatus(ctx context.Context, tx gdb.TX) (err error) {
	m := dao.V1CardAppleAccountInfo.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	err = m.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		// 所有账户今日交易量和交易订单金额清零
		if _, err2 := m.Update(do.V1CardAppleAccountInfo{
			TodayRechargeAmount: 0,
			TodayRechargeCount:  0,
		}); err2 != nil {
			return err2
		}
		return nil
		// 所有交易满额的账户取消限制
		//_, err2 := m.Where(dao.V1CardAppleAccountInfo.Columns().Status, consts.AppleAccountLimited).
		//	Update(do.V1CardAppleAccountInfo{
		//		Status: consts.AppleAccountNormal,
		//	})
		//return err2
	})
	return
}

// CronHandleTmpStoppedList 处理临时暂停账号
func (a *sAppleAccount) CronHandleTmpStoppedList(ctx context.Context) (err error) {
	//临时暂停的账号处理
	_, err = dao.V1CardAppleAccountInfo.Ctx(ctx).DB(config.GetDatabaseV1()).
		Where(dao.V1CardAppleAccountInfo.Columns().Status, consts.AppleAccountTmpStoppedByTooManyRequest).
		WhereLT(dao.V1CardAppleAccountInfo.Columns().UpdatedAt, gtime.Now().Add(-2*gtime.M)).
		Update(do.V1CardAppleAccountInfo{
			Status: consts.AppleAccountNormal,
		})
	//充值过快的账号处理
	_, err = dao.V1CardAppleAccountInfo.Ctx(ctx).DB(config.GetDatabaseV1()).
		Where(dao.V1CardAppleAccountInfo.Columns().Status, consts.AppleAccountTmpLimited).
		WhereLT(dao.V1CardAppleAccountInfo.Columns().UpdatedAt, gtime.Now().Add(-gtime.M)).
		Update(do.V1CardAppleAccountInfo{
			Status: consts.AppleAccountNormal,
		})
	return
}
