package com.kxs.stat.biz.mq;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kxs.common.core.constant.SecurityConstants;
import com.kxs.common.core.constant.enums.ErrorTypeEnum;
import com.kxs.common.core.exception.GlobalCustomerException;
import com.kxs.common.core.util.R;
import com.kxs.common.core.util.RetOps;
import com.kxs.common.core.util.TotalDateUtil;
import com.kxs.stat.api.amqp.rabbit.RabbitLkbActQueueMQ;
import com.kxs.stat.api.amqp.rabbit.RabbitLkbTradeQueueMQ;
import com.kxs.stat.api.model.KxsLkbActTrade;
import com.kxs.stat.api.model.KxsLkbTrade;
import com.kxs.stat.biz.constant.enums.TotalTypeEnum;
import com.kxs.stat.biz.service.KxsLkbActTradeService;
import com.kxs.stat.biz.service.KxsLkbTradeService;
import com.kxs.user.api.feign.RemoteKxsUserService;
import com.kxs.user.api.model.KxsUser;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * rabbit 队列侦听器 商品下单过期队列
 *
 * @author Pota1ovO
 * @date 2024-05-07
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class RabbitLkbQueueListener {

    private final KxsLkbTradeService kxsLkbTradeService;
    private final KxsLkbActTradeService kxsLkbActTradeService;

    private final RemoteKxsUserService remoteKxsUserService;

//    public static void main(String[] args) {
//        System.out.println(TotalDateUtil.getMonthNumber(LocalDateTimeUtil.parseDate("2024-03-14T12:54:41", DatePattern.UTC_SIMPLE_PATTERN)));
//        System.out.println(TotalDateUtil.getDateNumber(LocalDateTimeUtil.parseDate("2024-03-14T12:54:41", DatePattern.UTC_SIMPLE_PATTERN)));
//    }
    /**
     * 监听 来客吧商户激活 队列的处理器
     *
     * @param message 消息
     */
    @RabbitListener(queues = RabbitLkbActQueueMQ.QUEUE_NAME, ackMode = "MANUAL")
    @RabbitHandler
    public void onActMessage(String msg, Message message, Channel channel) {
        try {
            RabbitLkbActQueueMQ.MsgEntity parse = RabbitLkbActQueueMQ.parse(msg);
            log.info("来客吧商户激活消费端Payload: " + parse);

            KxsLkbActTrade lkbActTrade = kxsLkbActTradeService.getOne(Wrappers.<KxsLkbActTrade>lambdaQuery()
                    .eq(KxsLkbActTrade::getUserId, parse.getUserId())
                    .eq(KxsLkbActTrade::getTradeMonth, parse.getStatMonth())
                    .eq(KxsLkbActTrade::getTradeDate, parse.getStatDate())
                    .eq(KxsLkbActTrade::getTotalType, TotalTypeEnum.SELF.getType()));
            if (lkbActTrade == null) {
                lkbActTrade = new KxsLkbActTrade();
                lkbActTrade.setActNum(1);
                lkbActTrade.setUserId(Integer.valueOf(parse.getUserId()));
                lkbActTrade.setTradeMonth(Integer.valueOf(parse.getStatMonth()));
                lkbActTrade.setTradeDate(Integer.valueOf(parse.getStatDate()));
                lkbActTrade.setTotalType(TotalTypeEnum.SELF.getType());
                kxsLkbActTradeService.save(lkbActTrade);
            }else{
                lkbActTrade.setActNum(lkbActTrade.getActNum() + 1);
                kxsLkbActTradeService.updateById(lkbActTrade);
            }
            //团队业绩
            R<KxsUser> kxsUserR = remoteKxsUserService.loadUserById(Integer.valueOf(parse.getUserId()), SecurityConstants.FROM_IN);
            KxsUser user = RetOps.of(kxsUserR)
                    .getData()
                    .orElseThrow(() -> new GlobalCustomerException(ErrorTypeEnum.USER_NOT_FOUND.getDescription()));
            String pidPath = user.getPidPath();
            String[] split = pidPath.split(StrUtil.COMMA);
            for (String userId : split) {
                int pid = Integer.parseInt(userId);
                if(pid <= 0){
                    continue;
                }
                KxsLkbActTrade lkbActTradeTeam = kxsLkbActTradeService.getOne(Wrappers.<KxsLkbActTrade>lambdaQuery()
                        .eq(KxsLkbActTrade::getUserId, userId)
                        .eq(KxsLkbActTrade::getTradeMonth, parse.getStatMonth())
                        .eq(KxsLkbActTrade::getTradeDate, parse.getStatDate())
                        .eq(KxsLkbActTrade::getTotalType, TotalTypeEnum.TEAM.getType()));
                if (lkbActTradeTeam == null) {
                    lkbActTradeTeam = new KxsLkbActTrade();
                    lkbActTradeTeam.setActNum(1);
                    lkbActTrade.setUserId(Integer.valueOf(userId));
                    lkbActTradeTeam.setTradeMonth(Integer.valueOf(parse.getStatMonth()));
                    lkbActTradeTeam.setTradeDate(Integer.valueOf(parse.getStatDate()));
                    lkbActTradeTeam.setTotalType(TotalTypeEnum.TEAM.getType());
                    kxsLkbActTradeService.save(lkbActTradeTeam);
                }else{
                    lkbActTradeTeam.setActNum(lkbActTradeTeam.getActNum() + 1);
                    kxsLkbActTradeService.updateById(lkbActTradeTeam);
                }

            }
            log.info("来客吧商户激活消费成功:{}", JSON.toJSONString(parse));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e) {
            log.error("来客吧商户激活消费失败:{}", JSON.toJSONString(msg), e);
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException ex) {
                log.error("来客吧商户激活手动确认失败" + ex.getMessage(), ex);
            }
        }
    }
    /**
     * 监听 来客吧交易 队列的处理器
     *
     * @param message 消息
     */
    @RabbitListener(queues = RabbitLkbTradeQueueMQ.QUEUE_NAME, ackMode = "MANUAL")
    @RabbitHandler
    public void onMessage(String msg, Message message, Channel channel) {
        try {
            RabbitLkbTradeQueueMQ.MsgEntity parse = RabbitLkbTradeQueueMQ.parse(msg);
            log.info("来客吧交易消费端Payload: " + parse);

            Integer tradeMonth = TotalDateUtil.getMonthNumber(LocalDateTimeUtil.parseDate(parse.getCreateDate(), DatePattern.UTC_SIMPLE_PATTERN));
            Integer tradeDate = TotalDateUtil.getDateNumber(LocalDateTimeUtil.parseDate(parse.getCreateDate(), DatePattern.UTC_SIMPLE_PATTERN));


            //个人业绩
            KxsLkbTrade lkbTrade = kxsLkbTradeService.getOne(Wrappers.<KxsLkbTrade>lambdaQuery()
					.eq(KxsLkbTrade::getUserId, parse.getUserId())
					.eq(KxsLkbTrade::getBrandId, parse.getBrandId())
					.eq(KxsLkbTrade::getTradeMonth, tradeMonth)
					.eq(KxsLkbTrade::getTradeDate, tradeDate)
					.eq(KxsLkbTrade::getTotalType, TotalTypeEnum.SELF.getType())
			);
			if(lkbTrade == null){
                KxsLkbTrade kxsLkbTrade = new KxsLkbTrade();
                kxsLkbTrade.setTradeMonth(tradeMonth);
                kxsLkbTrade.setTradeDate(tradeDate);
                kxsLkbTrade.setUserId(parse.getUserId());
                kxsLkbTrade.setBrandId(parse.getBrandId());

                //活动标识（1活动，0非活动）
                if("1".equals(parse.getIsAct())){
                    kxsLkbTrade.setActTradeAmt(parse.getPayMoney());
                }else{
                    kxsLkbTrade.setTradeAmt(parse.getPayMoney());
                }
                kxsLkbTrade.setTotalType(TotalTypeEnum.SELF.getType());
				kxsLkbTradeService.save(kxsLkbTrade);
			}else{
                //活动标识（1活动，0非活动）
                if("1".equals(parse.getIsAct())){
                    lkbTrade.setActTradeAmt(lkbTrade.getActTradeAmt().add(parse.getPayMoney()));
                }else{
                    lkbTrade.setTradeAmt(lkbTrade.getTradeAmt().add(parse.getPayMoney()));
                }
				kxsLkbTradeService.updateById(lkbTrade);
			}


            //团队业绩
            R<KxsUser> kxsUserR = remoteKxsUserService.loadUserById(parse.getUserId(), SecurityConstants.FROM_IN);
            KxsUser user = RetOps.of(kxsUserR)
                    .getData()
                    .orElseThrow(() -> new GlobalCustomerException(ErrorTypeEnum.USER_NOT_FOUND.getDescription()));
            String pidPath = user.getPidPath();
            String[] split = pidPath.split(StrUtil.COMMA);
            for (String userId : split) {
                int pid = Integer.parseInt(userId);
                if(pid <= 0){
                    continue;
                }
                KxsLkbTrade lkbTradeTeam = kxsLkbTradeService.getOne(Wrappers.<KxsLkbTrade>lambdaQuery()
                        .eq(KxsLkbTrade::getUserId, pid)
                        .eq(KxsLkbTrade::getBrandId, parse.getBrandId())
                        .eq(KxsLkbTrade::getTradeMonth, tradeMonth)
                        .eq(KxsLkbTrade::getTradeDate, tradeDate)
                        .eq(KxsLkbTrade::getTotalType, TotalTypeEnum.TEAM.getType())
                );
                if(lkbTradeTeam == null){
                    KxsLkbTrade kxsLkbTrade = new KxsLkbTrade();
                    kxsLkbTrade.setTradeMonth(tradeMonth);
                    kxsLkbTrade.setTradeDate(tradeDate);
                    kxsLkbTrade.setUserId(pid);
                    kxsLkbTrade.setBrandId(parse.getBrandId());

                    //活动标识（1活动，0非活动）
                    if("1".equals(parse.getIsAct())){
                        kxsLkbTrade.setActTradeAmt(parse.getPayMoney());
                    }else{
                        kxsLkbTrade.setTradeAmt(parse.getPayMoney());
                    }
                    kxsLkbTrade.setTotalType(TotalTypeEnum.TEAM.getType());
                    kxsLkbTradeService.save(kxsLkbTrade);
                }else{
                    //活动标识（1活动，0非活动）
                    if("1".equals(parse.getIsAct())){
                        lkbTradeTeam.setActTradeAmt(lkbTradeTeam.getActTradeAmt().add(parse.getPayMoney()));
                    }else{
                        lkbTradeTeam.setTradeAmt(lkbTradeTeam.getTradeAmt().add(parse.getPayMoney()));
                    }
                    kxsLkbTradeService.updateById(lkbTradeTeam);
                }

            }
            log.info("来客吧交易数据消费成功:{}", JSON.toJSONString(parse));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("来客吧交易数据消费失败:{}", JSON.toJSONString(msg), e);
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException ex) {
                log.error("来客吧交易数据手动确认失败" + ex.getMessage(), ex);
            }
        }
    }

//    /**
//     * 监听死信 队列的处理器
//     *
//     * @param message 消息
//     */
//    @RabbitListener(queues = RabbitLkbTradeQueueMQ.DEAD_QUEUE_NAME)
//    @RabbitHandler
//    public void onDeadMessage(String msg, Message message, Channel channel) {
//        log.info("来客吧死信队列Payload: " + JSON.toJSONString(msg));
//        try {
//            RabbitShopTimeoutQueueMQ.MsgEntity parse = RabbitShopTimeoutQueueMQ.parse(msg);
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//
//        }
//    }


}