package com.pcloud.book.keywords.runner;

import com.alibaba.fastjson.JSONObject;
import com.pcloud.book.book.dto.BookGuideDelayDto;
import com.pcloud.book.consumer.content.ResourceConsr;
import com.pcloud.book.keywords.biz.BookKeywordBiz;
import com.pcloud.book.keywords.dao.SelfRobotGuideDao;
import com.pcloud.book.keywords.dao.SelfRobotKeywordDao;
import com.pcloud.book.keywords.dao.SelfRobotKeywordReplyDao;
import com.pcloud.book.keywords.entity.SelfRobotGuide;
import com.pcloud.book.keywords.entity.SelfRobotKeyword;
import com.pcloud.book.keywords.entity.SelfRobotKeywordReply;
import com.pcloud.book.keywords.enums.ReplyTypeEnum;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import com.pcloud.contentcenter.resource.dto.ResourceDTO;
import com.sdk.wxgroup.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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;

/**
 * 项目启动制行的任务
 *
 * @author Gui_q
 * @since 2020年2月3日 12点14分
 */
@Component
@Slf4j
public class KeyWordDelayRunner implements ApplicationRunner {

    @Value("${system.env}")
    private String envStr;

    @Autowired
    private SelfRobotKeywordDao selfRobotKeywordDao;

    @Autowired
    private BookKeywordBiz bookKeywordBiz;

    @Autowired
    private ResourceConsr resourceConsr;

    @Autowired
    private SelfRobotKeywordReplyDao selfRobotKeywordReplyDao;
    @Autowired
    private SelfRobotGuideDao selfRobotGuideDao;


    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        log.info("[项目启动后 定时检查用户情况]");
        if(!JedisClusterUtils.setnx("KEYWORDDELAYRUNNER_LOCK","KEYWORDDELAYRUNNER_LOCK")){
            JedisClusterUtils.expire("KEYWORDDELAYRUNNER_LOCK",15*60);
            return;
        }
        Long bookGroupId = 0L;
        String wxid = "";
        switch (envStr.toUpperCase()) {
            case "TEST":
                wxid = "wxid_zus32xb5ukjn22";
                bookGroupId = 1621L;
                break;
            case "UAT":
                wxid = "wxid_51ff9f099l9a22";
                bookGroupId = 449L;
                break;
            case "PRO":
                wxid = "wxid_x8i897ryabo722";
                bookGroupId = 23735L;
                break;
        }

        String finalWxid = wxid;
        Long finalBookGroupId = bookGroupId;
        new Thread(() -> {

            while (true) {
                try {
                    Thread.sleep(1000);

                    Map<String, String> friends = JedisClusterUtils.hgetAll(finalWxid+"_DELAY_PUSH");
                    if (friends==null){
                        continue;
                    }

                    Set<String> userSet = friends.keySet();

                    for (String userId : userSet) {
                        try {
                            BookGuideDelayDto bookGuideDelayDto = JSONObject.parseObject(friends.get(userId), BookGuideDelayDto.class);
                            if (bookGuideDelayDto.getExpireTime().before(new Date())) {
                                // 查询当前关键词
                                SelfRobotKeyword currentKeyword=selfRobotKeywordDao.getByBookGroupIdAndKeyword(finalBookGroupId,bookGuideDelayDto.getKeyword());
                                // 发送当前关键词引导语
                                List<SelfRobotGuide> guides = selfRobotGuideDao.getListByKeywordId(currentKeyword.getId());
                                if (!ListUtils.isEmpty(guides)){
                                   for (SelfRobotGuide selfRobotGuide: guides){
                                       if (ReplyTypeEnum.TEXT.value.equals(selfRobotGuide.getType())){
                                           SendTextMessageVO vo = new SendTextMessageVO();
                                           vo.setContent(selfRobotGuide.getContent());
                                           vo.setCode(SendMessageTypeEnum.SELF.getCode());
                                           vo.setWxId(bookGuideDelayDto.getUserWxId());
                                           vo.setAltId(finalWxid);
                                           vo.setWxGroupId(bookGuideDelayDto.getUserWxId());
                                           vo.setIp(bookGuideDelayDto.getIp());
                                           WxGroupSDK.sendTextMessage(vo);
                                           log.info("[发送当前关键词引导语]：{}", JSONObject.toJSONString(vo));
                                       }
                                       if (ReplyTypeEnum.IMAGE.value.equals(selfRobotGuide.getType())){
                                           SendPicMessageVO sendPicMessageVO = new SendPicMessageVO();
                                           sendPicMessageVO.setWxGroupId(bookGuideDelayDto.getUserWxId());
                                           sendPicMessageVO.setWxId(bookGuideDelayDto.getUserWxId());
                                           sendPicMessageVO.setAltId(finalWxid);
                                           sendPicMessageVO.setPicUrl(selfRobotGuide.getPicUrl());
                                           sendPicMessageVO.setIp(bookGuideDelayDto.getIp());
                                           sendPicMessageVO.setCode(SendMessageTypeEnum.SELF.getCode());
                                           WxGroupSDK.sendPicMessage(sendPicMessageVO);
                                           log.info("[发送当前关键词引导语]：{}", JSONObject.toJSONString(sendPicMessageVO));
                                       }
                                   }
                                }
                                if ("学前".equals(currentKeyword.getKeyword())
                                        && envStr.toUpperCase().equals("PRO") && finalWxid.equals("wxid_x8i897ryabo722")) {
                                    SendGroupInviteVO sendGroupInviteVO = new SendGroupInviteVO();
                                    sendGroupInviteVO.setAltId(finalWxid);
                                    sendGroupInviteVO.setWxId(bookGuideDelayDto.getUserWxId());
                                    sendGroupInviteVO.setWxGroupId("23084048866@chatroom");
                                    sendGroupInviteVO.setIp(bookGuideDelayDto.getIp());
                                    WxGroupSDK.sendGroupInvite(sendGroupInviteVO);
                                    log.info("临时发送入群连接 sendGroupInviteVO：{}", sendGroupInviteVO);
                                }
                                if ("教辅书单".equals(currentKeyword.getKeyword())) {
                                    List<SelfRobotKeywordReply> replyList = selfRobotKeywordReplyDao.getListByKeywordId(currentKeyword.getId());
                                    if (!ListUtils.isEmpty(replyList)) {
                                        for (SelfRobotKeywordReply keywordReply : replyList) {
                                            if (ReplyTypeEnum.RESOURCE.value.equals(keywordReply.getType())) {
                                                SendFileVO sendFileVO = new SendFileVO();
                                                Map<Long, ResourceDTO> map = resourceConsr.mapByIds(Arrays.asList(keywordReply.getResourceId()));
                                                ResourceDTO resourceDTO = map.get(keywordReply.getResourceId());
                                                if (resourceDTO != null) {
                                                    sendFileVO.setFileUrl(resourceDTO.getFileUrl());
                                                    sendFileVO.setFileName(resourceDTO.getResourceName());
                                                }
                                                sendFileVO.setIp(bookGuideDelayDto.getIp());
                                                sendFileVO.setAltId(finalWxid);
                                                sendFileVO.setWxId(bookGuideDelayDto.getUserWxId());
                                                WxGroupSDK.sendFile(sendFileVO);
                                            }
                                        }
                                    }
                                }

                                SelfRobotKeyword nextKeyWord = selfRobotKeywordDao.getNextKeyWord(finalBookGroupId, bookGuideDelayDto.getKeyword());
                                if (nextKeyWord==null){
                                    JedisClusterUtils.hdel(finalWxid+"_DELAY_PUSH",userId);
                                    continue;
                                }
                                int time = nextKeyWord.getDelayTime();
                                // 更新缓存中的关键词
                                BookGuideDelayDto delayDto = BookGuideDelayDto.builder().userWxId(bookGuideDelayDto.getUserWxId())
                                        .expireTime(DateUtils.addSecond(new Date(), time))
                                        .keyword(nextKeyWord.getKeyword())
                                        .ip(bookGuideDelayDto.getIp()).build();
                                JedisClusterUtils.hset(finalWxid + "_DELAY_PUSH", bookGuideDelayDto.getUserWxId(), JSONObject.toJSONString(delayDto));

                            }
                        }catch (Exception e){
                            continue;
                        }
                    }
                } catch (Exception e) {
//                    log.info("[KeyWordDelayRunner] 关键词超时推送 失败",e);
                }
            }
        }).start();
    }
}
