package com.ruoyi.group.service.impl;

import com.ruoyi.group.domain.dto.CustGroupMemberQueryDTO;
import com.ruoyi.group.domain.entity.CustGroup;
import com.ruoyi.group.domain.entity.CustGroupMember;
import com.ruoyi.group.domain.vo.CustGroupMemberVO;
import com.ruoyi.group.mapper.CustGroupMapper;
import com.ruoyi.group.mapper.CustGroupMemberMapper;
import com.ruoyi.group.service.ICustGroupMemberService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 客群客户服务实现类
 *
 * @author ruoyi
 */
@Service
public class CustGroupMemberServiceImpl implements ICustGroupMemberService {

    @Resource
    private CustGroupMemberMapper custGroupMemberMapper;

    @Resource
    private CustGroupMapper custGroupMapper;

    @Override
    public List<CustGroupMemberVO> listCustGroupMembers(Long groupId, CustGroupMemberQueryDTO dto) {
        return custGroupMemberMapper.selectCustGroupMemberList(groupId, dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String removeMembers(Long groupId, List<Long> memberIds) {
        // 检查客群是否存在
        CustGroup custGroup = custGroupMapper.selectById(groupId);
        if (custGroup == null) {
            return "客群不存在";
        }

        // 删除客户关联
        memberIds.forEach(memberId -> {
            CustGroupMember member = custGroupMemberMapper.selectById(memberId);
            if (member != null && member.getGroupId().equals(groupId)) {
                // 设置手动移除标识
                member.setManualRemove(1);
                // 逻辑删除
                custGroupMemberMapper.deleteById(memberId);
            }
        });

        return "移除成功";
    }
}
