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

import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

import cn.com.ty.lift.ud.chat.mapper.entity.ChatSessionEntity;
import cn.com.ty.lift.ud.chat.service.IChatSessionService;
import cn.com.ty.lift.ud.chat.service.impl.ChatSessionServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import cn.com.ty.lift.ud.utils.ApplicationContextUtil;
import cn.com.ty.lift.ud.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 更新缓存中用户在线数据状态
 *
 * @author sKing
 * @Date 2020年6月8日
 */
@Slf4j
@Component
public class RedisRunner implements CommandLineRunner {
    @Autowired
    private RedisUtil redis;

    @Autowired
    private IChatSessionService sessionService;

    @Override
    public void run(String... args) throws Exception {
        log.info("##--------------------->room loading!");
        redis.deletePattern("ROOM:*");
        //1.先查询出当前用户所有有效房间，然后把房间用户信息放入到redis中
        List<ChatSessionEntity> sessionList = sessionService.findAllSession();
        Map<String, List<ChatSessionEntity>> groupbySessionid = sessionList.stream().collect(Collectors.groupingBy(ChatSessionEntity::getSessionid));
        groupbySessionid.keySet().forEach(sessionid -> {
            List<ChatSessionEntity> userList = groupbySessionid.get(sessionid);
            ChatSessionEntity fistUserinfo = userList.get(0);
            RoomInfo roomInfo = new RoomInfo();

            roomInfo.setSessionid(fistUserinfo.getSessionid());
            roomInfo.setDataTable(fistUserinfo.getDataTable());
            roomInfo.setCaseType(fistUserinfo.getCaseType());
            roomInfo.setAcceptStatus(fistUserinfo.getAcceptStatus());
            roomInfo.setExpression(fistUserinfo.getExpression());
            if(null == fistUserinfo.getCreateTime()) {
                roomInfo.setLastTime(null);
            }else {
                roomInfo.setLastTime(fistUserinfo.getCreateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
            }

            List<UserInfo> users = new ArrayList<>();
            for (ChatSessionEntity chatSessionEntity : userList) {
                UserInfo user = new UserInfo();
                user.setUserId(chatSessionEntity.getUserId());
                user.setAvatarUrl(chatSessionEntity.getAvatarUrl());
                user.setUserName(chatSessionEntity.getUserName());
                users.add(user);
            }
            roomInfo.setUserLIst(users);
            redis.setValue("ROOM:" + sessionid, roomInfo);
        });
        log.info("##--------------------->room loaded!");

        /*log.info("项目启动成功，更新redis中用户在线状态, start!");

        Map<String, List<RoomVo>> redisRoom = redis.get("ROOM", Map.class);
        if (null != redisRoom) {

            for (String room : redisRoom.keySet()) {
                String txt = redis.getKey("ROOM");
                Object ob = txt == null ? null : JSONObject.parseObject(txt, HashMap.class).get(room);
                if (null != ob) {
                    List<RoomVo> voList = null;
                    try {
                        voList = JSONArray.parseArray(ob.toString(), RoomVo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (voList != null && !voList.isEmpty()){
                        for (RoomVo item : voList) {
                            item.setFlag(false);
                        }
                        redisRoom.put(room, voList);
                    }
                }
            }

            // 重置缓存
            redis.setValue("ROOM", redisRoom);
            log.info("更新redis缓存 end!");
        }*/

    }

}
