package com.m2pool.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.m2pool.chat.config.CustomWebSocketConfig;
import com.m2pool.chat.dto.ChatRoomDto;
import com.m2pool.chat.entity.ChatRoom;
import com.m2pool.chat.mapper.ChatMessageMapper;
import com.m2pool.chat.mapper.ChatRoomMapper;
import com.m2pool.chat.service.ChatRoomService;
import com.m2pool.chat.vo.CharRoomVo;
import com.m2pool.chat.vo.RoomPageVo;
import com.m2pool.chat.vo.RoomVo;
import com.m2pool.chat.vo.UserMessageVo;
import com.m2pool.common.core.Result.R;
import com.m2pool.common.core.constant.HttpStatus;
import com.m2pool.common.core.utils.PageUtils;
import com.m2pool.common.core.web.page.TableDataInfo;
import com.m2pool.common.security.utils.SecurityUtils;
import com.m2pool.system.api.RemoteUserService;
import com.m2pool.system.api.entity.SysUser;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.user.SimpUser;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Service
public class ChatRoomServiceImpl extends ServiceImpl<ChatRoomMapper, ChatRoom> implements ChatRoomService {

    @Autowired
    private ChatRoomMapper chatRoomMapper;

    @Resource
    private ChatMessageMapper chatMessageMapper;

    @Resource
    private RemoteUserService remoteUserService;

    @Autowired
    private SimpUserRegistry userRegistry;

    @Resource
    private CustomWebSocketConfig webSocketConfig;

    @Override
    public TableDataInfo<ChatRoomDto> findRoomList(RoomPageVo roomPageVo) {
        String userEmail = SecurityUtils.getUsername();
        List<Long> ids = chatMessageMapper.findRoomIdsByCustomerEmail(userEmail);
        List<ChatRoomDto> roomList = new ArrayList<>();
        if (ids.isEmpty()){
            return getDataTable(roomList);
        }
        //1.查找当前客服对应的聊天室
        roomList = chatRoomMapper.findRoomList(ids,roomPageVo.getSendDateTime());


//        if (roomList.isEmpty()){
//            TableDataInfo tableDataInfo = new TableDataInfo();
//            tableDataInfo.setCode(HttpStatus.ERROR);
//            tableDataInfo.setMsg("当前客服暂无聊天室");
//            return tableDataInfo;
//        }
        return getDataTable(roomList);
    }

    private TableDataInfo<ChatRoomDto> getDataTable(List<ChatRoomDto> list)
    {
        TableDataInfo<ChatRoomDto> rspData = new TableDataInfo<ChatRoomDto>();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        PageInfo<ChatRoomDto> pageInfo = new PageInfo<ChatRoomDto>(list);
        rspData.setTotal(pageInfo.getTotal());
        rspData.setTotalPage(pageInfo.getPages());
        return rspData;
    }
    @Override
    @Transactional
    public R<ChatRoomDto> findRoomByUserid(RoomVo roomVo) {
        Random random = new Random();
        //1.查询当前用户与对应用户是否已存在创建的聊天室
        String userEmail = roomVo.getEmail();
        ChatRoomDto roomByUserEmail = chatRoomMapper.findRoomByUserEmail(userEmail);
        System.out.println("bby-用户邮箱"+roomByUserEmail);
        //获取nacos中配置的客服邮箱列表,这个列表中的邮箱实际可能不是客服角色，但能够行驶客服角色功能
        List<String> customerEmails = new ArrayList<>(Arrays.asList(webSocketConfig.getDefaultCustomerEmail().split(",")));
        int i = random.nextInt(customerEmails.size());
        String email = customerEmails.get(i);
        customerEmails.removeIf(email1 -> !checkOnline(email1));
        if(roomByUserEmail != null){
            System.out.println("bby-在线的客服"+customerEmails + "初始化分配的客服"+email+"聊天室信息"+roomByUserEmail);
            //1.1 客服在线，并且在客服列表
            if (checkOnline(roomByUserEmail.getUserEmail()) && customerEmails.contains(roomByUserEmail.getUserEmail())) {
                roomByUserEmail.setCustomerIsOnline(true);
            }
            // 1.2客服账号不在担任客服角色，选择使用nacos默认配置中的客服角色，并修改数据库中的聊天室信息为新的客服角色。
            if(!customerEmails.contains(roomByUserEmail.getUserEmail())){
                roomByUserEmail.setCustomerIsOnline(false);
                if (!customerEmails.isEmpty()){
                    email = customerEmails.get(random.nextInt(customerEmails.size()));
                    roomByUserEmail.setUserEmail(email);
                    roomByUserEmail.setCustomerIsOnline(true);
                }
                chatRoomMapper.updateById(ChatRoom.builder().id(roomByUserEmail.getId()).userTwoEmail(email).build());
            }
            // 1.3客服不在线，不在线情况如果从nacos配置中获取到多个客服,选择一个在线的客服发送。
            if (!checkOnline(roomByUserEmail.getUserEmail())){
                roomByUserEmail.setCustomerIsOnline(false);
                if (!customerEmails.isEmpty()){
                    roomByUserEmail.setCustomerIsOnline(true);
                    email = customerEmails.get(random.nextInt(customerEmails.size()));
                    roomByUserEmail.setUserEmail(email);
                }
            }
            return R.success(roomByUserEmail);
        }

        //2.不存在创建一个聊天室
        List<SysUser> data = remoteUserService.getCSList().getData();
        List<String> emails = data.stream().map(SysUser::getEmail).collect(Collectors.toList());
        emails.removeIf(email1 -> !checkOnline(email1));

        //如果当前没有客服角色账号，使用nacos 默认配置中的客服角色
        if(Collections.isEmpty(emails)){
            emails = customerEmails;
            // 自己不能创建
            if(emails.contains( userEmail)){
                return R.fail("您作为管理员无法创建与自己的连接");
            }
        }
        System.out.println("bby-在线的客服-创建聊天室emails"+emails);
        boolean customerIsOnline = false;
        //有在线客服，再次分配给在线的客服
        if (!emails.isEmpty()){
            customerIsOnline = true;
            email = emails.get(random.nextInt(emails.size()));
            System.out.println("bby-最终分配的在线客服"+email);
        }
        ChatRoom build = ChatRoom.builder()
                .userOneEmail(userEmail)
                .userTwoEmail(email)
                .build();
        try{
            int insert = chatRoomMapper.insetOrUpdateRoom(build);
            if (insert > 0){
                return R.success(ChatRoomDto.builder()
                        .id(build.getId())
                        .selfEmail(userEmail)
                        .customerIsOnline(customerIsOnline)
                        .userEmail(build.getUserTwoEmail()).build());
            }
        }catch (Exception e){
            return R.fail("聊天室已存在，创建聊天室失败");
        }

        return R.fail("聊天室不存在,并且创建聊天室失败");
    }

    /**
     * 检查用户是否在线
     * @return
     */
    private boolean checkOnline(String email){
        return userRegistry.getUsers().stream()
                .anyMatch(user -> user.getName().equals(email));
    }


    @Override
    public R<String> updateRoom(CharRoomVo charRoomVo) {
        int i = chatRoomMapper.updateById(ChatRoom.builder().id(charRoomVo.getId()).flag(charRoomVo.getFlag()).build());
        if(i > 0){
            return R.success("修改成功");
        }
        return R.fail("修改失败,不存在该聊天室");
    }
}
