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.entity.ImMessage;
import com.wecloud.im.entity.ImMessageOnlineSend;
import com.wecloud.im.mapper.ImMessageMapper;
import com.wecloud.im.param.ImHistoryMessagePageParam;
import com.wecloud.im.param.add.ImMsgRecall;
import com.wecloud.im.param.add.ImMsgUpdate;
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.ImMessageOfflineListVo;
import com.wecloud.im.vo.OfflineMsgDto;
import com.wecloud.im.ws.enums.WsResponseCmdEnum;
import com.wecloud.im.ws.model.WsResponseModel;
import com.wecloud.im.ws.model.request.PushModel;
import com.wecloud.im.ws.sender.PushTask;
import com.wecloud.im.ws.service.WriteDataService;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
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.List;

/**
 * 消息存储表 服务实现类
 *
 * @author wei
 * @since 2021-04-29
 */
@Slf4j
@Service
public class ImMessageServiceImpl extends BaseServiceImpl<ImMessageMapper, ImMessage> implements ImMessageService {

    @Autowired
    private ImMessageMapper imMessageMapper;

    @Autowired
    private ImClientService imClientService;

    @Autowired
    private ImConversationService imConversationService;

    @Autowired
    private PushTask pushTask;

    @Autowired
    private ImApplicationService imApplicationService;


    @Autowired
    private ImConversationMembersService imConversationMembersService;

    @Autowired
    private WriteDataService writeDataService;

    @Override
    public ImMessage saveImMessage(ImApplication imApplication, ImClient imClientSender, Long toConversationId, long messageId, String content) {

        ImMessage imMessage = new ImMessage();
        imMessage.setId(messageId);
        imMessage.setCreateTime(new Date());
        imMessage.setFkAppid(imApplication.getId());
        imMessage.setSender(imClientSender.getId());
        imMessage.setContent(content);
        imMessage.setWithdraw(false);
        imMessage.setEvent(false);
        imMessage.setSystem(false);
        imMessage.setSendStatus(2);
        imMessage.setFkConversationId(toConversationId);
        this.save(imMessage);
        return imMessage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult<Boolean> updateMsgWithdrawById(ImMsgRecall imMsgRecall) {
        ImClient imClientSender = imClientService.getCurentClient();

        // 查询imApplication
        ImApplication imApplication = imApplicationService.getById(imClientSender.getFkAppid());
        if (imApplication == null) {
            log.info("imApplication为空");
            return ApiResult.fail();
        }

        // 判断该消息是否是该客户端发送
        ImMessage messageById = this.getById(imMsgRecall.getMsgId());
        if (!messageById.getSender().equals(imClientSender.getId())) {
            log.error("判断该消息是否是该客户端发送");
            return ApiResult.fail();
        }
        if (messageById.getWithdraw()) {
            return ApiResult.ok();
        }

        // 修改消息体
        messageById.setWithdraw(Boolean.TRUE);
        messageById.setWithdrawTime(new Date());
        // 清空消息
        messageById.setContent("{}");
        boolean saveOk = this.updateById(messageById);

        if (saveOk) {


            // 查询该会话所有成员
            List<ImConversationMembers> membersList = imConversationMembersService.list(
                    new QueryWrapper<ImConversationMembers>().lambda()
                            .eq(ImConversationMembers::getFkConversationId, messageById.getFkConversationId())
                            .notIn(ImConversationMembers::getFkClientId, imClientSender.getId())
            );
            if (membersList.isEmpty()) {
                log.info("membersList为空,toConversationId:" + messageById.getFkConversationId());
                return ApiResult.fail();

            }
            // 遍历发送
            for (ImConversationMembers conversationMembers : membersList) {
//                // 保存收件箱
//                long imInboxId = SnowflakeUtil.getId();
//                ImInbox imInbox = new ImInbox();
//                imInbox.setId(imInboxId);
//                imInbox.setCreateTime(new Date());
//                imInbox.setFkAppid(imApplication.getId());
//                imInbox.setReceiver(conversationMembers.getFkClientId());
//                imInbox.setFkMsgId(messageId);
//                imInbox.setReadMsgStatus(0);
//                imInbox.setReceiverMsgStatus(0);
//                imInbox.setFkConversationId(toConversationId);
//                imInboxService.save(imInbox);

                // 查询接收方
                ImClient imClientReceiver = imClientService.getOne(new QueryWrapper<ImClient>().lambda()
                        .eq(ImClient::getFkAppid, imApplication.getId())
                        .eq(ImClient::getId, conversationMembers.getFkClientId()));
                if (imClientReceiver == null) {
                    continue;
                }

                // 封装响应的实体
                ImMessageOnlineSend imMessageOnlineSend = new ImMessageOnlineSend();
                BeanUtils.copyProperties(messageById, imMessageOnlineSend);
                imMessageOnlineSend.setMsgId(messageById.getId());
                imMessageOnlineSend.setSender(imClientSender.getClientId());
                imMessageOnlineSend.setContent(null);
                imMessageOnlineSend.setConversationId(conversationMembers.getFkConversationId());
                imMessageOnlineSend.setWithdraw(Boolean.TRUE);
                imMessageOnlineSend.setEvent(Boolean.TRUE);

                //  向接收方推送
                WsResponseModel<ImMessageOnlineSend> responseModel = new WsResponseModel<>();
                responseModel.setCmd(WsResponseCmdEnum.ONLINE_EVENT_MSG.getCmdCode());
                ApiResult<Boolean> result = ApiResult.result(ApiCode.SUCCESS);
                responseModel.setCode(result.getCode());
                responseModel.setMsg(result.getMessage());
                responseModel.setData(imMessageOnlineSend);
                responseModel.setReqId(null);
                writeDataService.write(responseModel, imApplication.getAppKey(), imClientReceiver.getClientId());

                // 获取自定义推送字段
                PushModel pushModel = imMsgRecall.getPush();

                // 异步推送系统通知消息
                pushTask.push(pushModel, imClientReceiver, imApplication);
            }

            return ApiResult.ok();

        } else {
            return ApiResult.fail();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult<Boolean> updateMsgById(ImMsgUpdate imMsgUpdate) {

//        ImClient client = imClientService.getCurentClient();

/*        // 判断该消息是否是该客户端发送
        ImMessage messageById = this.getById(imMsgUpdate.getId());
        if (!messageById.getSender().equals(client.getId())) {
            log.error("判断该消息是否是该客户端发送");
            return ApiResult.fail();
        }*/

        ImMessage imMessage = new ImMessage();
        imMessage.setId(imMsgUpdate.getMsgId());

        JsonMapper jsonMapper = new JsonMapper();

        try {
            String content = jsonMapper.writeValueAsString(imMsgUpdate.getContent());
            imMessage.setContent(content);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return ApiResult.fail();
        }

        if (this.updateById(imMessage)) {
            return ApiResult.ok();
        } else {
            return ApiResult.fail();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveImMessage(ImMessage imMessage) throws Exception {
        return super.save(imMessage);
    }
//
//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public boolean updateImMessage(ImMessage imMessage) throws Exception {
//        return super.updateById(imMessage);
//    }
//
//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public boolean deleteImMessage(Long id) throws Exception {
//        return super.removeById(id);
//    }
//
//    @Override
//    public ImMessageQueryVo getImMessageById(Long id) throws Exception {
//        return imMessageMapper.getImMessageById(id);
//    }
//
//    @Override
//    public Paging<ImMessageQueryVo> getImMessagePageList(ImMessagePageParam imMessagePageParam) throws Exception {
//        Page<ImMessageQueryVo> page = new PageInfo<>(imMessagePageParam, OrderItem.desc(getLambdaColumn(ImMessage::getCreateTime)));
//        IPage<ImMessageQueryVo> iPage = imMessageMapper.getImMessagePageList(page, imMessagePageParam);
//        return new Paging<ImMessageQueryVo>(iPage);
//    }

    @Override
    public Paging<OfflineMsgDto> getHistoryMsgConversationId(ImHistoryMessagePageParam imHistoryMessagePageParam) throws Exception {
        Page<ImMessage> page = new PageInfo<>(imHistoryMessagePageParam, OrderItem.desc(getLambdaColumn(ImMessage::getCreateTime)));

        IPage<OfflineMsgDto> iPage = imMessageMapper.getHistoryMsgConversationId(page, imHistoryMessagePageParam);

        return new Paging<>(iPage);
    }


    /**
     * 查询用户所有离线消息
     *
     * @return
     * @throws Exception
     */
    @Override
    public List<ImMessageOfflineListVo> getOfflineList() throws Exception {

        // 返回数据
        List<ImMessageOfflineListVo> imMessageOfflineListVoList = new ArrayList<>();

        ImClient client = imClientService.getCurentClient();

        // 获取加入的所有会话
        List<ImConversation> myImConversationList = imConversationService.getMyImConversationList();

        // 遍历会话列表, 查询每个会话列表的离线消息
        for (ImConversation imConversation : myImConversationList) {

            //根据客户端id与会话id 查询离线消息
            List<OfflineMsgDto> offlineListByClientAndConversation = this.getOfflineListByClientAndConversation(client.getId(), imConversation.getId());

            // 房间消息为空则不添加
            if (offlineListByClientAndConversation.isEmpty()) {
                continue;
            }
            ImMessageOfflineListVo imMessageOfflineListVo = new ImMessageOfflineListVo();
            imMessageOfflineListVo.setMsgList(offlineListByClientAndConversation);
            imMessageOfflineListVo.setConversationId(imConversation.getId());
            imMessageOfflineListVoList.add(imMessageOfflineListVo);
        }

        return imMessageOfflineListVoList;
    }

    /**
     * 根据客户端id与会话id 查询离线消息
     *
     * @param clientId
     * @param conversationId
     * @return
     */
    @Override
    public List<OfflineMsgDto> getOfflineListByClientAndConversation(Long clientId, Long conversationId) {
        return imMessageMapper.getOfflineListByClientAndConversation(clientId, conversationId);
    }


    @Override
    public OfflineMsgDto getReceivedLastMsgByConversationId(Long clientId, Long conversationId) {
        return imMessageMapper.getReceivedLastMsgByConversationId(clientId, conversationId);
    }

    @Override
    public OfflineMsgDto getLastMsgByConversationId(Long conversationId) {
        return imMessageMapper.getLastMsgByConversationId(conversationId);
    }


}
