package cn.iocoder.yudao.module.crm.service.userlivetree;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.crm.controller.admin.userlivetree.vo.UserLiveTreeListVO;
import cn.iocoder.yudao.module.crm.controller.admin.userlivetree.vo.UserLiveTreePageReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.userlivetree.vo.UserLiveTreeSaveReqVO;
import cn.iocoder.yudao.module.crm.dal.dataobject.userlivetree.UserLiveTreeDO;
import cn.iocoder.yudao.module.crm.dal.mysql.userlivetree.UserLiveTreeMapper;
import cn.iocoder.yudao.module.crm.service.salesperformancesettlement.SalesPerformanceSettlementService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

/**
 * crm用户结构树 Service 实现类
 *
 * @author 艾楷
 */
@Service
@Validated
public class UserLiveTreeServiceImpl implements UserLiveTreeService {

    @Resource
    private UserLiveTreeMapper userLiveTreeMapper;

    @Resource
    private AdminUserApi userApi;
    @Resource
    @Lazy
    private SalesPerformanceSettlementService salesPerformanceSettlementService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createUserLiveTree(UserLiveTreeSaveReqVO createReqVO) {
        // 插入
        UserLiveTreeDO userLiveTree = BeanUtils.toBean(createReqVO, UserLiveTreeDO.class);
        userLiveTreeMapper.insert(userLiveTree);
        salesPerformanceSettlementService.createSalesPerformanceSettlement(LocalDateTime.now(), userLiveTree.getUserId());
        // 返回
        return userLiveTree.getId();
    }

    @Override
    public void updateUserLiveTree(UserLiveTreeSaveReqVO updateReqVO) {
        // 更新
        UserLiveTreeDO updateObj = BeanUtils.toBean(updateReqVO, UserLiveTreeDO.class);
        userLiveTreeMapper.updateById(updateObj);
    }

    @Override
    public void deleteUserLiveTree(Long id) {
        // 删除
        userLiveTreeMapper.deleteById(id);
    }

    @Override
    public UserLiveTreeDO getUserLiveTree(Long id) {
        return userLiveTreeMapper.selectById(id);
    }

    @Override
    public PageResult<UserLiveTreeListVO> getUserLiveTreePage(UserLiveTreePageReqVO pageReqVO) {

        PageResult<UserLiveTreeListVO> pageResult = BeanUtils.toBean(userLiveTreeMapper.selectPage(pageReqVO), UserLiveTreeListVO.class);
        if (CollUtil.isNotEmpty(pageResult.getList())) {
            // 获取用户编号
            Set<Long> userIds = convertSet(pageResult.getList(), UserLiveTreeListVO::getUserId);
            // 获取用户信息
            Map<Long, AdminUserRespDTO> userMap = userApi.getUserMap(userIds);

            pageResult.getList().forEach(item -> {
                item.setNickname(userMap.get(item.getUserId()) != null ? userMap.get(item.getUserId()).getNickname() : null);
            });
        }
        return pageResult;
    }

    @Override
    public List<UserLiveTreeListVO> userLiveTreeList() {
        List<UserLiveTreeListVO> userLiveTreeDOS = this.getUserLiveTreeList();
        return userLiveTreeDOS.stream()
                .filter(vo -> vo.getPid() == 0)
                .collect(Collectors.toList());
    }

    @Override
    public List<Long> getItemIdsByUserId(Long userId) {
        List<UserLiveTreeListVO> userLiveTreeListVOS = this.getUserLiveTreeList();
        Map<Long, List<UserLiveTreeListVO>> map = userLiveTreeListVOS.stream().collect(Collectors.groupingBy(UserLiveTreeListVO::getUserId));
        List<UserLiveTreeListVO> list = map.get(userId);
        List<Long> ids = new ArrayList<>();
        this.recursionGetId(list, ids);
        ids.remove(userId);
        return ids;
    }

    private void recursionGetId(List<UserLiveTreeListVO> list, List<Long> ids) {
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        List<UserLiveTreeListVO> nextList = new ArrayList<>();
        for (UserLiveTreeListVO userLiveTreeListVO : list) {
            ids.add(userLiveTreeListVO.getUserId());
            if (CollectionUtil.isNotEmpty(userLiveTreeListVO.getItems())) {
                nextList.addAll(userLiveTreeListVO.getItems());
            }
        }
        recursionGetId(nextList, ids);
    }

    @Override
    public List<UserLiveTreeListVO> getUserLiveList() {
        // -- 这里将所有的数据拉出来 -
        return userLiveTreeMapper.userLiveTreeList();
    }
    @Override
    public List<UserLiveTreeDO> getItemByPid(Long pid) {
        return userLiveTreeMapper.selectList(new LambdaQueryWrapper<UserLiveTreeDO>()
                .eq(UserLiveTreeDO::getPid, pid));
    }

    public List<UserLiveTreeListVO> getUserLiveTreeList() {
        // -- 这里将所有的数据拉出来 -
        List<UserLiveTreeListVO> userLiveTreeDOS = userLiveTreeMapper.userLiveTreeList();
        // 1. 按父ID分组，获取每个父节点下的子节点列表
        Map<Long, List<UserLiveTreeListVO>> pidGroupMap = userLiveTreeDOS.stream()
                .collect(Collectors.groupingBy(UserLiveTreeListVO::getPid));

        // 2. 遍历所有节点，设置它们的子节点列表
        for (UserLiveTreeListVO vo : userLiveTreeDOS) {
            vo.setItems(pidGroupMap.getOrDefault(vo.getUserId(), Collections.emptyList()));

        }
        return userLiveTreeDOS;
    }
}
