package com.fs.app.redis;//package com.fs.app.redis;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fs.common.constant.FsConstants;
import com.fs.hisStore.domain.FsStoreOrderScrm;
import com.fs.hisStore.domain.FsStoreVerifyCodeScrm;
import com.fs.hisStore.mapper.FsStoreOrderItemScrmMapper;
import com.fs.hisStore.mapper.FsStoreOrderScrmMapper;
import com.fs.hisStore.mapper.FsStoreVerifyCodeScrmMapper;
import com.fs.hisStore.service.IFsStoreVerifyCodeScrmService;
import com.fs.hisStore.vo.FsStoreOrderItemVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    private static final Logger log = LoggerFactory.getLogger(RedisKeyExpirationListener.class);

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

//    @Autowired
//    private IQwUserService qwUserService;
//    @Autowired
//    private ConfigUtil configUtil;

    @Autowired
    private StringRedisTemplate redisTemplate;  // 使用 RedisTemplate 进行分布式锁

    @Autowired
    private FsStoreOrderScrmMapper orderScrmMapper;

    @Autowired
    private FsStoreOrderItemScrmMapper orderItemScrmMapper;

    @Autowired
    private FsStoreVerifyCodeScrmMapper verifyCodeScrmMapper;

    @Autowired
    private IFsStoreVerifyCodeScrmService verifyCodeScrmService;

//    @Autowired
//    QwUserMapper qwUserMapper;
//
//    @Autowired
//    QwCompanyMapper qwCompanyMapper;
//
//    @Autowired
//    QwApiService qwApiService;

    /**
     * 针对redis数据失效事件，进行数据处理
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = new String(message.getChannel(), StandardCharsets.UTF_8);
        //过期的key
        String key = new String(message.getBody(), StandardCharsets.UTF_8);

//        //判断是否是appKey失效
//        if(key.contains(FsConstants.REDIS_QW_appKey_Active)) {
//
//            log.info("监听Qw过期appKey-redis过期：pattern={},channel={},key={}",new String(pattern),channel,key);
//
//            String lockKey = "lockAppKey:" + key;  // 分布式锁的 key
//
//            // 尝试获取锁，设置 30 秒自动过期，防止死锁
//            Boolean lockAcquired = redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 30, TimeUnit.SECONDS);
//
//            if (Boolean.TRUE.equals(lockAcquired)) {  // 只有一个实例会成功获取锁
//                try {
//                    String[] parts = key.split(":");
//
//                    if (parts.length == 3) {
//                        String corpId = parts[1].trim();
//                        String qwUserId = parts[2].trim();
//
//                        String appKey = qwUserService.selectQwUserByQwUserIdAndCorId(qwUserId, corpId);
//
//                        String msg="<font color=\"warning\">您的【云联融智】助手已退出，企业微信【侧边栏】有异常，发送已停止，请注意查看</font>";
//                        sendQwMsg(appKey,msg);
//
//                        log.info("监听Qw过期appKey-redis过期：pattern={},channel={},key={}",new String(pattern),channel,key);
//                    } else {
//                        System.out.println("监听appKey失效！");
//                    }
//                } finally {
//                    // 释放锁，避免影响后续任务
//                    redisTemplate.delete(lockKey);
//                }
//            } else {
//                log.info("另一个实例已经处理了 key={}，当前实例跳过", key);
//            }
//
//        }else
        if (key.contains(FsConstants.REDIS_ORDER_UNPAY)) {//未支付支付订单过期
            log.info("监听商城过期appKey-redis过期：pattern={},channel={},key={}", new String(pattern), channel, key);
            String lockKey = "lockStoreAppKey:" + key;  // 分布式锁的 key
            Boolean lockAcquired = redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 30, TimeUnit.SECONDS);
            if (Boolean.TRUE.equals(lockAcquired)) {  // 只有一个实例会成功获取锁
                try {
                    String[] parts = key.split(":");
                    if (parts.length == 3) {
                        Long orderId = Long.parseLong(parts[parts.length - 1].trim());
                        if (orderId != null) {
                            //获取订单信息
                            FsStoreOrderScrm orderScrm = orderScrmMapper.selectFsStoreOrderById(orderId);
                            if (orderScrm != null && orderScrm.getStatus() == 0) {
                                //获取订单下的详情信息
                                List<FsStoreOrderItemVO> scrmList = orderItemScrmMapper.selectMyFsStoreOrderItemListByOrderId(orderId);
                                if (!scrmList.isEmpty()) {
                                    List<Long> orderItemIds = scrmList.stream().map(FsStoreOrderItemVO::getItemId).collect(Collectors.toList());
                                    //获取溯源码，进行回退
                                    List<FsStoreVerifyCodeScrm> verifyCodes = verifyCodeScrmMapper.selectList(new LambdaQueryWrapper<FsStoreVerifyCodeScrm>().eq(FsStoreVerifyCodeScrm::getOrderId, orderId).in(FsStoreVerifyCodeScrm::getOrderItemId, orderItemIds).eq(FsStoreVerifyCodeScrm::getIsDel, "0"));
                                    if(!verifyCodes.isEmpty()){
                                        verifyCodes.forEach(v->{
                                            v.setVerifyStatus(0L);
                                            v.setOutboundStatus(0L);
                                        });
                                        //批量更新数据
                                        verifyCodeScrmService.updateBatchById(verifyCodes);
                                    }
                                }
                                //更新订单状态
                                FsStoreOrderScrm updateOrder = new FsStoreOrderScrm();
                                updateOrder.setId(orderId);
                                updateOrder.setStatus(-3);
                                orderScrmMapper.updateFsStoreOrder(updateOrder);
                            }
                        }
                    } else {
                        System.out.println("监听appKey失效！");
                    }
                } finally {
                    // 释放锁，避免影响后续任务
                    redisTemplate.delete(lockKey);
                }
            } else {
                log.info("另一个实例已经处理了 key={}，当前实例跳过", key);
            }

        }
    }

//    /**
//     * 给企业微信的应用发送消息
//     */
//    private void sendQwMsg(String appKey,String msg){
//        QwUser qwUserByAppKey = qwUserMapper.selectQwUserByAppKey(appKey);
//
//        QwSendMsgParam sendMsgParam = new QwSendMsgParam();
//        QwCompany qwCompany = qwCompanyMapper.selectQwCompanyByCorpId(qwUserByAppKey.getCorpId());
//        sendMsgParam.setAgentid(Integer.parseInt(qwCompany.getServerAgentId().trim()));
//        sendMsgParam.setTouser(qwUserByAppKey.getQwUserId());
//
//        QwSendMsgParam.Markdown markdown = new QwSendMsgParam.Markdown();
//        markdown.setContent(msg);
//
//        sendMsgParam.setMarkdown(markdown);
//        sendMsgParam.setMsgtype("markdown");
//        qwApiService.sendMsg(sendMsgParam, qwCompany.getCorpId());
//
//    }
}
