package com.czg.mq;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.czg.EntryManager;
import com.czg.PayCst;
import com.czg.config.RabbitConstants;
import com.czg.config.RedisCst;
import com.czg.dto.resp.EntryRespDto;
import com.czg.order.entity.ShopDirectMerchant;
import com.czg.service.RedisService;
import com.czg.service.order.dto.AggregateMerchantVO;
import com.czg.service.order.service.ShopDirectMerchantService;
import com.mybatisflex.core.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 打印mq消息处理器
 *
 * @author Administrator
 */
@Component
@Slf4j
public class EntryManagerMqListener {
    @Resource
    private RedisService redisService;
    @Resource
    private ShopDirectMerchantService shopDirectMerchantService;

    String key = RedisCst.SHOP_ENTRY;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "${spring.profiles.active}-" + RabbitConstants.Queue.SHOP_ENTRY_MANAGER,
                            durable = "true", exclusive = "false", autoDelete = "false"),
                    exchange = @Exchange(value = "${spring.profiles.active}-" + RabbitConstants.Exchange.CASH_EXCHANGE),
                    key = "${spring.profiles.active}-" + RabbitConstants.Queue.SHOP_ENTRY_MANAGER
            ),
            concurrency = "5"
    )
    @RabbitHandler
    public void handle(Message message, Channel channel, String msg) throws IOException {
        log.info("进件1MQ对接开始 店铺标识:{}", msg);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        if (StrUtil.isBlank(msg)) {
            channel.basicNack(deliveryTag, false, false);
            return;
        }
        String[] split = msg.split(":");
        if (split.length != 2) {
            log.error("进件MQ对接参数异常 店铺标识:{}", msg);
            channel.basicNack(deliveryTag, false, false);
            return;
        }
        if (split[0]==null) {
            channel.basicNack(deliveryTag, false, false);
            return;
        }
        Long shopId = Long.valueOf(split[0]);
        if (hasMessageId(msg)) {
            return;
        }
        try {
            // 将唯一标识添加到日志上下文
            ThreadContext.put("traceId", String.valueOf(shopId));
            log.info("进件2MQ对接开始shopId:{}", msg);
            // 安全转换shopId
            AggregateMerchantVO entry = shopDirectMerchantService.getEntry(shopId);
            log.info("进件3MQ对接开始shopId:{}", msg);
            if (entry != null) {
                EntryManager.uploadParamImage(entry);
                List<String> platform = new ArrayList<>();
                if (PayCst.EntryStatus.WAIT.equals(entry.getAlipayStatus())) {
                    platform.add(PayCst.Type.ALIPAY);
                }
                if (PayCst.EntryStatus.WAIT.equals(entry.getWechatStatus())) {
                    platform.add(PayCst.Type.WECHAT);
                }
                EntryRespDto resp = EntryManager.entryMerchant(entry, platform.toArray(new String[0]));
                ShopDirectMerchant merchant = new ShopDirectMerchant();
                merchant.setMerchantBaseInfo(JSONObject.toJSONString(entry.getMerchantBaseInfo()));
                merchant.setLegalPersonInfo(JSONObject.toJSONString(entry.getLegalPersonInfo()));
                merchant.setBusinessLicenceInfo(JSONObject.toJSONString(entry.getBusinessLicenceInfo()));
                merchant.setStoreInfo(JSONObject.toJSONString(entry.getStoreInfo()));
                merchant.setSettlementInfo(JSONObject.toJSONString(entry.getSettlementInfo()));


                merchant.setWechatApplyId(resp.getWechatApplyId());
                merchant.setWechatStatus(resp.getWechatStatus());
                merchant.setWechatErrorMsg(resp.getWechatErrorMsg());
                merchant.setAlipayOrderId(resp.getAlipayOrderId());
                merchant.setAlipayStatus(resp.getAlipayStatus());
                merchant.setAlipayAuthInfo(resp.getAlipayAuthInfo());
                merchant.setAlipayErrorMsg(resp.getAlipayErrorMsg());
                shopDirectMerchantService.update(merchant, new QueryWrapper().eq(ShopDirectMerchant::getShopId, shopId).eq(ShopDirectMerchant::getLicenceNo, split[1]));
            }
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("进件MQ对接业务异常shopId:{}", msg, e);
            ShopDirectMerchant merchant = new ShopDirectMerchant();
            merchant.setWechatStatus(PayCst.EntryStatus.REJECTED);
            merchant.setAlipayStatus(PayCst.EntryStatus.REJECTED);
            merchant.setErrorMsg("系统错误，请联系管理员后重试。");
            shopDirectMerchantService.update(merchant, new QueryWrapper().eq(ShopDirectMerchant::getShopId, shopId).eq(ShopDirectMerchant::getLicenceNo, split[1]));
            channel.basicNack(deliveryTag, false, false);
        } finally {
            delMessageId(msg);
//             清除日志上下文信息
            ThreadContext.remove("messageId");
        }
    }

    public boolean hasMessageId(String messageId) {
        if (!redisService.hasKey(key)) {
            if (StrUtil.isNotBlank(messageId)) {
                redisService.leftPush(key, messageId);
                return false;
            } else {
                return true;
            }
        }
        List<Object> list = redisService.lGet(key, 0, -1);
        if (!list.contains(messageId)) {
            redisService.leftPush(key, messageId);
            return false;
        }
        return true;
    }

    public void delMessageId(String messageId) {
        redisService.lRemove(key, 0, messageId);
    }

}
