package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.domain.SocketMessage;
import com.ruoyi.system.domain.vo.SocketMessageVo;
import com.ruoyi.system.mapper.SocketMessageMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import liquibase.pro.packaged.S;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.SocketContactBo;
import com.ruoyi.system.domain.vo.SocketContactVo;
import com.ruoyi.system.domain.SocketContact;
import com.ruoyi.system.mapper.SocketContactMapper;
import com.ruoyi.system.service.ISocketContactService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 通信目录Service业务层处理
 *
 * @author hdka
 * @date 2024-10-21
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SocketContactServiceImpl implements ISocketContactService {

    private final SocketContactMapper baseMapper;

    private final SysUserMapper sysUserMapper;

    private final SocketMessageMapper socketMessageMapper;

    /**
     * 查询通信目录
     */
    @Override
    public SocketContactVo queryById(Long id) {
        SocketContactVo socketContactVo = baseMapper.selectVoById(id);
        LambdaQueryWrapper<SocketMessage> socketMessageLambdaQueryWrapper = new LambdaQueryWrapper<>();
        socketMessageLambdaQueryWrapper.eq(SocketMessage::getRoomId, socketContactVo.getRoomId())
                .eq(SocketMessage::getContactId, id);
        Long userId = LoginHelper.getUserId();
        socketContactVo.setUser(sysUserMapper.selectUserById(Objects.equals(socketContactVo.getContactUserId(), userId) ?socketContactVo.getUserId():socketContactVo.getContactUserId()));
        List<SocketMessageVo> socketMessageVos = socketMessageMapper.selectVoList(socketMessageLambdaQueryWrapper);
        socketMessageVos.stream()
                        .peek(item->{
                            SysUser sysUser = sysUserMapper.selectUserById(item.getUserId());
                            item.setUser(sysUser);
                        }).collect(Collectors.toList());
        socketContactVo.setMessages(socketMessageVos);

        return socketContactVo;
    }

    /**
     * 查询通信目录列表
     */
    @Override
    public TableDataInfo<SocketContactVo> queryPageList(SocketContactBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SocketContact> socketContactLambdaQueryWrapper = buildQueryWrapper(bo);
        Page<SocketContactVo> result = baseMapper.selectVoPage(pageQuery.build(), socketContactLambdaQueryWrapper);
        for (SocketContactVo record : result.getRecords()) {
            SysUser sysUser = sysUserMapper.selectUserById(Objects.equals(record.getContactUserId(), bo.getUserId()) ? record.getUserId() : record.getContactUserId());
            record.setUser(sysUser);
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询通信目录列表
     */
    @Override
    public List<SocketContactVo> queryList(SocketContactBo bo) {
        LambdaQueryWrapper<SocketContact> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SocketContact> buildQueryWrapper(SocketContactBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SocketContact> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, SocketContact::getContactUserId, bo.getUserId())
                        .or()
        .eq(bo.getUserId() != null, SocketContact::getUserId, bo.getUserId());
        return lqw;
    }

    /**
     * 新增通信目录
     */
    @Override
    public Boolean insertByBo(SocketContactBo bo) {


        // 正向存
        SocketContact add = BeanUtil.toBean(bo, SocketContact.class);
        add.setRoomId(0L);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }

//
//        // 反向存
//        add.setContactUserId(bo.getUserId());
//        add.setUserId(bo.getContactUserId());
//        validEntityBeforeSave(add);
//        flag = baseMapper.insert(add) > 0;
//        if (flag) {
//            bo.setId(add.getId());
//        }
        return flag;
    }


    /**
     * 新增通信群聊目录
     */
    @Override
    public Boolean insertByBoAndRoom(SocketContactBo bo) {
        Long roomId = System.currentTimeMillis();
        boolean flag = false;
        List<SysUser> userList = bo.getUserList();
        for (SysUser sysUser : userList) {
            SocketContact add = BeanUtil.toBean(bo, SocketContact.class);
            add.setUserId(sysUser.getUserId());
            for (SysUser user : userList) {
                // 当当前用户不等于接收者用户时候再进行set
                if (!user.getUserId().equals(sysUser.getUserId())) {
                    add.setContactUserId(user.getUserId());
                    add.setRoomId(roomId);
                    flag = baseMapper.insert(add) > 0;
                    if (flag) {
                        bo.setId(add.getId());
                    }
                }

            }
        }
        return flag;
    }

    /**
     * 修改通信目录
     */
    @Override
    public Boolean updateByBo(SocketContactBo bo) {
        SocketContact update = BeanUtil.toBean(bo, SocketContact.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SocketContact entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除通信目录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
