package cn.com.ty.lift.ud.chat.service.impl;

import cn.com.ty.lift.common.model.PushMessage;
import cn.com.ty.lift.common.model.PushUserInfo;
import cn.com.ty.lift.ud.chat.controller.model.ChatSessionReq;
import cn.com.ty.lift.ud.chat.controller.model.ChatSessionVo;
import cn.com.ty.lift.ud.chat.controller.query.ChatSessionQuery;
import cn.com.ty.lift.ud.chat.mapper.ChatSessionMapper;
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.neety.task.RoomInfo;
import cn.com.ty.lift.ud.neety.task.UserInfo;
import cn.com.ty.lift.ud.redis.RedisUtil;
import cn.com.ty.lift.ud.userAccount.service.IUserAccountService;
import cn.com.ty.lift.ud.userInfo.mapper.UserInfoMapper;
import cn.com.ty.lift.ud.userInfo.mapper.entity.UserInfoEntity;
import cn.com.ty.lift.ud.utils.UUIDUtil;
import cn.com.xwy.boot.web.dto.RestResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Array;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * 会话 -ServiceImpl
 *
 * @author Xson
 * @date 2020-04-23
 */
@Service
@Transactional
public class ChatSessionServiceImpl extends ServiceImpl<ChatSessionMapper, ChatSessionEntity>
    implements IChatSessionService {

    private @Autowired ChatSessionMapper sessionMapper;

    private @Autowired IUserAccountService iUserAccountService;

    private @Autowired UserInfoMapper userInfoMapper;

    private @Autowired RedisUtil redis;

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Override
    public ChatSessionEntity findOneBySessionIdAndPwd(String sessionId, String pwd) {
        return sessionMapper.findOneBySessionIdAndPwd(sessionId, pwd);
    }

    @Override
    public RestResponse existRoom(String room) {

        QueryWrapper<ChatSessionEntity> query = new QueryWrapper<ChatSessionEntity>();
        query.eq("sessionid", room);
        query.eq("statuz", 1);

        boolean flag = sessionMapper.selectOne(query) == null ? false : true;
        if (flag)
            return RestResponse.success(flag, "successfully");
        else
            return RestResponse.success(flag, "房间已关闭，或未找到");
    }

    @Override
    public RestResponse batchUpdate(ChatSessionReq req) {
        List<String> sessionList = new ArrayList<>();
        for (Long id : req.getIds()) {
            ChatSessionEntity selectById = sessionMapper.selectById(id);
            sessionList.add(selectById.getSessionid());
        }
        req.setSessionList(sessionList);
        int flag = sessionMapper.batchUpdate(req);
        if (flag > 0)
            return RestResponse.success("Updated successfully");
        else
            return RestResponse.fail("Updated unsuccessfully");
    }

    @Override
    public RestResponse setTop(ChatSessionReq req) {
        int i = sessionMapper.setTop(req);

        if (i > 0)
            return RestResponse.success("Updated successfully");
        else
            return RestResponse.fail("Updated unsuccessfully");
    }

    @Override
    public RestResponse selectByExample(ChatSessionQuery query) {
        IPage page = query.page();
        List<ChatSessionEntity> list = sessionMapper.selectByQuery(query.condition(), query);
        int total = sessionMapper.countByQuery(query.condition());
        page.setRecords(list);
        page.setTotal(total);
        return RestResponse.success(page);
    }

    @Override
    public int insertSelective(ChatSessionEntity record) {
        return sessionMapper.insert(record);
    }

    @Override
    public RestResponse findOneByLiftCase(ChatSessionQuery req) {
        QueryWrapper<ChatSessionEntity> queryWrapper = new QueryWrapper<ChatSessionEntity>();
        queryWrapper.eq("data_id", req.getDataId());
        queryWrapper.eq("user_id", req.getUserId());
        ChatSessionEntity data = sessionMapper.selectOne(queryWrapper);

        return RestResponse.success(data, "success");
    }

    @Override
    public List<String> findListByUserId(String userId) {
        return sessionMapper.findListByUserId(userId);
    }

    @Override
    public RestResponse batchUpdateEntrance(ChatSessionReq req) {
        sessionMapper.batchUpdateEntrance(req.getSessionId(), 0);
        return RestResponse.success();
    }

    @Override
    public RestResponse findDBListByUserId(ChatSessionQuery query) {
        IPage page = query.page();
        List<ChatSessionEntity> list = sessionMapper.findDBListByUserId(query);
        list.forEach(entity -> {
            RoomInfo roomInfo = redis.get("ROOM:" + entity.getSessionid(), RoomInfo.class);
            if (null != roomInfo) {
                entity.setLastMsg(roomInfo.getLastChat());
                entity.setLastTime(roomInfo.getLastTime());
            }
        });
        Collections.sort(list, (ent1, ent2) -> {
            if (ent1.getLastTime() == null || ent2.getLastTime() == null){
                return -1;
            }

            return ent2.getLastTime().compareTo(ent1.getLastTime());
        });

        page.setRecords(list);
        return RestResponse.success(page);
    }

    @Override
    /**
     * 系统启动的时候加载放假及用户信息
     */
    public List<ChatSessionEntity> findAllSession() {
        return sessionMapper.findAllSession();
    }

    @Override
    public RestResponse createPrivateChatRoom(ChatSessionQuery request) {
        ChatSessionVo vo = new ChatSessionVo();
        // 使用我的用户id和将要聊天的用户id正反去数据库查询房间号是否存在
        String sessionId =
            sessionMapper.findOneByUserIdAndCreateUserIdAndDateTable(request.getUserId(), request.getCreateUserId(), 3);

        if (StringUtils.isBlank(sessionId)) {
            ChatSessionEntity record = new ChatSessionEntity();
            // 添加自己到房间
            sessionId = UUIDUtil.getUuidByTime9();
            record.setUserId(request.getUserId()+","+request.getCreateUserId());
            record.setCreateUserId(request.getCreateUserId());
            record.setSessionid(sessionId);
            record.setDataTable(3);
            record.setEntrance(1);
            record.setStatuz(1);
            record.setCreateTime(LocalDateTime.now());
            sessionMapper.insertSelective(record);
            // 添加对方用户到房间
            /*record = new ChatSessionEntity();
            record.setUserId(request.getCreateUserId());
            record.setCreateUserId(null);
            record.setSessionid(sessionId);
            record.setDataTable(3);
            record.setEntrance(1);
            record.setStatuz(1);
            record.setCreateTime(LocalDateTime.now());
            sessionMapper.insertSelective(record);*/

            vo.setType(1);
            vo.setRoom(sessionId);
            // 在redis中创建房间
            RoomInfo roomInfo = new RoomInfo();
            roomInfo.setSessionid(record.getSessionid());
            roomInfo.setDataTable(record.getDataTable());
            roomInfo.setLastTime(record.getCreateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());

            UserInfo userInfo1 = new UserInfo();
            userInfo1.setUserId(request.getUserId());
            UserInfo userInfo2 = new UserInfo();
            userInfo2.setUserId(request.getCreateUserId());
            List<UserInfo> userList = new ArrayList<>();
            userList.add(userInfo1);
            userList.add(userInfo2);

            roomInfo.setUserLIst(userList);
            redis.setValue("ROOM:" + vo.getRoom(), roomInfo);

            // 推送消息
            UserInfoEntity byUserId = userInfoMapper.getByUserId(Long.parseLong(request.getUserId()));
            PushUserInfo pushUserInfo = iUserAccountService.getPushUserInfoByUserId(request.getCreateUserId().toString());
            PushMessage pushMessage = PushMessage.sayHelloToFriend(byUserId.getName());
            pushMessage.sendTokenOnPlatform(jmsMessagingTemplate, pushUserInfo);
        } else {
            vo.setType(2);
            vo.setRoom(sessionId);
        }

        return RestResponse.success(vo);
    }

    @Override
    public List<ChatSessionEntity> findListBySessionId(String sessionid) {
        QueryWrapper query = new QueryWrapper();
        query.eq("sessionid", sessionid);
        List list = list(query);

        return list;
    }
}
