package agent

import (
	"context"
	"xingfucha-server/common/ctxdata"
	"xingfucha-server/common/xerr"

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

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

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

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

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

func (l *GetAgentWithdrawalLogic) GetAgentWithdrawal(req *types.GetWithdrawalReq) (resp *types.GetWithdrawalResp, 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.AgentWithdrawalModel.SelectBuilder().Where(squirrel.Eq{
		"agent_id": agentModel.Id,
	})
	agentWithdrawalModelList, total, err := l.svcCtx.AgentWithdrawalModel.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.Withdrawal, 0)

	if len(agentWithdrawalModelList) > 0 {
		for _, agentWithdrawalModel := range agentWithdrawalModelList {
			var withdrawal types.Withdrawal
			copyErr := copier.Copy(&withdrawal, agentWithdrawalModel)
			if copyErr != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理提现列表, %v", err)
			}
			withdrawal.CreateTime = agentWithdrawalModel.CreateTime.Format("2006-01-02 15:04:05")
			// 从扣税记录中取扣税比例，供前端展示“扣了几个点”
			taxModel, taxErr := l.svcCtx.AgentWithdrawalTaxModel.FindOneByWithdrawalId(l.ctx, agentWithdrawalModel.Id)
			if taxErr == nil {
				withdrawal.TaxRate = taxModel.TaxRate
			}
			list = append(list, withdrawal)
		}
	}
	return &types.GetWithdrawalResp{
		Total: total,
		List:  list,
	}, nil
}
