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.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.group.mapper.CustGroupMapper;
import com.ruoyi.group.mapper.CustGroupMemberMapper;
import com.ruoyi.group.service.ICustGroupService;
import com.ruoyi.group.service.ICustGroupMemberService;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

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

    @Resource
    private CustGroupMemberMapper custGroupMemberMapper;

    @Resource
    private CustGroupMapper custGroupMapper;

    @Resource
    private ICustGroupService custGroupService;

    @Override
    public List<CustGroupMemberVO> listCustGroupMembers(Long groupId, CustGroupMemberQueryDTO dto) {
        custGroupService.checkCustGroupViewPermission(groupId);
        dto.setUserRole(SecurityUtils.userRole());
        dto.setCurrentUserName(SecurityUtils.getUsername());
        dto.setCurrentDeptId(SecurityUtils.getDeptId());
        // 在权限检查之后启动分页，避免权限检查SQL消耗分页设置
        int pageNum = dto.getPageNum() != null ? dto.getPageNum() : 1;
        int pageSize = dto.getPageSize() != null ? dto.getPageSize() : 10;
        PageHelper.startPage(pageNum, pageSize);
        // 1. 查询客群成员列表（分页）
        List<CustGroupMemberVO> memberList = custGroupMemberMapper.selectCustGroupMemberList(groupId, dto);
        if (memberList == null || memberList.isEmpty()) {
            return memberList;
        }

        // 2. 按客户类型分组，批量查询存量状态
        // 个人客户
        List<String> retailCustIds = memberList.stream()
                .filter(m -> "0".equals(m.getCustType()))
                .map(CustGroupMemberVO::getCustId)
                .collect(Collectors.toList());
        // 商户客户
        List<String> merchantCustIds = memberList.stream()
                .filter(m -> "1".equals(m.getCustType()))
                .map(CustGroupMemberVO::getCustId)
                .collect(Collectors.toList());
        // 企业客户
        List<String> businessCustIds = memberList.stream()
                .filter(m -> "2".equals(m.getCustType()))
                .map(CustGroupMemberVO::getCustId)
                .collect(Collectors.toList());

        // 3. 批量查询各类型存量客户
        Set<String> existingRetailCustIds = new HashSet<>();
        Set<String> existingMerchantCustIds = new HashSet<>();
        Set<String> existingBusinessCustIds = new HashSet<>();

        if (!retailCustIds.isEmpty()) {
            existingRetailCustIds.addAll(custGroupMemberMapper.selectExistingRetailCustIds(retailCustIds));
        }
        if (!merchantCustIds.isEmpty()) {
            existingMerchantCustIds.addAll(custGroupMemberMapper.selectExistingMerchantCustIds(merchantCustIds));
        }
        if (!businessCustIds.isEmpty()) {
            existingBusinessCustIds.addAll(custGroupMemberMapper.selectExistingBusinessCustIds(businessCustIds));
        }

        // 4. 填充存量状态
        for (CustGroupMemberVO member : memberList) {
            String custType = member.getCustType();
            String custId = member.getCustId();
            if ("0".equals(custType)) {
                member.setIsExisting(existingRetailCustIds.contains(custId));
            } else if ("1".equals(custType)) {
                member.setIsExisting(existingMerchantCustIds.contains(custId));
            } else if ("2".equals(custType)) {
                member.setIsExisting(existingBusinessCustIds.contains(custId));
            } else {
                member.setIsExisting(false);
            }
        }

        return memberList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String removeMembers(Long groupId, List<Long> memberIds) {
        // 检查客群是否存在
        CustGroup custGroup = custGroupMapper.selectById(groupId);
        if (custGroup == null) {
            throw new ServiceException("客群不存在");
        }
        if (!SecurityUtils.hasRole("headAdmin")
                && !SecurityUtils.hasRole("headPublic")
                && !SecurityUtils.hasRole("headPrivate")
                && !SecurityUtils.hasRole("headOps")) {
            throw new ServiceException("无权限操作该客群");
        }
        Long count = custGroupMapper.countHeadOperableCustGroup(groupId, SecurityUtils.getHeadId());
        if (count == null || count <= 0) {
            throw new ServiceException("无权限操作该客群");
        }

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

        return "移除成功";
    }
}
