package com.ruoyi.cms.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.cms.domain.CommunityUser;
import com.ruoyi.cms.domain.WechatGroup;
import com.ruoyi.cms.mapper.CommunityUserMapper;
import com.ruoyi.cms.mapper.WechatGroupMapper;
import com.ruoyi.cms.service.ICommunityUserService;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

@Service
public class CommunityUserServiceImpl extends ServiceImpl<CommunityUserMapper, CommunityUser>
        implements ICommunityUserService {

    @Autowired
    private WechatGroupMapper wechatGroupMapper;

    @Override
    public List<CommunityUser> selectCommunityUserList(CommunityUser communityUser) {

        return baseMapper.selectList(Wrappers.lambdaQuery(CommunityUser.class)
                .like(StrUtil.isNotBlank(communityUser.getWechatName()), CommunityUser::getWechatName, communityUser.getWechatName())
                .like(StrUtil.isNotBlank(communityUser.getPhoneNumber()), CommunityUser::getPhoneNumber, communityUser.getPhoneNumber())
        );
    }

    @Override
    public int delCommunityUser(Long[] ids) {
        if (ids == null || ids.length == 0) return 0;
        Collection<Long> userIds = CollUtil.newArrayList(ids);
        Long count = wechatGroupMapper.selectCount(Wrappers.lambdaQuery(WechatGroup.class)
                .in(WechatGroup::getCommunityId, userIds));
        if (count > 0) {
            throw new ServiceException("所选工作人员已配置转发对象！");
        }
        return baseMapper.deleteBatchIds(userIds);
    }
}
