package camel_oil

import (
	"context"
	v1 "kami/api/camel_oil/v1"
	"kami/internal/consts"
	"kami/internal/dao"
	"kami/internal/model/entity"
	"kami/utility/config"

	"github.com/gogf/gf/v2/os/glog"
)

// ====================================================================================
// 账号历史记录查询
// ====================================================================================

// GetAccountHistory 获取账号历史记录
func (s *sCamelOil) GetAccountHistory(ctx context.Context, req *v1.AccountHistoryReq) (res *v1.AccountHistoryRes, err error) {
	// 1. 构建查询
	m := dao.V1CamelOilAccountHistory.Ctx(ctx).DB(config.GetDatabaseV1())
	m = m.Where(dao.V1CamelOilAccountHistory.Columns().AccountId, req.AccountId)

	// 2. 查询总数
	total, err := m.Count()
	if err != nil {
		glog.Error(ctx, "查询账号历史记录总数失败", err)
		return nil, err
	}

	// 3. 查询列表
	var histories []*entity.V1CamelOilAccountHistory
	err = m.Page(req.Current, req.PageSize).
		OrderDesc(dao.V1CamelOilAccountHistory.Columns().Id).
		Scan(&histories)

	if err != nil {
		glog.Error(ctx, "查询账号历史记录列表失败", err)
		return nil, err
	}

	// 4. 组装响应数据
	items := make([]v1.AccountHistoryItem, 0, len(histories))
	for _, history := range histories {
		items = append(items, v1.AccountHistoryItem{
			AccountId:    history.AccountId,
			ChangeType:   consts.CamelOilAccountChangeType(history.ChangeType),
			ChangeText:   getAccountChangeTypeText(history.ChangeType),
			StatusBefore: consts.CamelOilAccountStatus(history.StatusBefore),
			StatusAfter:  consts.CamelOilAccountStatus(history.StatusAfter),
			FailureCount: history.FailureCount,
			Remark:       history.Remark,
			CreatedAt:    history.CreatedAt,
		})
	}

	res = &v1.AccountHistoryRes{}
	res.List = items
	res.Total = total

	return res, nil
}

// getAccountChangeTypeText 获取账号变更类型文本
func getAccountChangeTypeText(changeType string) string {
	changeTypeMap := map[string]string{
		"create":         "创建账号",
		"login":          "登录成功",
		"offline":        "检测到掉线",
		"login_fail":     "登录失败",
		"pause":          "暂停使用（订单数达到10）",
		"resume":         "恢复使用（次日重置）",
		"invalidate":     "账号失效（单日下单不足10个）",
		"order_bind":     "绑定订单",
		"order_complete": "订单完成",
		"update":         "更新账号信息",
		"delete":         "删除账号",
	}

	if text, ok := changeTypeMap[changeType]; ok {
		return text
	}
	return changeType
}
