package org.dromara.im.service.impl;

import cn.hutool.core.util.ObjectUtil;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.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 lombok.RequiredArgsConstructor;
import org.dromara.im.domain.ImFriend;
import org.dromara.im.domain.bo.ImFriendBo;
import org.dromara.im.domain.vo.ImFriendVo;
import org.dromara.im.mapper.ImFriendMapper;
import org.dromara.im.service.IImFriendService;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 好友Service业务层处理
 *
 * @author Luo.J
 * @date 2025-05-15
 */
@RequiredArgsConstructor
@Service
public class ImFriendServiceImpl implements IImFriendService {

    private final ImFriendMapper baseMapper;

    private final SysUserMapper sysUserMapper;

    /**
     * 查询好友
     *
     * @param id 主键
     * @return 好友
     */
    @Override
    public ImFriendVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询好友列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 好友分页列表
     */
    @Override
    public TableDataInfo<ImFriendVo> queryPageList(ImFriendBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ImFriend> lqw = buildQueryWrapper(bo);
        Page<ImFriendVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的好友列表
     *
     * @param bo 查询条件
     * @return 好友列表
     */
    @Override
    public List<ImFriendVo> queryList(ImFriendBo bo) {
        LambdaQueryWrapper<ImFriend> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ImFriend> buildQueryWrapper(ImFriendBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ImFriend> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(ImFriend::getId);
        lqw.eq(bo.getUserId() != null, ImFriend::getUserId, bo.getUserId());
        lqw.eq(bo.getFriendId() != null, ImFriend::getFriendId, bo.getFriendId());
        lqw.like(StringUtils.isNotBlank(bo.getFriendNickName()), ImFriend::getFriendNickName, bo.getFriendNickName());
        lqw.eq(StringUtils.isNotBlank(bo.getFriendHeadImage()), ImFriend::getFriendHeadImage, bo.getFriendHeadImage());
        lqw.eq(bo.getCreatedTime() != null, ImFriend::getCreatedTime, bo.getCreatedTime());
        lqw.eq(StringUtils.isNotBlank(bo.getDeleted()), ImFriend::getDeleted, bo.getDeleted());
        return lqw;
    }

    /**
     * 新增好友
     *
     * @param bo 好友
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ImFriendBo bo) {
        ImFriend add = MapstructUtils.convert(bo, ImFriend.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改好友
     *
     * @param bo 好友
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ImFriendBo bo) {
        ImFriend update = MapstructUtils.convert(bo, ImFriend.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

    /**
     * 校验并批量删除好友信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public void initialize(Long userId) {
        if (ObjectUtil.isNotEmpty(userId)){
            baseMapper.deleteByUserId(userId);
            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser::getStatus,"0");
            queryWrapper.ne(SysUser::getUserId,userId);
            List<SysUser> friendList = sysUserMapper.selectList(queryWrapper);
            for (SysUser friend : friendList) {
                ImFriend imFriend = new ImFriend();
                imFriend.setUserId(userId);
                imFriend.setFriendId(friend.getUserId());
                imFriend.setFriendNickName(friend.getNickName());
                imFriend.setFriendHeadImage(friend.getAvatar());
                imFriend.setCreatedTime(new Date());
                baseMapper.insert(imFriend);
            }
        }else {
            baseMapper.truncateTable();
            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser::getStatus,"0");
            List<SysUser> userList = sysUserMapper.selectList(queryWrapper);
            for (SysUser user : userList) {
                LambdaQueryWrapper<SysUser> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(SysUser::getStatus,"0");
                queryWrapper1.ne(SysUser::getUserId,user.getUserId());
                List<SysUser> friendList = sysUserMapper.selectList(queryWrapper1);
                for (SysUser friend : friendList) {
                    ImFriend imFriend = new ImFriend();
                    imFriend.setUserId(user.getUserId());
                    imFriend.setFriendId(friend.getUserId());
                    imFriend.setFriendNickName(friend.getNickName());
                    imFriend.setFriendHeadImage(friend.getAvatar());
                    imFriend.setCreatedTime(new Date());
                    baseMapper.insert(imFriend);
                }
            }
        }
    }
}
