package admin_agent

import (
	"context"
	"qnc-server/common/globalkey"
	"qnc-server/common/xerr"
	"qnc-server/pkg/lzkit/crypto"

	"github.com/pkg/errors"

	"qnc-server/app/main/api/internal/svc"
	"qnc-server/app/main/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminGetAgentRealNameListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAdminGetAgentRealNameListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetAgentRealNameListLogic {
	return &AdminGetAgentRealNameListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminGetAgentRealNameListLogic) AdminGetAgentRealNameList(req *types.AdminGetAgentRealNameListReq) (resp *types.AdminGetAgentRealNameListResp, err error) {
	builder := l.svcCtx.AgentRealNameModel.SelectBuilder().
		Where("del_state = ?", globalkey.DelStateNo)

	if req.AgentId != nil {
		builder = builder.Where("agent_id = ?", *req.AgentId)
	}
	if req.Status != nil {
		// 根据状态过滤：1=未验证（verify_time为NULL），2=已通过（verify_time不为NULL）
		switch *req.Status {
		case 1: // 未验证
			builder = builder.Where("verify_time IS NULL")
		case 2: // 已通过
			builder = builder.Where("verify_time IS NOT NULL")
		}
	}

	// 分页查询
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 20
	}

	realNames, total, err := l.svcCtx.AgentRealNameModel.FindPageListByPageWithTotal(l.ctx, builder, page, pageSize, "create_time DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询实名认证列表失败, %v", err)
	}

	// 组装响应
	items := make([]types.AgentRealNameListItem, 0, len(realNames))
	for _, realName := range realNames {
		// 解密手机号（仅显示部分）
		mobile := ""
		if realName.Mobile != "" {
			decrypted, err := crypto.DecryptMobile(realName.Mobile, l.svcCtx.Config.Encrypt.SecretKey)
			if err == nil {
				mobile = decrypted
			}
		}

		// 解密身份证号（仅显示部分）
		idCard := ""
		if realName.IdCard != "" {
			decrypted, err := crypto.DecryptIDCard(realName.IdCard, []byte(l.svcCtx.Config.Encrypt.SecretKey))
			if err == nil {
				// 脱敏显示
				if len(decrypted) > 10 {
					idCard = decrypted[:3] + "***********" + decrypted[len(decrypted)-4:]
				} else {
					idCard = decrypted
				}
			}
		}

		// 根据verify_time判断状态：NULL=未验证(1)，不为NULL=已通过(2)
		statusInt := int64(1) // 默认未验证
		verifyTime := ""
		if realName.VerifyTime.Valid {
			statusInt = 2 // 已通过
			verifyTime = realName.VerifyTime.Time.Format("2006-01-02 15:04:05")
		}

		item := types.AgentRealNameListItem{
			Id:         realName.Id,
			AgentId:    realName.AgentId,
			Name:       realName.Name,
			IdCard:     idCard,
			Mobile:     mobile,
			Status:     statusInt,
			CreateTime: realName.CreateTime.Format("2006-01-02 15:04:05"),
		}
		// TODO: 重新生成接口后，取消注释下面的代码
		item.VerifyTime = verifyTime
		items = append(items, item)
	}

	return &types.AdminGetAgentRealNameListResp{
		Total: total,
		Items: items,
	}, nil
}
