package com.wecloud.im.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.wecloud.im.entity.ImApplication;
import com.wecloud.im.entity.ImClient;
import com.wecloud.im.entity.ImConversation;
import com.wecloud.im.entity.ImConversationMembers;
import com.wecloud.im.mapper.ImConversationMapper;
import com.wecloud.im.param.ImConversationPageParam;
import com.wecloud.im.param.ImConversationQueryVo;
import com.wecloud.im.param.add.ImConversationCreate;
import com.wecloud.im.service.ImApplicationService;
import com.wecloud.im.service.ImClientService;
import com.wecloud.im.service.ImConversationMembersService;
import com.wecloud.im.service.ImConversationService;
import com.wecloud.im.service.ImMessageService;
import com.wecloud.im.vo.ImConversationCreateVo;
import com.wecloud.im.vo.MyConversationListVo;
import com.wecloud.im.vo.OfflineMsgDto;
import io.geekidea.springbootplus.framework.common.api.ApiResult;
import io.geekidea.springbootplus.framework.common.service.impl.BaseServiceImpl;
import io.geekidea.springbootplus.framework.core.pagination.PageInfo;
import io.geekidea.springbootplus.framework.core.pagination.Paging;
import io.geekidea.springbootplus.framework.shiro.jwt.JwtToken;
import io.geekidea.springbootplus.framework.shiro.util.SnowflakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 会话表 服务实现类
 *
 * @author wei
 * @since 2021-05-07
 */
@Slf4j
@Service
public class ImConversationServiceImpl extends BaseServiceImpl<ImConversationMapper, ImConversation> implements ImConversationService {

    @Autowired
    private ImConversationMapper imConversationMapper;

    @Autowired
    private ImConversationMembersService imConversationMembersService;

    @Autowired
    private ImConversationService imConversationService;

    @Autowired
    private ImClientService imClientService;

    @Autowired
    private ImApplicationService imApplicationService;

    @Autowired
    private ImMessageService imMessageService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveImConversation(ImConversation imConversation) throws Exception {
        return super.save(imConversation);
    }

    @Override
    public ApiResult<ImConversationCreateVo> createImConversation(ImConversationCreate imConversationCreate) {

        JwtToken jwtToken = (JwtToken) SecurityUtils.getSubject().getPrincipal();

        // 判断是否已经存在会话
        // 两个用户如果已经创建过会话,不能重复创建会话

        // 会话id
        Long imConversationId = SnowflakeUtil.getId();

        //  根据appKey查询appid
        ImApplication imApplication = imApplicationService.getOne(
                new QueryWrapper<ImApplication>().lambda().eq(ImApplication::getAppKey, jwtToken.getAppKey())
        );
        Long fkAppid = imApplication.getId();

        ImClient client = imClientService.getOne(new QueryWrapper<ImClient>().lambda()
                .eq(ImClient::getFkAppid, fkAppid)
                .eq(ImClient::getClientId, jwtToken.getClientId()));
        Long creator = client.getId();

        // 创建会话
        ImConversation imConversation = new ImConversation();
        imConversation.setId(imConversationId);
        imConversation.setCreateTime(new Date());
        imConversation.setLastMessage(null);
        imConversation.setFkAppid(fkAppid);
        imConversation.setCreator(creator);
        imConversation.setName(imConversationCreate.getName());

        JsonMapper jsonMapper = new JsonMapper();
        try {
            String writeValueAsString = jsonMapper.writeValueAsString(imConversationCreate.getAttributes());
            imConversation.setAttributes(writeValueAsString);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        imConversation.setSystem(false);
        imConversationService.save(imConversation);

        // 将自己添加到会话
        Long imConversationMembersId = SnowflakeUtil.getId();
        ImConversationMembers imConversationMembers = new ImConversationMembers();
        imConversationMembers.setId(imConversationMembersId);
        imConversationMembers.setCreateTime(new Date());
        imConversationMembers.setFkAppid(fkAppid);
        imConversationMembers.setFkConversationId(imConversationId);
        imConversationMembers.setFkClientId(creator);
        imConversationMembersService.save(imConversationMembers);

        // 将他人添加到会话
        for (String id : imConversationCreate.getClientIds()) {
            ImClient client2 = imClientService.getOne(new QueryWrapper<ImClient>().lambda()
                    .eq(ImClient::getFkAppid, fkAppid)
                    .eq(ImClient::getClientId, id));
            Long imConversationMembersId2 = SnowflakeUtil.getId();
            ImConversationMembers imConversationMembers2 = new ImConversationMembers();
            imConversationMembers2.setId(imConversationMembersId2);
            imConversationMembers2.setCreateTime(new Date());
            imConversationMembers2.setFkAppid(fkAppid);
            imConversationMembers2.setFkConversationId(imConversationId);
            imConversationMembers2.setFkClientId(client2.getId());
            imConversationMembersService.save(imConversationMembers2);
        }

        ImConversationCreateVo imConversationCreateVo = new ImConversationCreateVo();
        imConversationCreateVo.setId(imConversationId);

        return ApiResult.ok(imConversationCreateVo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateImConversation(ImConversation imConversation) throws Exception {
        return super.updateById(imConversation);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteImConversation(Long id) throws Exception {
        return super.removeById(id);
    }

    @Override
    public ImConversationQueryVo getImConversationById(Long id) throws Exception {
        return imConversationMapper.getImConversationById(id);
    }

    @Override
    public Paging<ImConversationQueryVo> getImConversationPageList(ImConversationPageParam imConversationPageParam) throws Exception {
        Page<ImConversationQueryVo> page = new PageInfo<>(imConversationPageParam, OrderItem.desc(getLambdaColumn(ImConversation::getCreateTime)));
        IPage<ImConversationQueryVo> iPage = imConversationMapper.getImConversationPageList(page, imConversationPageParam);
        return new Paging<ImConversationQueryVo>(iPage);
    }

    @Override
    public List<MyConversationListVo> getMyImConversationListAndMsgCount() throws Exception {

        ImClient client = imClientService.getClient();

        // 查询用户加入的所有会话 与每个会话的未读条数 成员
        List<MyConversationListVo> myImConversationListAndMsgCount = imConversationMapper.getMyImConversationListAndMsgCount(client.getId());
        JsonMapper jsonMapper = new JsonMapper();

        // 返回的
        List<MyConversationListVo> myImConversationListAndMsgCountNew = new ArrayList<>();

        // 转换json格式
        for (MyConversationListVo myconversationlistvo : myImConversationListAndMsgCount) {
            HashMap attributess = jsonMapper.readValue(myconversationlistvo.getAttribute(), HashMap.class);
            myconversationlistvo.setAttributes(attributess);

            // 查询会话的最后一条消息
            OfflineMsgDto lastMsg = imMessageService.getLastMsgByConversationId(myconversationlistvo.getId());
            myconversationlistvo.setLastMsg(lastMsg);

            myImConversationListAndMsgCountNew.add(myconversationlistvo);

        }
        return myImConversationListAndMsgCountNew;

    }


    @Override
    public List<ImConversation> getMyImConversationList() throws Exception {
        ImClient client = imClientService.getClient();
        return imConversationMapper.getMyImConversationList(client.getId());
    }

}
