package com.huiju.estateagents.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.TaChat;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.mapper.TaChatMapper;
import com.huiju.estateagents.mapper.TaPersonMapper;
import com.huiju.estateagents.service.IMiniAppService;
import com.huiju.estateagents.service.ITaChatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.websocket.ChatServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 聊天记录表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-05-10
 */
@Service
public class TaChatServiceImpl extends ServiceImpl<TaChatMapper, TaChat> implements ITaChatService {

    @Autowired
    TaPersonMapper taPersonMapper;

    @Autowired
    TaChatMapper taChatMapper;

    @Autowired
    IMiniAppService miniAppService;

    @Override
    public ResponseBean getChatHistory(String openid, String chatWith, int pageNumber, int pageSize) {
        QueryWrapper<TaPerson> query = new QueryWrapper<>();
        query.eq("mini_openid", openid);
        List<TaPerson> taPersons = taPersonMapper.selectList(query);

        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证当前人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        String fromPerson = taPersons.get(0).getPersonId();

        IPage<TaChat> page = new Page<>();
        page.setCurrent(pageNumber);
        page.setSize(pageSize);

        List<TaChat> result = taChatMapper.getChatHistory(page, fromPerson, chatWith);
        page.setRecords(result);

        updateMessageStatus(chatWith,fromPerson,CommConstant.MESSAGE_READED);

        return ResponseBean.success(page);
    }

    @Override
    public ResponseBean getChatWithList(String openid, int pageNumber, int pageSize) {
        List<TaPerson> taPersons = taPersonMapper.getPersonByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证当前人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        String personId = taPersons.get(0).getPersonId();
        IPage<TaChat> page = new Page<>();
        page.setCurrent(pageNumber);
        page.setSize(pageSize);
        List<TaChat> result = taChatMapper.getChatWith(page, personId);

        List<Map<String, Object>> friendList = new ArrayList<>();
        if (null != result && result.size() > 0) {
            for (TaChat taChat: result) {
                if (null != taChat.getSendPerson() && null != taChat.getSendAvatar() && null != taChat.getSendName() && null != taChat.getReceivePerson()){
                    boolean isSend = taChat.getSendPerson().equals(personId) ? true : false;
                    String chatWith = isSend ? taChat.getReceivePerson() : taChat.getSendPerson();
                    String name = isSend ? taChat.getReceiveName() : taChat.getSendName();
                    String chatAvatar = isSend ? taChat.getReceiveAvatar() : taChat.getSendAvatar();
                    Integer unReadNum = taChatMapper.getUnReadMessage(personId, chatWith);

                    Map<String, Object> friend = new HashMap<>();
                    friend.put("friendId", chatWith);
                    friend.put("name", name);
                    friend.put("avatar", chatAvatar);
                    friend.put("messageType", taChat.getMessageType());
                    friend.put("message", taChat.getMessage());
                    friend.put("createDate", taChat.getCreateDate());
                    friend.put("unReadNum", unReadNum);
                    friend.put("isSend", isSend);

                    friendList.add(friend);
                }
            }
        }

        Map<String, Object> resp = new HashMap<>();
        resp.put("total", page.getTotal());
        resp.put("size", page.getSize());
        resp.put("current", page.getCurrent());
        resp.put("pages", page.getPages());
        resp.put("records", friendList);

        return ResponseBean.success(resp);
    }

    @Override
    public ResponseBean chat(JSONObject message) {
        System.out.println("进入聊天");
        TaChat taChat = new TaChat();
        taChat.setCreateDate(LocalDateTime.now());
        taChat.setMessage((String) message.get("message"));
        taChat.setMessageType((String) message.get("messageType"));
        taChat.setIsRead(CommConstant.MESSAGE_UNREAD);

        TaPerson from = taPersonMapper.selectById((String) message.get("sendPerson"));
        if (null != from) {
            taChat.setSendPerson(from.getPersonId());
            taChat.setSendName(from.getNickname());
            taChat.setSendAvatar(from.getAvatarurl());
        }

        TaPerson to = taPersonMapper.selectById((String) message.get("receivePerson"));
        if (null != to) {
            taChat.setReceivePerson(to.getPersonId());
            taChat.setReceiveName(StringUtils.ifNull(to.getNickname(), to.getName()));
            taChat.setReceiveAvatar(StringUtils.ifNull(to.getAvatarurl(), to.getPhoto()));

            boolean isOnline = ChatServer.isOnline(to.getPersonId());
            if (!isOnline && null != from) {
                // 推送微信消息
                String[] its = {
                        String.format("sendId=%s", from.getPersonId()),
                        String.format("sendName=%s", StringUtils.urlEncode(StringUtils.ifNull(from.getName(), from.getNickname()))),
                        String.format("receiverId=%s", to.getPersonId()),
                        String.format("receiverName=%s", StringUtils.urlEncode(StringUtils.ifNull(to.getName(), to.getNickname())))
                };
                String link = "/pages/im/index?"+String.join("&", its);

                miniAppService.sendNoticeMessage(to, link, StringUtils.ifNull(from.getName(), from.getNickname()), StringUtils.ifNull(from.getTel(), from.getPhone()), "给您发送了一条新消息, 请查收", LocalDateTime.now());
            } else {
//                taChat.setIsRead(CommConstant.MESSAGE_READED);
            }
        }

        taChatMapper.insert(taChat);
        return ResponseBean.success(taChat);
    }

    @Override
    public ResponseBean updateMessageReadedOf(String openid) {
        QueryWrapper<TaPerson> query = new QueryWrapper<>();
        query.eq("mini_openid", openid);
        List<TaPerson> taPersons = taPersonMapper.selectList(query);

        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证当前人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }

        String fromPerson = taPersons.get(0).getPersonId();

        // 更新所有未读为已读
        updateMessageStatus(fromPerson, null, CommConstant.MESSAGE_READED);

        return ResponseBean.success("");
    }

    private int updateMessageStatus(String from, String to, int status) {
        // 更新所有未读为已读
        UpdateWrapper<TaChat> wrapper = new UpdateWrapper<>();
        wrapper.set("is_read", status);
        wrapper.eq(null != from, "send_person", from);
        wrapper.eq(null != to, "receive_person", to);
        return taChatMapper.update(new TaChat(), wrapper);
    }

    private int updateMessageStateOfPerson(String person) {
        UpdateWrapper<TaChat> wrapper = new UpdateWrapper<>();
        wrapper.set("is_read", CommConstant.MESSAGE_READED);
        wrapper.eq("send_person", person).or().eq("receive_person", person);
        return taChatMapper.update(new TaChat(), wrapper);
    }
}
