package com.pcloud.book.guide.runner;

import com.alibaba.fastjson.JSONObject;
import com.pcloud.book.guide.dto.PcloudGuideDelayDto;
import com.pcloud.book.guide.entity.PcloudGuide;
import com.pcloud.book.guide.mapper.PcloudGuideMapper;
import com.pcloud.book.guide.mapper.PcloudGuideMessageMapper;
import com.pcloud.book.guide.mapper.PcloudRobotSilenceMapper;
import com.pcloud.book.guide.vo.PcloudGuideMessageVO;
import com.pcloud.book.keywords.enums.ReplyTypeEnum;
import com.pcloud.book.pcloudKeyword.dto.RobotClassifyDTO;
import com.pcloud.book.pcloudkeyword.dao.PcloudRobotDao;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import com.sdk.wxgroup.SendPicMessageVO;
import com.sdk.wxgroup.SendTextMessageVO;
import com.sdk.wxgroup.WxGroupSDK;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.pcloud.book.guide.constant.PcloudGuideRedisConstant.PCLOUD_GUIDE_LOCK;
import static com.pcloud.book.guide.constant.PcloudGuideRedisConstant.PCLOUD_GUIDE_SUFFIX;

/**
 * 小睿引导语 间隔发送
 */
@Slf4j
@Component
public class PcloudGuideSilenceRunnerImpl implements ApplicationRunner {

    @Autowired
    private PcloudRobotSilenceMapper pcloudRobotSilenceMapper;
    @Autowired
    private PcloudGuideMapper pcloudGuideMapper;
    @Autowired
    private PcloudGuideMessageMapper pcloudGuideMessageMapper;
    @Autowired
    private PcloudRobotDao pcloudRobotDao;


    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {

        log.info("[项目启动后 定时检查引导与推送]");
        if (!JedisClusterUtils.exists(PCLOUD_GUIDE_LOCK)) {
            JedisClusterUtils.set(PCLOUD_GUIDE_LOCK, "1");
        } else {
            if ("1".equals(JedisClusterUtils.get(PCLOUD_GUIDE_LOCK))) {
                JedisClusterUtils.set(PCLOUD_GUIDE_LOCK, "0");
                return;
            } else {
                JedisClusterUtils.set(PCLOUD_GUIDE_LOCK, "1");
            }
        }

        new Thread(() -> {
            log.info("[PcloudGuideSilenceRunnerImpl] 线程启动成功");

            while (true) {
                try {
                    Thread.sleep(1000);
                    List<RobotClassifyDTO> allPcloudRobot = pcloudRobotDao.getAllPcloudRobot();
                    for (RobotClassifyDTO  robotClassifyDTO: allPcloudRobot) {
                        Map<String, String> friends = JedisClusterUtils.hgetAll(robotClassifyDTO.getWxId() + PCLOUD_GUIDE_SUFFIX);
                        if (friends == null) {
                            continue;
                        }
                        Set<String> userSet = friends.keySet();
                        for (String userId : userSet) {
                            PcloudGuideDelayDto pcloudGuideDelayDto = JSONObject.parseObject(friends.get(userId), PcloudGuideDelayDto.class);

                            // 超时 推送引导语
                            if (!DateUtils.addSecond(pcloudGuideDelayDto.getSendTime(), pcloudGuideDelayDto.getSpanTime() + pcloudGuideDelayDto.getDuration()).after(new Date())) {
                                // 发送消息
                                for (PcloudGuideMessageVO message : pcloudGuideDelayDto.getMsgList()) {
                                    Integer replyType = message.getReplyType();
                                    if (ReplyTypeEnum.TEXT.value.equals(replyType)) {
                                        SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
                                        sendTextMessageVO.setContent(message.getContent());
                                        sendTextMessageVO.setAltId(pcloudGuideDelayDto.getRobotWxId());
                                        sendTextMessageVO.setWxGroupId(userId);
                                        sendTextMessageVO.setIp(pcloudGuideDelayDto.getIp());
                                        sendTextMessageVO.setCode(pcloudGuideDelayDto.getCode());
                                        WxGroupSDK.sendTextMessage(sendTextMessageVO);
                                    }
                                    if (ReplyTypeEnum.IMAGE.value.equals(replyType)) {
                                        SendPicMessageVO sendPicMessageVO = new SendPicMessageVO();
                                        sendPicMessageVO.setPicUrl(message.getPicUrl());
                                        sendPicMessageVO.setAltId(pcloudGuideDelayDto.getRobotWxId());
                                        sendPicMessageVO.setWxGroupId(userId);
                                        sendPicMessageVO.setIp(pcloudGuideDelayDto.getIp());
                                        sendPicMessageVO.setCode(pcloudGuideDelayDto.getCode());
                                        WxGroupSDK.sendPicMessage(sendPicMessageVO);
                                    }
                                }

                                // 向缓存中写入下一条
                                PcloudGuide pcloudGuide = pcloudGuideMapper.getFirstByClassifyId(robotClassifyDTO.getClassifyId(), pcloudGuideDelayDto.getNum() + 1);
                                if (pcloudGuide != null) {

                                    List<PcloudGuideMessageVO> messageVOList = pcloudGuideMessageMapper.listByGuideId(pcloudGuide.getId());
                                    PcloudGuideDelayDto guideDelayDto = PcloudGuideDelayDto.builder().sendTime(new Date()).duration(0)
                                            .spanTime((pcloudGuide.getTimeSpan() == null ? 0 : pcloudGuide.getTimeSpan())).num(pcloudGuideDelayDto.getNum() + 1)
                                            .robotWxId(pcloudGuideDelayDto.getRobotWxId()).ip(pcloudGuideDelayDto.getIp()).code(pcloudGuideDelayDto.getCode()).msgList(messageVOList).build();

                                    if (JSONObject.toJSONString(guideDelayDto) == null) {
                                        guideDelayDto = PcloudGuideDelayDto.builder().sendTime(new Date()).duration(0)
                                                .spanTime((pcloudGuide.getTimeSpan() == null ? 0 : pcloudGuide.getTimeSpan())).num(pcloudGuideDelayDto.getNum() + 1)
                                                .robotWxId(pcloudGuideDelayDto.getRobotWxId()).code(pcloudGuideDelayDto.getCode()).ip(pcloudGuideDelayDto.getIp()).build();
                                    }

                                    JedisClusterUtils.hset(pcloudGuideDelayDto.getRobotWxId() + PCLOUD_GUIDE_SUFFIX, userId, JSONObject.toJSONString(guideDelayDto));
                                } else {
                                    // 最后一条 删除缓存
                                    JedisClusterUtils.hdel(pcloudGuideDelayDto.getRobotWxId() + PCLOUD_GUIDE_SUFFIX, userId);
                                }
                            }
                        }
                    }
                } catch (InterruptedException e) {
                    log.error("引导语延时发送，处理失败", e);
                }
            }

        }).start();
    }
}
