package agent

import (
	"context"
	"encoding/hex"
	"encoding/json"
	"sim-server/app/main/model"
	"sim-server/common/ctxdata"
	"sim-server/common/xerr"
	"sim-server/pkg/lzkit/crypto"

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

	"sim-server/app/main/api/internal/svc"
	"sim-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 process_status = 1", agent.Id)

	orders, total, 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)
	}
	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)
	}
	// 组装查询报告列表（只展示已创建的查询）
	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)
		}

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

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

		item := types.PromotionQueryItem{}
		_ = copier.Copy(&item, q)
		item.Id = q.Id
		item.OrderId = q.OrderId
		item.OrderNo = order.OrderNo
		item.ProductName = product.ProductName
		item.OrderAmount = order.Amount // 订单金额
		item.Amount = ao.AgentProfit    // 推广收益
		item.CreateTime = q.CreateTime.Format("2006-01-02 15:04:05")
		item.QueryState = q.QueryState

		// 解析query_params获取查询人信息
		if q.QueryParams != "" {
			queryParamsByte, err := crypto.AesDecrypt(q.QueryParams, key)
			var queryParams map[string]interface{}
			if err != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "解密查询参数失败, %v", err)
			}
			if err := json.Unmarshal(queryParamsByte, &queryParams); err == nil {
				// 获取姓名
				if name, ok := queryParams["name"].(string); ok {
					item.QueryName = name
				}
				// 获取手机号
				if mobile, ok := queryParams["mobile"].(string); ok {
					item.QueryMobile = mobile
				}
			}
		}

		list = append(list, item)
	}

	return &types.GetPromotionQueryListResp{
		Total: total, // 前端仅展示已创建查询条目
		List:  list,
	}, nil
}
