package agent

import (
	"context"
	"encoding/hex"
	"encoding/json"
	"tyc-server/common/ctxdata"
	"tyc-server/common/xerr"
	"tyc-server/pkg/lzkit/crypto"

	"github.com/Masterminds/squirrel"
	"github.com/jinzhu/copier"
	"github.com/pkg/errors"

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

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

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

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

func (l *GetAgentCommissionLogic) GetAgentCommission(req *types.GetCommissionReq) (resp *types.GetCommissionResp, err error) {
	userID, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理佣金列表, %v", err)
	}
	agentModel, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理佣金列表, %v", err)
	}
	builder := l.svcCtx.AgentCommissionModel.SelectBuilder().Where(squirrel.Eq{
		"agent_id": agentModel.Id,
	})
	agentCommissionModelList, total, err := l.svcCtx.AgentCommissionModel.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)
	}

	var list = make([]types.Commission, 0)

	if len(agentCommissionModelList) > 0 {
		for _, agentCommissionModel := range agentCommissionModelList {
			var commission types.Commission
			copyErr := copier.Copy(&commission, agentCommissionModel)
			if copyErr != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理佣金列表, %v", err)
			}
			// 显式设置 status 字段和已退款金额
			commission.Status = agentCommissionModel.Status
			commission.RefundedAmount = agentCommissionModel.RefundedAmount
			// 计算净佣金金额（防御性处理，避免出现负数）
			netAmount := agentCommissionModel.Amount - agentCommissionModel.RefundedAmount
			if netAmount < 0 {
				netAmount = 0
			}
			commission.NetAmount = netAmount
			product, findProductErr := l.svcCtx.ProductModel.FindOne(l.ctx, agentCommissionModel.ProductId)
			if findProductErr != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理佣金列表, %v", err)
			}
			commission.CreateTime = agentCommissionModel.CreateTime.Format("2006-01-02 15:04:05")
			commission.ProductName = product.ProductName

			// 从 order 表获取 platform_order_id
			orderModel, findOrderErr := l.svcCtx.OrderModel.FindOne(l.ctx, agentCommissionModel.OrderId)
			if findOrderErr == nil && orderModel != nil && orderModel.PlatformOrderId.Valid {
				commission.OrderId = orderModel.PlatformOrderId.String
			} else {
				commission.OrderId = ""
			}

			queryModel, queryErr := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, agentCommissionModel.OrderId)
			if queryErr == nil && queryModel != nil {

				key := l.svcCtx.Config.Encrypt.SecretKey
				keyBytes, decodeErr := hex.DecodeString(key)
				if decodeErr != nil {
					return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理佣金列表, %v", err)
				}
				// 根据订单号查询query表获取query_params
				decryptedData, decryptErr := crypto.AesDecrypt(queryModel.QueryParams, keyBytes)
				if decryptErr != nil {
					return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理佣金列表, %v", err)
				}
				// 解析query_params，从JSON字符串转换为map
				if queryModel.QueryParams != "" {

					var queryParamsMap map[string]interface{}
					if unmarshalErr := json.Unmarshal(decryptedData, &queryParamsMap); unmarshalErr == nil {
						commission.QueryParams = queryParamsMap
					}
				}
			}
			list = append(list, commission)
		}
	}
	return &types.GetCommissionResp{
		Total: total,
		List:  list,
	}, nil
}
