package com.fs.qw.service.impl;

import com.alibaba.fastjson.JSON;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.StringUtils;
import com.fs.qw.domain.*;
import com.fs.qw.event.EventAuthqrcode;
import com.fs.qw.mapper.*;
import com.fs.qw.service.IQwEventAuthService;
import com.fs.qw.service.IQwUserService;
import com.fs.qw.utils.QwAllUtil;
import com.fs.qw.utils.QwRedisUtil;
import com.fs.qw.vo.QwContactVO;
import com.fs.qw.vo.QwLabelVO;
import com.fs.qw.vo.QwRoomListVO;
import com.fs.qw.vo.QwRoomMember;
import lombok.Synchronized;
import org.apache.commons.codec.digest.DigestUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.fs.qw.utils.QwAllUtil.*;
import static com.fs.qw.utils.QwUtil.*;

@Service
public class QwEventAuthServiceImpl implements IQwEventAuthService {
    @Autowired
    private QwRedisUtil qwRedisUtil;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private QwAccountMapper qwAccountMapper;
    @Autowired
    private QwContactMapper qwContactMapper;
    @Autowired
    private QwLabelMapper qwLabelMapper;
    @Autowired
    private QwRoomMapper qwRoomMapper;
    @Autowired
    private QwRoomMemberMapper qwRoomMemberMapper;
    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private QwConversationMapper conversationMapper;

    @Autowired
    private QwInnerContactMapper innerContactMapper;

    @Autowired
    private IQwUserService qwUserService;


    @Override
    public R EventAuthqrcode(String deviceId, EventAuthqrcode authqrcode) {
        String authqrcodeJson = redisCache.getCacheObject("qw_login:"+deviceId);
        if (StringUtils.isNotEmpty(authqrcodeJson)){
            EventAuthqrcode qrKey = JSON.parseObject(authqrcodeJson, EventAuthqrcode.class);
            if (authqrcode.getKey().equals(qrKey.getKey())){
                // 转换为 JSON
                String json = toJson(authqrcode);
                redisCache.setCacheObject("qw_login:"+deviceId,json,604800, TimeUnit.SECONDS);
            }
            return R.ok();
        }else {
            return R.error();
        }
    }

    @Override
    @Synchronized
    public void EventAuthOnline(String deviceId, QwUser qwUser) {
        //获取联系人列表
        QwContactReturn qwContactReturn = contactList(null,deviceId);
        List<QwContactVO> list = qwContactReturn.getContacts();
        list.stream()
                //判断过滤
                .filter(vo -> qwContactMapper.selectQwContactByHomeUserId(vo.getUserId(), qwUser.getUserId().toString()) == null)
                .map(vo -> {
                    //组装入库实体
                    QwContact qwContact = new QwContact();
                    BeanUtils.copyProperties(vo, qwContact);
                    qwContact.setRemarkPhone(toJson(vo.getRemarkPhone()));
                    qwContact.setLabels(toJson(vo.getLabels()));
                    qwContact.setDescribes(vo.getDesc());
                    qwContact.setHomeUserId(qwUser.getUserId().toString());
                    return qwContact;
                })
                .forEach(qwContactMapper::insertQwContact);
        //获取内部联系人列表
        QwInnerContactReturn qwInnerContactReturn = innerContactList("0",deviceId);
        List<QwContactVO> innerList = qwInnerContactReturn.getContacts();
        for (QwContactVO vo : innerList){
            QwInnerContact innerContact = innerContactMapper.selectInnerContactById(vo.getUserId());
            if (innerContact == null){
                innerContact = new QwInnerContact();
                BeanUtils.copyProperties(vo, innerContact);
                innerContact.setRemarkPhone(toJson(vo.getRemarkPhone()));
                innerContact.setLabels(toJson(vo.getLabels()));
                innerContact.setDescribes(vo.getDesc());
                innerContactMapper.insertQwInnerContact(innerContact);
            }

        }
        //获取标签列表
        List<QwLabelVO> labelList = labelList(deviceId);
        labelList.stream()
                .filter(vo -> qwLabelMapper.selectLabelByHomeUser(vo.getLabelId(), qwUser.getUserId().toString()) == null)
                .map(vo -> {
                    QwLabel qwLabel = new QwLabel();
                    BeanUtils.copyProperties(vo, qwLabel);
                    qwLabel.setHomeUserId(qwUser.getUserId().toString());
                    return qwLabel;
                })
                .forEach(qwLabelMapper::insertQwLabel);
        //获取群列表
        QwRoomReturn roomReturn = QwAllUtil.roomList(null,deviceId);
        List<QwRoomListVO> roomList = roomReturn.getRooms();
        roomList.stream()
                .filter(vo -> qwRoomMapper.selectRoomByRoomId(vo.getRoomId()) == null)
                .forEach(vo -> {
                    QwRoom qwRoom = new QwRoom();
                    BeanUtils.copyProperties(vo, qwRoom);
                    qwRoom.setAdminList(toJson(vo.getAdminList()));
                    qwRoomMapper.insertQwRoom(qwRoom);
                    //获取成成员列表
                    List<QwRoomMember> roomMembers = vo.getMemberList();
                    for(QwRoomMember roomMember : roomMembers){
                        QwRoomMember qwRoomMember = qwRoomMemberMapper.selectQwRoomMemberByUserId(roomMember.getUserId(), qwRoom.getRoomId());
                        if (qwRoomMember==null){
                            roomMember.setRoomId(vo.getRoomId());
                            qwRoomMemberMapper.insertQwRoomMember(roomMember);
                        }
                    }
                });
        QwUser qwUser1 = qwUserService.selectQwUserById(qwUser.getUserId());
        if (qwUser1 == null){
            //组装各类列表的seq增同步
            qwUser.setSeq(qwContactReturn.getSeq());
            qwUser.setRoomSeq(roomReturn.getSeq());
            qwUser.setInnerSeq(qwInnerContactReturn.getSeq());
            //将seq存入redis定时获取同步信息
            redisCache.setCacheObject("qw_seq:"+deviceId,toJson(qwUser),15, TimeUnit.DAYS);
            qwUserService.insertQwUser(qwUser);
        }else {
            qwUserMapper.updateUserDevice(qwUser1.getUserId(), deviceId);
        }
    }

    @Override
    @Synchronized
    public void ContactChangedLogs(Long userId,String deviceId) {
        QwUser qwUser = qwUserService.selectQwUserById(userId);
        if (qwUser != null){
            //获取联系人返回
            QwContactReturn qwContactReturn = contactList(qwUser.getSeq(),deviceId);
            //获取内部联系人返回
            QwInnerContactReturn qwInnerContactReturn = innerContactList(qwUser.getInnerSeq(),deviceId);
            //判断变更的联系人集合是否为空
            if (qwContactReturn.getContacts().size()!=0){
                qwUser.setSeq(qwContactReturn.getSeq());
                qwUserService.updateQwUser(qwUser);
                List<QwContactVO> list = qwContactReturn.getContacts();
                for (QwContactVO vo:list){
                    QwContact qwContact = qwContactMapper.selectQwContactByHomeUserId(vo.getUserId(), qwUser.getUserId().toString());
                    //判断联系人在库中是否存在
                    if (qwContact!=null){
                        //存在的话执行update操作
                        BeanUtils.copyProperties(vo,qwContact);
                        qwContact.setRemarkPhone(toJson(vo.getRemarkPhone()));
                        qwContact.setLabels(toJson(vo.getLabels()));
                        qwContact.setDescribes(vo.getDesc());
                        qwContact.setHomeUserId(qwUser.getUserId().toString());
                        qwContactMapper.updateQwContact(qwContact);
                        //更新会话中ext
                        QwEventMessageServiceImpl qwEventMessageService = new QwEventMessageServiceImpl();
                        String conver = qwEventMessageService.sortAndCombine(qwUser.getUserId().toString(),qwContact.getUserId().toString());
                        String conversationId = DigestUtils.md5Hex(conver);
                        QwConversation qwConversation = conversationMapper.selectConByConversationId(conversationId);
                        if (qwConversation!=null){
                            List<QwConversationExt> extList = new ArrayList<>();
                            QwConversationExt qwConversationExt = new QwConversationExt();
                            QwConversationExt qwConversationExt1 = new QwConversationExt();
                            qwConversationExt1.setUserId(qwUser.getUserId());
                            qwConversationExt1.setNickName(qwUser.getNickName());
                            qwConversationExt1.setAvatar(qwUser.getAvatar());
                            qwConversationExt1.setRemark("");
                            qwConversationExt.setUserId(vo.getUserId());
                            qwConversationExt.setNickName(vo.getNickName());
                            qwConversationExt.setAvatar(vo.getAvatar());
                            qwConversationExt.setRemark(qwContact.getRemark());
                            extList.add(qwConversationExt);
                            extList.add(qwConversationExt1);
                            String ext = toJson(extList);
                            conversationMapper.updateExt(conversationId,ext);
                        }
                    }else {
                        qwContact = new QwContact();
                        BeanUtils.copyProperties(vo,qwContact);
                        qwContact.setRemarkPhone(toJson(vo.getRemarkPhone()));
                        qwContact.setLabels(toJson(vo.getLabels()));
                        qwContact.setDescribes(vo.getDesc());
                        qwContact.setHomeUserId(qwUser.getUserId().toString());
                        //不存在的话新增
                        qwContactMapper.insertQwContact(qwContact);
                    }
                }
            }
            //判断变更的内部联系人集合是否为空
            if (qwInnerContactReturn.getContacts().size()!=0){
                qwUser.setInnerSeq(qwInnerContactReturn.getSeq());
                //更新user中的innerSeq
                qwUserService.updateQwUser(qwUser);
                List<QwContactVO> list = qwInnerContactReturn.getContacts();
                for (QwContactVO vo:list){
                    QwInnerContact qwInnerContact = innerContactMapper.selectInnerContactByUserId(qwUser.getCorpId(),vo.getUserId());
                    //判断联系人在库中是否存在
                    if (qwInnerContact!=null){
                        //存在的话执行update操作
                        BeanUtils.copyProperties(vo,qwInnerContact);
                        qwInnerContact.setRemarkPhone(toJson(vo.getRemarkPhone()));
                        qwInnerContact.setLabels(toJson(vo.getLabels()));
                        qwInnerContact.setDescribes(vo.getDesc());
                        innerContactMapper.updateQwInnerContact(qwInnerContact);
                        //更新会话中ext
                        QwEventMessageServiceImpl qwEventMessageService = new QwEventMessageServiceImpl();
                        String conver = qwEventMessageService.sortAndCombine(qwUser.getUserId().toString(),qwInnerContact.getUserId().toString());
                        String conversationId = DigestUtils.md5Hex(conver);
                        QwConversation qwConversation = conversationMapper.selectConByConversationId(conversationId);
                        if (qwConversation!=null){
                            List<QwConversationExt> extList = new ArrayList<>();
                            QwConversationExt qwConversationExt = new QwConversationExt();
                            QwConversationExt qwConversationExt1 = new QwConversationExt();
                            qwConversationExt1.setUserId(qwUser.getUserId());
                            qwConversationExt1.setNickName(qwUser.getNickName());
                            qwConversationExt1.setAvatar(qwUser.getAvatar());
                            qwConversationExt1.setRemark("");
                            qwConversationExt.setUserId(vo.getUserId());
                            qwConversationExt.setNickName(vo.getNickName());
                            qwConversationExt.setAvatar(vo.getAvatar());
                            qwConversationExt.setRemark(qwInnerContact.getRemark());
                            extList.add(qwConversationExt);
                            extList.add(qwConversationExt1);
                            String ext = toJson(extList);
                            conversationMapper.updateExt(conversationId,ext);
                        }
                    }else {
                        qwInnerContact = new QwInnerContact();
                        BeanUtils.copyProperties(vo,qwInnerContact);
                        qwInnerContact.setRemarkPhone(toJson(vo.getRemarkPhone()));
                        qwInnerContact.setLabels(toJson(vo.getLabels()));
                        qwInnerContact.setDescribes(vo.getDesc());
                        //不存在的话新增
                        innerContactMapper.insertQwInnerContact(qwInnerContact);
                    }
                }
            }
            //将seq存入redis定时获取同步信息
            redisCache.setCacheObject("qw_seq:"+deviceId,toJson(qwUser),15, TimeUnit.DAYS);
        }
    }

    @Override
    public void RoomChangedLogs(Long userId, String deviceId) {
        QwUser qwUser = qwUserService.selectQwUserById(userId);
        if (qwUser != null){
            QwRoomReturn qwRoomReturn = roomList(qwUser.getRoomSeq(),deviceId);
            //判断变更的群组集合是否为空
            if (qwRoomReturn.getRooms().size()!=0){
                qwUser.setRoomSeq(qwRoomReturn.getSeq());
                qwUserService.updateQwUser(qwUser);
                List<QwRoomListVO> list = qwRoomReturn.getRooms();
                for (QwRoomListVO vo:list){
                    QwRoom qwRoom = qwRoomMapper.selectRoomByRoomId(vo.getRoomId());
                    //判断群聊在库中是否存在
                    if (qwRoom!=null){
                        //存在的话执行update操作
                        BeanUtils.copyProperties(vo, qwRoom);
                        qwRoom.setAdminList(toJson(vo.getAdminList()));
                        qwRoomMapper.updateQwRoom(qwRoom);
                        //更新会话中ext
                        QwConversation qwConversation = conversationMapper.selectConByConversationId(vo.getRoomId().toString());
                        if (qwConversation!=null){
                            List<QwRoomMember> roomMembers = vo.getMemberList();
                            String ancestors = roomMembers.stream()
                                    .map(QwRoomMember::getUserId)
                                    .map(Object::toString)
                                    .collect(Collectors.joining(","));
                            qwConversation.setAncestors(ancestors);
                            //组装群聊会话的ext
                            Map<String,Object> extMap = new HashMap<>();
                            extMap.put("roomId",vo.getRoomId());
                            extMap.put("roomAvatar","https://hos-1309931967.cos.ap-chongqing.myqcloud.com/fs/20231025/faf2cbc41c9a4921b8218dec0a610a38.jpeg");
                            extMap.put("roomName",vo.getRoomName());
                            String ext = toJson(extMap);
                            qwConversation.setExt(ext);
                            conversationMapper.updateExt(qwConversation.getConversationId(),ext);
                        }
                    }else {
                        qwRoom = new QwRoom();
                        BeanUtils.copyProperties(vo,qwRoom);
                        qwRoom.setAdminList(toJson(vo.getAdminList()));
                        qwRoomMapper.insertQwRoom(qwRoom);
                        List<QwRoomMember> roomMembers = vo.getMemberList();
                        roomMembers.forEach(qwRoomMember -> {
                            qwRoomMember.setRoomId(vo.getRoomId());
                            qwRoomMemberMapper.insertQwRoomMember(qwRoomMember);
                        });
                    }
                }
            }
        }
    }

    @Override
    public void updateRoomExt(Long roomId,String roomName) {
        QwConversation qwConversation = conversationMapper.selectConByConversationId(roomId.toString());
        if (qwConversation!=null) {
            Map<String, Object> extMap = new HashMap<>();
            extMap.put("roomId", roomId);
            extMap.put("roomAvatar", "https://hos-1309931967.cos.ap-chongqing.myqcloud.com/fs/20231025/faf2cbc41c9a4921b8218dec0a610a38.jpeg");
            extMap.put("roomName", roomName);
            String ext = toJson(extMap);
            conversationMapper.updateExt(roomId.toString(), ext);
        }
    }


    @Override
    public void updateRoomAncestors(Long roomId) {
        QwConversation qwConversation = conversationMapper.selectConByConversationId(roomId.toString());
        if (qwConversation !=null){
            List<QwRoomMember> roomMembers = qwRoomMemberMapper.selectQwRoomMemberByRoomId(roomId);
            String ancestors = roomMembers.stream()
                    .map(QwRoomMember::getUserId)
                    .map(Object::toString)
                    .collect(Collectors.joining(","));
            conversationMapper.updateAncestors(roomId.toString(), ancestors);
        }
    }
}
