package cn.com.ty.lift.ud.neety.task;

import cn.com.ty.lift.ud.chat.mapper.entity.ChatMsgEntity;
import cn.com.ty.lift.ud.chat.service.IChatMsgService;
import cn.com.ty.lift.ud.chat.service.IChatUnreadMsgService;
import cn.com.ty.lift.ud.neety.protocol.IMMessage;
import cn.com.ty.lift.ud.neety.protocol.RoomVo;
import cn.com.ty.lift.ud.redis.ChatDo;
import cn.com.ty.lift.ud.redis.RedisUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * 同步缓存数据到mysql
 *
 * @author sKing
 */
@Slf4j
@Component
public class RedisTask {
    @Autowired
    private RedisUtil redis;
    @Autowired
    private IChatUnreadMsgService chatUnreadMsgService;
    @Autowired
    private IChatMsgService msgService;

    public RedisTask() {
        log.info("RedisTask init");
    }

    /**
     * 在凌晨时，讲聊天记录同步到数据库中，redis只放当天的数据
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(initialDelay = 5000, fixedDelay=3600000)
    public void synRedisChatToDB() {
        log.info("执行保存未读消息操作！");
        Set<String> keys = redis.keys("ALLCHATS:*");
        for (String key : keys) {
            List<ChatMsgEntity> chatList = new ArrayList<>();
            List list = redis.get(key, List.class);
            list.forEach(msg -> {
                ChatMsgEntity entity = new ChatMsgEntity();
                IMMessage imMessage = JSONObject.parseObject(msg.toString(), IMMessage.class);
                entity.setMsg(imMessage.getMsg());
                entity.setFromUser(imMessage.getFromUser());
                entity.setToUser(imMessage.getReceiver());
                entity.setType(imMessage.getType());
                entity.setSessionid(imMessage.getSessionid());
                entity.setStatuz(1);
                entity.setCreateBy(imMessage.getName());
                entity.setCreateTime(new Date(imMessage.getTime()).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime());
                chatList.add(entity);
            });

            if (!chatList.isEmpty()) {
                msgService.saveBatch(chatList);
            }
            redis.delete(key);
        }
        /*List<ChatUnreadMsgEntity> unreadMsgList = new ArrayList<>();
        Map<String, List<RoomVo>> redisRoom = redis.get("ROOM", Map.class);
        ChatUnreadMsgEntity entity = new ChatUnreadMsgEntity();
        // 获取所有房间的聊天记录
        if (null != redisRoom) {

            for (String room : redisRoom.keySet()) {

                log.info("Start.  正在执行的房间号是：{}", room);
                String txt = redis.getKey("ROOM");
                Object ob = txt == null ? null : JSONObject.parseObject(txt, HashMap.class).get(room);
                if (null != ob) {
                    List<RoomVo> voList = JSONArray.parseArray(ob.toString(), RoomVo.class);

                    for (RoomVo item : voList) {

                        if (item.getMsgList().size() > 0) {
                            item.getMsgList().forEach(msg -> {
                                BeanUtils.copyProperties(msg, entity);
                                unreadMsgList.add(entity);
                            });

                            item.setMsgList(null);
                            item.setUnreadNum(0);

                        } else {

                            log.info("房间号是：{}----》暂无未读消息保存", room);
                        }

                    }
                    *//** TODO 打开之后将清理redis中未读的缓存 暂时未用（使用之后用户上线查询未读消息需要结合缓存以及数据库的数据） *//*
                    // redisRoom.put(room, voList);
                }

            }
            // 重置缓存
            redis.setValue("ROOM", redisRoom);

            chatUnreadMsgService.saveBatch(unreadMsgList);
        }*/
        log.info("End. 保存未读消息操作结束！");

    }

    /**
     * 每三分钟执行一次 同步redis缓存中聊天记录数据到mysql中 [秒] [分] [小时] [日] [月] [周] [年]
     */
//    @Scheduled(cron = "0 */3 * * * ?")
    // @Scheduled(fixedDelay = 60000 * 5)
    public void saveUnreadMsg() {
        // RedisUtil redis = ApplicationContextUtil.getBean(RedisUtil.class);
        // IChatMsgService msgService = ApplicationContextUtil.getBean(ChatMsgServiceImpl.class);
        log.info("执行保存聊天记录操作！");
        List<ChatMsgEntity> msg = new ArrayList<>();
        List<String> key = new ArrayList<>();// 创建临时房间列表。避免清除缓存的时候删除了新增的房间号
        Map<String, List<RoomVo>> redisRoom = redis.get("ROOM", Map.class);
        // 获取所有房间的聊天记录
        if (null != redisRoom) {
            for (String item : redisRoom.keySet()) {
                // logger.info("Start. 正在执行的房间号是：{}", item);
                ChatDo chatDo = redis.get(item, ChatDo.class);
                if (null != chatDo) {
                    chatDo.getList().forEach(chat -> {
                        ChatMsgEntity entity = new ChatMsgEntity();
                        BeanUtils.copyProperties(chat, entity);
                        LocalDateTime convertStr = LocalDateTime.parse(chat.getCreateTime());
                        entity.setCreateTime(convertStr);
                        msg.add(entity);
                    });
                    key.add(item);
                } else {
                    // logger.info("房间号是：{}----》暂无消息可保存", item);
                }
            }

            // 删除缓存中已提取的房间号
            redis.delete(key);

            msgService.saveBatch(msg);
        }
        log.info("End. 保存聊天记录操作结束！");
    }

}
