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

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.com.ty.lift.ud.chat.controller.query.ChatMsgQuery;
import cn.com.ty.lift.ud.chat.mapper.ChatMsgMapper;
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.neety.protocol.ChatMsgDTO;
import cn.com.ty.lift.ud.neety.protocol.IMMessage;
import cn.com.ty.lift.ud.redis.ChatDo;
import cn.com.ty.lift.ud.redis.RedisUtil;
import cn.com.xwy.boot.web.dto.RestResponse;

/**
 * 聊天记录 -ServiceImpl
 *
 * @author Xson
 * @date 2020-04-23
 */
@Service
@Transactional
public class ChatMsgServiceImpl extends ServiceImpl<ChatMsgMapper, ChatMsgEntity> implements IChatMsgService {

    private @Autowired ChatMsgMapper chatMsgMapper;

    private @Autowired RedisUtil redis;

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

    @Override
    public RestResponse messageHistory(ChatMsgQuery req) throws Exception {
        List<IMMessage> data = new ArrayList<>();
        List list2 = redis.get("ALLCHATS:" + req.getSessionid(), List.class);
        if (list2 != null) {
            for (Object i : list2) {
                ObjectMapper objectMapper = new ObjectMapper();
                IMMessage convertValue = objectMapper.convertValue(i, IMMessage.class);
                data.add(convertValue);
            }
        }

        // 查询缓存中是否存在聊天记录
        if (null != data) {
            // 如果查询的总记录小于缓存中的总数就从缓存中获取
            if (data.size() >= (req.getPageNum() * req.getPageSize())) {
                for (IMMessage item : data) {
                    IMMessage entity = new IMMessage();
                    BeanUtils.copyProperties(item, entity);
                    data.add(entity);
                } ;
            } else {// 否者两者结合。将缓存中的数据和数据库中的数据全部获取出来
                long pageNum = req.getPageNum();
                long pageSize = req.getPageSize();
                req.setPageNum(1);
                req.setPageSize(Integer.MAX_VALUE);
                List<IMMessage> list = chatMsgMapper.msgHistoryListQuery(req);
                req.setPageNum(pageNum);
                req.setPageSize(pageSize);
                for (IMMessage item : list) {
                    IMMessage entity = new IMMessage();
                    BeanUtils.copyProperties(item, entity);
                    data.add(entity);
                }

            }
        } else {
            long pageNum = req.getPageNum();
            long pageSize = req.getPageSize();
            req.setPageNum(1);
            req.setPageSize(Integer.MAX_VALUE);
            data = chatMsgMapper.msgHistoryListQuery(req);
            req.setPageNum(pageNum);
            req.setPageSize(pageSize);
        }
        // 进行排序，最新的数据排在最上面
        data = listOrder(data);
        IPage resultData = paging(data, req);
        return RestResponse.success(resultData, "successfully");
    }

    /**
     * 合并缓存和数据库的数据进行分页
     * 
     * @param list
     *            合并之后的数据
     * @param req
     *            操作对象
     * @return
     * @throws Exception
     */
    public IPage paging(List<IMMessage> list, ChatMsgQuery req) throws Exception {
        List<IMMessage> pageList = new ArrayList<IMMessage>();
        int currIdx = (int)(req.getPageNum() > 1 ? (req.getPageNum() - 1) * req.getPageSize() : 0);
        for (int i = 0; i < req.getPageSize() && i < list.size() - currIdx; i++) {
            IMMessage listNew = list.get(currIdx + i);
            pageList.add(listNew);
        }
        IPage page = req.page();
        page.setRecords(pageList);
        page.setTotal(list.size());
        if (page.getTotal() % req.getPageSize() == 0) {
            page.setPages((int)page.getTotal() / req.getPageSize());
        } else {
            page.setPages((int)page.getTotal() / req.getPageSize() + 1);
        }
        page.setCurrent(req.getPageNum());
        page.setSize(pageList.size());
        return page;
    }

    /**
     * 集合内元素前后顺序颠倒
     * 
     * @param list
     * @return
     */
    public static List listOrder(List list) {
        List list1 = new ArrayList<>();
        if (list.size() > 1) {
            for (int i = list.size() - 1; i >= 0; i--) {
                list1.add(list.get(i));
            }
        } else {
            list1 = list;
        }
        return list1;
    }

    @Override
    public RestResponse msgHistoryList(ChatMsgQuery query) {
        IPage page = query.page();
        List<IMMessage> list = chatMsgMapper.msgHistoryListQuery(query);
        int total = chatMsgMapper.countMsgHistoryList(query);
        page.setRecords(list);
        page.setTotal(total);
        return RestResponse.success(list, "Queried successfully");
    }
}
