package com.pcloud.book.guide.runner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pcloud.book.consumer.content.ResourceConsr;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
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.pcloud.contentcenter.resource.dto.ResourceDTO;
import com.sdk.wxgroup.RobotProcessTypeEnum;
import com.sdk.wxgroup.SendFileVO;
import com.sdk.wxgroup.SendPicMessageVO;
import com.sdk.wxgroup.SendTextMessageVO;
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.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

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;
    @Autowired
    private ResourceConsr resourceConsr;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;

    @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())) {
                                // 发送消息
                                List<PcloudGuideMessageVO> msgList = pcloudGuideDelayDto.getMsgList();
                                String groupId = UUID.randomUUID().toString();
                                int counts = msgList.size();
                                for (int i = 0; i < msgList.size(); i++) {
                                    PcloudGuideMessageVO message = msgList.get(i);
                                    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());
                                        sendTextMessageVO.setMessageGroupId(groupId);
                                        sendTextMessageVO.setCounts(counts);
                                        sendTextMessageVO.setIndex(i);
                                        sendTextMessageVO.setRobotProcessType(RobotProcessTypeEnum.GUIDE);
                                        wechatGroupConsr.sendMessage(JSON.toJSONString(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());
                                        sendPicMessageVO.setMessageGroupId(groupId);
                                        sendPicMessageVO.setCounts(counts);
                                        sendPicMessageVO.setIndex(i);
                                        sendPicMessageVO.setRobotProcessType(RobotProcessTypeEnum.GUIDE);
                                        wechatGroupConsr.sendMessage(JSON.toJSONString(sendPicMessageVO));
                                    }
                                    if (ReplyTypeEnum.RESOURCE.value.equals(replyType)) {
                                        SendFileVO sendFileVO = new SendFileVO();
                                        Map<Long, ResourceDTO> map = resourceConsr.mapByIds(Arrays.asList(message.getResourceId()));
                                        ResourceDTO resourceDTO = map.get(message.getResourceId());
                                        if (resourceDTO != null) {
                                            sendFileVO.setFileUrl(resourceDTO.getFileUrl());
                                            String fileName = resourceDTO.getResourceName();
                                            String fileType = resourceDTO.getFileType();
                                            log.info("fileName=" + fileName + "+fileType+" + fileType);
                                            if (fileName.contains(fileType)) {//去掉后缀
                                                fileName = fileName.substring(0, fileName.indexOf(fileType) - 1);
                                            }
                                            log.info("fileName=" + fileName);
                                            sendFileVO.setFileName(fileName);
                                        }
                                        sendFileVO.setIp(pcloudGuideDelayDto.getIp());
                                        sendFileVO.setAltId(pcloudGuideDelayDto.getRobotWxId());
                                        sendFileVO.setWxId(userId);
                                        sendFileVO.setMessageGroupId(groupId);
                                        sendFileVO.setCounts(counts);
                                        sendFileVO.setIndex(i);
                                        sendFileVO.setRobotProcessType(RobotProcessTypeEnum.GUIDE);
                                        wechatGroupConsr.sendMessage(JSON.toJSONString(sendFileVO));
                                    }
                                }

                                // 向缓存中写入下一条
                                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();
    }
}
