package com.jy.business.listener;

import com.alibaba.fastjson2.JSON;
import com.jy.business.config.RabbitConfig;
import com.jy.business.contract.dao.ContractDetailDao;
import com.jy.business.contract.dao.ContractInfoDao;
import com.jy.business.contract.model.dto.ContractInfoDto;
import com.jy.business.contract.model.entity.ContractDetail;
import com.jy.framework.model.constants.CommonConstant;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Slf4j
@Component
public class ContractRabbitListener {

    @Autowired
    private ContractInfoDao contractInfoDao;

    @Autowired
    private ContractDetailDao contractDetailDao;

    @Transactional(rollbackFor = Exception.class)
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(RabbitConfig.CONTRACT_QUEUE),
                    exchange = @Exchange(RabbitConfig.JY_DIRECT_EXCHANGE)
            )
    })
    public void msgSend(String msg, Channel channel, Message message) throws IOException {
        log.info("mq收到合同消息:【{}】", msg);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            ContractInfoDto dto = JSON.parseObject(msg).to(ContractInfoDto.class);
            handle(dto);

            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            channel.basicNack(deliveryTag, false, true);
            log.error("消息消费失败:【{}】", e.getMessage(), e);
        }
    }

    private void handle(ContractInfoDto dto) {
        Integer handleType = dto.getHandleType();
        switch (handleType) {
            case 1 -> handleAddOrEdit(dto);
            case 3 -> handleDelete(dto);
            default -> {
                log.error("未知的操作类型：{}", handleType);
                throw new IllegalArgumentException("未知的操作类型：" + handleType);
            }
        }
    }

    private void handleAddOrEdit(ContractInfoDto dto) {
        contractInfoDao.saveOrUpdate(dto);
        if (dto.getDetailList() != null) {
            contractDetailDao.updateLinked(dto.getDetailList(), ContractDetail::getContractId, dto.getId());
        }
    }

    private void handleDelete(ContractInfoDto dto) {
        contractInfoDao.removeById(dto.getId());
        contractDetailDao.remove(q -> q.eq(ContractDetail::getContractId, dto.getId()));
    }

}
