package admin_platform_user

import (
	"context"
	"database/sql"
	"fmt"

	"qnc-server/app/main/api/internal/svc"
	"qnc-server/app/main/api/internal/types"
	"qnc-server/common/xerr"
	"qnc-server/pkg/lzkit/crypto"

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

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

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

func (l *AdminGetPlatformUserListLogic) AdminGetPlatformUserList(req *types.AdminGetPlatformUserListReq) (resp *types.AdminGetPlatformUserListResp, err error) {
	builder := l.svcCtx.UserModel.SelectBuilder()
	if req.Mobile != "" {
		builder = builder.Where("mobile = ?", req.Mobile)
	}
	if req.Nickname != "" {
		builder = builder.Where("nickname = ?", req.Nickname)
	}
	if req.Inside != 0 {
		builder = builder.Where("inside = ?", req.Inside)
	}
	if req.CreateTimeStart != "" {
		builder = builder.Where("create_time >= ?", req.CreateTimeStart)
	}
	if req.CreateTimeEnd != "" {
		builder = builder.Where("create_time <= ?", req.CreateTimeEnd)
	}

	orderBy := "id DESC"
	if req.OrderBy != "" && req.OrderType != "" {
		orderBy = fmt.Sprintf("%s %s", req.OrderBy, req.OrderType)
	}
	users, total, err := l.svcCtx.UserModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, orderBy)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户分页失败: %v", err)
	}
	var items []types.PlatformUserListItem
	secretKey := l.svcCtx.Config.Encrypt.SecretKey

	for _, user := range users {
		mobile := user.Mobile
		if mobile.Valid {
			encryptedMobile, err := crypto.DecryptMobile(mobile.String, secretKey)
			if err != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "手机登录, 解密手机号失败: %+v", err)
			}
			mobile = sql.NullString{String: encryptedMobile, Valid: true}
		}
		itemData := types.PlatformUserListItem{
			Id:         user.Id,
			Mobile:     mobile.String,
			Nickname:   "",
			Info:       user.Info,
			Inside:     user.Inside,
			CreateTime: user.CreateTime.Format("2006-01-02 15:04:05"),
			UpdateTime: user.UpdateTime.Format("2006-01-02 15:04:05"),
		}
		if user.Nickname.Valid {
			itemData.Nickname = user.Nickname.String
		}
		items = append(items, itemData)
	}
	resp = &types.AdminGetPlatformUserListResp{
		Total: total,
		Items: items,
	}
	return resp, nil
}
