package agent

import (
	"bdqr-server/app/main/model"
	"bdqr-server/common/ctxdata"
	"bdqr-server/common/globalkey"
	"bdqr-server/common/xerr"
	"context"
	"encoding/hex"
	"encoding/json"
	"strings"

	"bdqr-server/pkg/lzkit/crypto"

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

	"bdqr-server/app/main/api/internal/svc"
	"bdqr-server/app/main/api/internal/types"
)

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

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

func (l *GetPromotionQueryListLogic) GetPromotionQueryList(req *types.GetPromotionQueryListReq) (resp *types.GetPromotionQueryListResp, err error) {
	userID, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户信息失败, %v", err)
	}

	agent, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			return nil, errors.Wrapf(xerr.NewErrMsg("您不是代理"), "")
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败, %v", err)
	}

	// 查询当前代理的代理订单，按创建时间倒序分页
	builder := l.svcCtx.AgentOrderModel.SelectBuilder().
		Where("agent_id = ? AND del_state = ?", agent.Id, globalkey.DelStateNo)

	orders, _, err := l.svcCtx.AgentOrderModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, "create_time DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理订单失败, %v", err)
	}

	// 组装查询报告列表（只展示已创建的查询）
	list := make([]types.PromotionQueryItem, 0, len(orders))
	for _, ao := range orders {
		// 查询对应的报告
		q, qErr := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, ao.OrderId)
		if qErr != nil {
			if errors.Is(qErr, model.ErrNotFound) {
				// 订单对应的查询尚未创建，跳过展示
				continue
			}
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询报告失败, %v", qErr)
		}

		// 获取产品名称
		product, pErr := l.svcCtx.ProductModel.FindOne(l.ctx, ao.ProductId)
		if pErr != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询产品信息失败, %v", pErr)
		}

		// 获取订单价格
		order, oErr := l.svcCtx.OrderModel.FindOne(l.ctx, ao.OrderId)
		if oErr != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询订单信息失败, %v", oErr)
		}

		// 解密并脱敏params
		var params map[string]interface{}
		if q.QueryParams != "" {
			secretKey := l.svcCtx.Config.Encrypt.SecretKey
			key, decodeErr := hex.DecodeString(secretKey)
			if decodeErr != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取AES密钥失败, %v", decodeErr)
			}
			decryptedData, decryptErr := crypto.AesDecrypt(q.QueryParams, key)
			if decryptErr != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "解密查询参数失败, %v", decryptErr)
			}
			unmarshalErr := json.Unmarshal(decryptedData, &params)
			if unmarshalErr != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "解析查询参数失败, %v", unmarshalErr)
			}
			// 脱敏处理
			params = l.desensitizeParams(params)
		} else {
			params = make(map[string]interface{})
		}

		item := types.PromotionQueryItem{}
		_ = copier.Copy(&item, q)
		item.Id = q.Id
		item.OrderId = q.OrderId
		item.ProductName = product.ProductName
		item.CreateTime = q.CreateTime.Format("2006-01-02 15:04:05")
		item.QueryState = q.QueryState
		item.Params = params
		item.Price = order.Amount
		list = append(list, item)
	}

	return &types.GetPromotionQueryListResp{
		Total: int64(len(list)), // 仅统计已创建查询的条目
		List:  list,
	}, nil
}

// desensitizeParams 对敏感数据进行脱敏处理
func (l *GetPromotionQueryListLogic) desensitizeParams(params map[string]interface{}) map[string]interface{} {
	result := make(map[string]interface{})
	for key, value := range params {
		if strValue, ok := value.(string); ok {
			keyLower := strings.ToLower(key)
			if (strings.Contains(keyLower, "name") || strings.Contains(keyLower, "姓名")) && len(strValue) > 0 {
				result[key] = l.maskName(strValue)
			} else if (strings.Contains(keyLower, "idcard") || strings.Contains(keyLower, "id_card") || strings.Contains(keyLower, "身份证")) && len(strValue) > 10 {
				result[key] = l.maskIDCard(strValue)
			} else if (strings.Contains(keyLower, "mobile") || strings.Contains(keyLower, "phone") || strings.Contains(keyLower, "手机")) && len(strValue) >= 8 {
				result[key] = l.maskPhone(strValue)
			} else {
				result[key] = strValue
			}
		} else {
			result[key] = value
		}
	}
	return result
}

// maskName 姓名脱敏
func (l *GetPromotionQueryListLogic) maskName(name string) string {
	runes := []rune(name)
	length := len(runes)
	if length <= 1 {
		return name
	}
	if length == 2 {
		return string(runes[0]) + "*"
	}
	return string(runes[0]) + strings.Repeat("*", length-2) + string(runes[length-1])
}

// maskIDCard 身份证号脱敏
func (l *GetPromotionQueryListLogic) maskIDCard(idCard string) string {
	length := len(idCard)
	if length <= 10 {
		return idCard
	}
	// 保留前3位和后4位
	if length > 7 {
		return idCard[:3] + strings.Repeat("*", length-7) + idCard[length-4:]
	}
	return idCard
}

// maskPhone 手机号脱敏
func (l *GetPromotionQueryListLogic) maskPhone(phone string) string {
	length := len(phone)
	if length < 8 {
		return phone
	}
	// 保留前3位和后4位
	if length > 7 {
		return phone[:3] + strings.Repeat("*", length-7) + phone[length-4:]
	}
	return phone
}
