package com.pcloud.book.mq.topic;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.pcloud.book.advertising.biz.AdvertisingCpaProductPackageBiz;
import com.pcloud.book.advertising.biz.BmBiz;
import com.pcloud.book.advertising.dao.AdvertisingCpaDao;
import com.pcloud.book.advertising.dao.BmOptionDao;
import com.pcloud.book.advertising.dao.BmRegisterDao;
import com.pcloud.book.advertising.dao.BmRegisterItemDao;
import com.pcloud.book.advertising.entity.AdvertisingBmRegister;
import com.pcloud.book.advertising.entity.AdvertisingCpa;
import com.pcloud.book.mq.config.MQTopicConumer;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.core.constant.SMSTemplateConstant;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.exercisebook.enums.PayModeEnums;
import com.pcloud.facade.tradecenter.dto.ExerciseBookPayDTO;
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
@RabbitListener(queues = MQTopicConumer.PAYMENT_EXERCISE_BOOK)
@Slf4j
public class PaymentExerciseBookListener {

    @Autowired
    private BmRegisterDao bmRegisterDao;
    @Autowired
    private AdvertisingCpaDao advertisingCpaDao;
    @Autowired
    private AdvertisingCpaProductPackageBiz cpaProductPackageBiz;
    @Autowired
    private BmBiz bmBiz;
    @Autowired
    private BmOptionDao bmOptionDao;
    @Autowired
    private BmRegisterItemDao bmRegisterItemDao;


    @RabbitHandler
    @ParamLog("处理订单支付Queue")
    public void process(ExerciseBookPayDTO exerciseBookPayDTO) throws BizException {
        log.info("接收处理订单支付Queue exerciseBookPayDTO：{}", exerciseBookPayDTO);
        if (exerciseBookPayDTO == null || exerciseBookPayDTO.getOrderMainNum() == null) {
            return;
        }
        try {
            handlePayMessage(exerciseBookPayDTO);
        } catch (Exception e) {
            log.error("小睿伴学处理购买消息失败exerciseBookPayDTO：{}，ERROR：{}", exerciseBookPayDTO, e);
        }
    }

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

        // 拿到用户手机
        /*Long mobilePhoneOptionId = bmOptionDao.getMobilePhoneOptionIdByCPA(bmRegister.getCpaId());
        String mobile = bmRegisterItemDao.getRegisterOptionValue(payDTO.getWechatUserId(), bmRegister.getId(), mobilePhoneOptionId);*/

        // 发送短信
        AdvertisingCpa advertisingCpa = advertisingCpaDao.getById(bmRegister.getCpaId());
        if(null!=advertisingCpa && null!=advertisingCpa.getSuccessEmail() && advertisingCpa.getSuccessEmail()==3 && StrUtil.isNotBlank(advertisingCpa.getSuccessSendCode())){
            if (StrUtil.isNotBlank(payDTO.getPhoneNumber())) {
                log.info("发送短信[{}]：[{}]；payDTO：{}", payDTO.getPhoneNumber(), advertisingCpa.getSuccessSendCode(),JSONUtil.toJsonStr(payDTO));
                bmBiz.sendSMS(payDTO.getPhoneNumber(),null, advertisingCpa.getSuccessSendCode());
            } else {
                log.error("未找到手机号，无法发送短信；payDTO：{}", JSONUtil.toJsonStr(payDTO));
            }
        }

        // 查询 权益id是否有配置需要发送支付信息给第三方
        cpaProductPackageBiz.handlerCreateProductPackage(payDTO);
    }
}
