package com.pcloud.book.mq.topic;

import cn.hutool.json.JSONUtil;
import com.pcloud.book.advertising.biz.AdvertisingCpaProductPackageBiz;
import com.pcloud.book.advertising.dao.BmRegisterDao;
import com.pcloud.book.advertising.entity.AdvertisingBmRegister;
import com.pcloud.book.mq.config.MQTopicConumer;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.exercisebook.dto.RefundExerciseBookDTO;
import com.pcloud.exercisebook.enums.PayModeEnums;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("refundExerciseBookListener")
@RabbitListener(queues = MQTopicConumer.REFUND_EXERCISE_BOOK)
@Slf4j
public class RefundExerciseBookListener {

    @Autowired
    private BmRegisterDao bmRegisterDao;
    @Autowired
    private AdvertisingCpaProductPackageBiz cpaProductPackageBiz;


    @RabbitHandler
    @ParamLog("处理退款订单Queue")
    public void process(RefundExerciseBookDTO refundDTO) throws BizException {
        log.info("接收处理退款订单Queue refundDTO：{}", refundDTO);
        if (refundDTO == null || refundDTO.getOrderMainNum() == null) {
            return;
        }
        try {
            handleRefundMessage(refundDTO);
        } catch (Exception e) {
            log.error("小睿伴学处理退款消息失败 refundDTO：{}，ERROR：{}", refundDTO, e.getMessage());
        }
    }

    private void handleRefundMessage(RefundExerciseBookDTO refundDTO) {
        // 判断 buyMode
        if(!PayModeEnums.ADVERTISING_CPA.getCode().equals(refundDTO.getBuyMode())) {
            return;
        }
        // 根据 buy_id（register_id） 查询详情
        AdvertisingBmRegister bmRegister = bmRegisterDao.getById(refundDTO.getBuyId());
        if (bmRegister == null) {
            log.error("未找到对应的 id，无法处理退款单，请关注；refundDTO：{}", JSONUtil.toJsonStr(refundDTO));
            return;
        }
        // 更新退款状态
        AdvertisingBmRegister updateRegister = new AdvertisingBmRegister();
        updateRegister.setId(bmRegister.getId());
        updateRegister.setPayStatus(-1);
        bmRegisterDao.update(updateRegister);

        // 退款
        cpaProductPackageBiz.handlerRefundProductPackage(refundDTO);
    }
}