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.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.ApiCode;
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.util.SnowflakeUtil;
import lombok.extern.slf4j.Slf4j;
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
    @Transactional(rollbackFor = Exception.class)
    public ApiResult<ImConversationCreateVo> createImConversation(ImConversationCreate imConversationCreate) {

        ImClient client = imClientService.getClient();

        // 成员不存在,不能创建会话
        for (String id : imConversationCreate.getClientIds()) {
            ImClient client2 = imClientService.getOne(new QueryWrapper<ImClient>().lambda()
                    .select(ImClient::getId)
                    .eq(ImClient::getFkAppid, client.getFkAppid())
                    .eq(ImClient::getClientId, id));
            if (client2 == null) {
                log.info("成员不存在,不能创建会话 client2 == null");
                return ApiResult.result(ApiCode.CLIENT_NOT_FOUNT, null);
            }
        }

        // 判断是否已经存在会话
        // 两个用户如果已经创建过会话,不能重复创建会话
        // size() == 1 为单聊的时候不允许重复创建
        if (imConversationCreate.getClientIds().size() == 1) {
            ImClient client2 = imClientService.getOne(new QueryWrapper<ImClient>().lambda()
                    .eq(ImClient::getFkAppid, client.getFkAppid())
                    .eq(ImClient::getClientId, imConversationCreate.getClientIds().get(0)));

            // 是否存在重复会话
            Integer repetitionConversation = getRepetitionConversation(client.getId(), client2.getId());
            if (repetitionConversation != 0) {

                log.debug("repetitionConversation != 0");
                // 返回已存在的会话id
                ImConversation repetitionConversationInfo = imConversationMapper.getRepetitionConversationInfo(client.getId(), client2.getId());
                ImConversationCreateVo imConversationCreateVo = new ImConversationCreateVo();
                imConversationCreateVo.setId(repetitionConversationInfo.getId());

                return ApiResult.ok(imConversationCreateVo);
            }
        }

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

        Long creator = client.getId();

        // 创建会话
        ImConversation imConversation = new ImConversation();
        imConversation.setId(imConversationId);
        imConversation.setCreateTime(new Date());
        imConversation.setLastMessage(null);
        imConversation.setFkAppid(client.getFkAppid());
        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(client.getFkAppid());
        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, client.getFkAppid())
                    .eq(ImClient::getClientId, id));
            Long imConversationMembersId2 = SnowflakeUtil.getId();
            ImConversationMembers imConversationMembers2 = new ImConversationMembers();
            imConversationMembers2.setId(imConversationMembersId2);
            imConversationMembers2.setCreateTime(new Date());
            imConversationMembers2.setFkAppid(client.getFkAppid());
            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());
    }

    @Override
    public Integer getRepetitionConversation(Long clientId1, Long clientId2) {
        return imConversationMapper.getRepetitionConversation(clientId1, clientId2);
    }

}
