package com.kcim.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kcim.common.exception.CostException;
import com.kcim.common.util.BeanUtil;
import com.kcim.common.util.UserContext;
import com.kcim.common.constants.NumberConstant;
import com.kcim.common.enums.ErrorCodeEnum;
import com.kcim.dao.mapper.ResponsibilityDepartmentMapper;
import com.kcim.dao.mapper.ResponsibilityMapper;
import com.kcim.dao.model.Responsibility;
import com.kcim.dao.model.ResponsibilityDepartment;
import com.kcim.dao.model.dto.ResponsibilityEditDTO;
import com.kcim.dao.model.dto.ResponsibilitySaveDTO;
import com.kcim.dao.model.dto.SysDepartment;
import com.kcim.dao.repository.ResponsibilityDepartmentRepository;
import com.kcim.service.CenterService;
import com.kcim.service.ResponsibilityService;
import com.kcim.common.constants.Constant;
import com.kcim.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service("responsibilityService")
public class ResponsibilityServiceImpl extends ServiceImpl<ResponsibilityMapper, Responsibility> implements ResponsibilityService {


    private final CostShareLevelServiceImpl costShareLevelService;
    private final ResponsibilityDepartmentMapper responsibilityDepartMapper;
    private final CenterService centerService;

    private final ResponsibilityDepartmentRepository responsibilityDepartmentRepository;
    public ResponsibilityServiceImpl(CostShareLevelServiceImpl costShareLevelService, ResponsibilityDepartmentMapper responsibilityDepartMapper, CenterService centerService, ResponsibilityDepartmentRepository responsibilityDepartmentRepository) {
        this.costShareLevelService = costShareLevelService;
        this.responsibilityDepartMapper = responsibilityDepartMapper;
        this.centerService = centerService;
        this.responsibilityDepartmentRepository = responsibilityDepartmentRepository;
    }

    /**
     * 责任中心列表不分页
     * @return
     */
    @Override
    public List<CostResponsibilityVO> getList() {
        // 1. 获取所有的列表然后组装
        List<CostResponsibilityVO> costResponsibilityVOS = this.getCostResponsibilityVO();
        // 拷贝组合

        List<DictDataVo> responsibilityType = getResponsibilityType();
        Map<String,String> dictMap = responsibilityType.stream().collect(Collectors.toMap(DictDataVo::getCode, DictDataVo::getName, (a, b) -> b));

        List<DictDataVo> standardShareLevel = getStandardShareLevel();

        Map<String,String> standardDictMap = standardShareLevel.stream().collect(Collectors.toMap(DictDataVo::getCode, DictDataVo::getName, (a, b) -> b));
        for (CostResponsibilityVO responsibility : costResponsibilityVOS) {
            if(!StringUtils.isEmpty(responsibility.getType())){
                responsibility.setTypeName(dictMap.get(responsibility.getType()));
            }
            if(!StringUtils.isEmpty(responsibility.getStandardShareLevel())){
                responsibility.setStandardShareLevelName(standardDictMap.get(responsibility.getStandardShareLevel()));
            }
        }

        List<CostResponsibilityVO> collect = costResponsibilityVOS.stream().filter(i -> i.getParentId() == 0)
                .peek(i -> i.setChild(this.getResponsibilityChildren(i, costResponsibilityVOS)))
                .collect(Collectors.toList());
        responsibilitySort(collect);
        return collect;
//        List<CostResponsibilityVO> parentCostResponsibility = costResponsibilityVOS.stream()
//                .filter(i -> i.getParentId() == 0).collect(Collectors.toList());
//        // 多层结构
//        List<CostResponsibilityVO> all = new ArrayList<>();
//        // todo 试试多线程实现方式
//        for (CostResponsibilityVO parent : parentCostResponsibility) {
//            List<CostResponsibilityVO> children = this.getResponsibilityChildren(parent, costResponsibilityVOS);
//            all.addAll(children);
//        }
//        return all;
    }

    @Override
    public List<CostResponsibilityVO> getSharelevelRespList(Integer shareId, String filter) {
        // 1. 获取指定层级和过滤条件的责任中心
        List<CostResponsibilityVO> shareLevelResponsibilityVOS = this.getShareLevelResponsibilityVO(shareId, filter);
        if (CollectionUtils.isEmpty(shareLevelResponsibilityVOS)) {
            return new ArrayList<>();
        }

        // 2. 获取所有的责任中心用于构建完整树结构
        List<CostResponsibilityVO> allResponsibilityVOS = this.getCostResponsibilityVO();

        // 3. 构建ID映射，用于快速查找
        Map<Long, CostResponsibilityVO> idMap = allResponsibilityVOS.stream()
                .collect(Collectors.toMap(CostResponsibilityVO::getId, i -> i, (existing, replacement) -> existing));

        // 4. 收集需要返回的所有责任中心ID（包括父级）
        Set<Long> needReturnIds = new HashSet<>();

        // 将满足条件的责任中心及其所有父级加入集合
        for (CostResponsibilityVO vo : shareLevelResponsibilityVOS) {
            // 添加自身
            needReturnIds.add(vo.getId());
            // 添加所有父级
            Long parentId = vo.getParentId();
            while (parentId != null && parentId != 0) {
                needReturnIds.add(parentId);
                CostResponsibilityVO parent = idMap.get(parentId);
                if (parent != null) {
                    parentId = parent.getParentId();
                } else {
                    break;
                }
            }
        }

        // 5. 筛选出需要返回的责任中心
        List<CostResponsibilityVO> needReturnList = allResponsibilityVOS.stream()
                .filter(vo -> needReturnIds.contains(vo.getId()))
                .collect(Collectors.toList());

        // 6. 添加字典数据
        List<DictDataVo> responsibilityType = getResponsibilityType();
        Map<String, String> dictMap = responsibilityType.stream()
                .collect(Collectors.toMap(DictDataVo::getCode, DictDataVo::getName, (a, b) -> b));

        List<DictDataVo> standardShareLevel = getStandardShareLevel();
        Map<String, String> standardDictMap = standardShareLevel.stream()
                .collect(Collectors.toMap(DictDataVo::getCode, DictDataVo::getName, (a, b) -> b));

        for (CostResponsibilityVO responsibility : needReturnList) {
            if (!StringUtils.isEmpty(responsibility.getType())) {
                responsibility.setTypeName(dictMap.get(responsibility.getType()));
            }
            if (!StringUtils.isEmpty(responsibility.getStandardShareLevel())) {
                responsibility.setStandardShareLevelName(standardDictMap.get(responsibility.getStandardShareLevel()));
            }
        }

        // 7. 构建多层级树结构
        List<CostResponsibilityVO> result = needReturnList.stream()
                .filter(i -> i.getParentId() == 0)  // 只取顶级节点
                .peek(i -> i.setChild(this.getResponsibilityChildren(i, needReturnList)))
                .collect(Collectors.toList());

        // 8. 排序
        responsibilitySort(result);
        return result;
    }

    private void responsibilitySort(List<CostResponsibilityVO> responsibilityList){
        for (CostResponsibilityVO responsibility :responsibilityList){
            if(!CollectionUtils.isEmpty(responsibility.getChild())){
                responsibilitySort(responsibility.getChild());
            }
        }
        responsibilityList.sort(Comparator.comparing(CostResponsibilityVO::getSort,Comparator.nullsLast(Integer::compareTo)));
    }
    private List<CostResponsibilityVO> getCostResponsibilityVO() {
        List<Responsibility> list = this.list(
                new LambdaQueryWrapper<Responsibility>()
                        .eq(Responsibility::getHospId, UserContext.getHospId())
                        .orderByDesc(Responsibility::getCreateTime)
        );
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }


        return BeanUtil.convertList(list, CostResponsibilityVO.class);
    }

    private List<CostResponsibilityVO> getShareLevelResponsibilityVO(Integer shareId, String filter ) {
        LambdaQueryWrapper<Responsibility> queryWrapper = new LambdaQueryWrapper<Responsibility>()
                .eq(Responsibility::getHospId, UserContext.getHospId())
                .orderByDesc(Responsibility::getCreateTime);
        if(shareId != null){
            queryWrapper.eq(Responsibility::getShareId,shareId);
        }
        if(!StringUtils.isEmpty(filter)){
            queryWrapper.like(Responsibility::getResponsibilityName,filter);
        }
        List<Responsibility> list = this.list(queryWrapper);
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        return BeanUtil.convertList(list, CostResponsibilityVO.class);
    }

    /**
     * 获取子层级
     *
     * @param parent                当前的
     * @param costResponsibilityVOS 所有的
     * @return
     */
    private List<CostResponsibilityVO> getResponsibilityChildren(CostResponsibilityVO parent, List<CostResponsibilityVO> costResponsibilityVOS) {
        return costResponsibilityVOS.stream().filter(o -> o.getParentId().equals(parent.getId()))
                .peek(o -> o.setChild(this.getResponsibilityChildren(o, costResponsibilityVOS)))
                .collect(Collectors.toList());
//        List<CostResponsibilityVO> list = new LinkedList<>();
//        list.add(parent);
//        for (CostResponsibilityVO costResponsibilityVO : costResponsibilityVOS) {
//            if (parent.getId().equals(costResponsibilityVO.getParentId())) {
//                List<CostResponsibilityVO> child = parent.getChild();
//                if (CollUtil.isEmpty(child)) {
//                    child = new ArrayList<>();
//                }
//                child.add(costResponsibilityVO);
//                parent.setChild(child);
//                this.getResponsibilityChildren(costResponsibilityVO, costResponsibilityVOS);
//            }
//        }
//        return list;
    }


    /**
     * 新增责任中心
     *
     * @param responsibilitySaveDTO {@link ResponsibilitySaveDTO }
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void addResponsibilityCenter(ResponsibilitySaveDTO responsibilitySaveDTO) {
        // 如果是一级分类parentId为0
        Long id = responsibilitySaveDTO.getId();
        if (Objects.isNull(id)) {
            id = 0L;
        }
        // 校验责任中心代码code是否唯一
        checkCode(responsibilitySaveDTO.getResponsibilityCode(), UserContext.getHospId());

        Responsibility center = BeanUtil.convertObj(responsibilitySaveDTO, Responsibility.class);
        center.setCreateTime(System.currentTimeMillis()).setId(null).setParentId(id).setHospId(UserContext.getHospId());

        // 如果是汇总中心，那么不存在分摊级别
        Integer isGatherCenter = responsibilitySaveDTO.getIsGatherCenter();
        if (isGatherCenter == 1) {
            center.setShareLevel(0);
            center.setShareName("");
            center.setResponsibilityType(NumberConstant.ONE);
        }

        // 只允许存在一个默认中心
        if (responsibilitySaveDTO.getIsDefault() == 1) {
            this.checkIsDefault(UserContext.getHospId());
        }
        this.save(center);
    }

    private void checkIsDefault(Long hospId) {
        Responsibility one = this.getOne(
                new LambdaQueryWrapper<Responsibility>()
                        .eq(Responsibility::getHospId, hospId)
                        .eq(Responsibility::getIsDefault, 1)
                        .last(Constant.LIMIT)
        );
        if (Objects.nonNull(one)) {
            throw new CostException("责任中心只能拥有一个默认责任中心");
        }
    }

    private void checkCode(String code, Long hospId) {
        // 校验责任代码唯一性
        Responsibility one = this.getOne(
                new LambdaQueryWrapper<Responsibility>().select(Responsibility::getId)
                        .eq(Responsibility::getResponsibilityCode, code)
                        .eq(Responsibility::getHospId, hospId).last("limit 1")
        );
        if (Objects.nonNull(one)) {
            throw new CostException(ErrorCodeEnum.RESPONSIBILITY_CODE_EXIST);
        }
    }


    /**
     * 编辑责任中心
     *
     * @param responsibilityEditDTO {@link ResponsibilityEditDTO}
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void editResponsibility(ResponsibilityEditDTO responsibilityEditDTO) {
        Long id = responsibilityEditDTO.getId();
        Responsibility center = this.getById(id);
        if (Objects.isNull(center)) {
            throw new CostException(ErrorCodeEnum.DATA_NOT_EXIST);
        }

        Responsibility one = this.getOne(
                new LambdaQueryWrapper<Responsibility>().select(Responsibility::getId)
                        .eq(Responsibility::getResponsibilityCode, responsibilityEditDTO.getResponsibilityCode())
                        .eq(Responsibility::getHospId, UserContext.getHospId()).last("limit 1")
        );
        if (Objects.nonNull(one)&& !one.getId().equals(center.getId())) {
            throw new CostException(ErrorCodeEnum.RESPONSIBILITY_CODE_EXIST);
        }
        BeanUtil.convertObj(responsibilityEditDTO,center);
        this.updateById(center);



//        // 判断是否有子节点
//        List<Responsibility> list = this.list(
//                new LambdaQueryWrapper<Responsibility>()
//                        .eq(Responsibility::getHospId, UserContext.getHospId())
//                        .eq(Responsibility::getParentId, id)
//        );
//        // 如果不存在子节点 ，修改它本身
//        if (list.isEmpty()) {
//            this.updateCurResp(center, responsibilityEditDTO);
//            return;
//        }
//
//        this.updateParent(responsibilityEditDTO, center, UserContext.getHospId());
    }


    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void updateCurResp(Responsibility center, ResponsibilityEditDTO dto) {
        // 删除
        Long id = dto.getId();
        this.removeById(id);
        // 校验code
        this.checkCode(dto.getResponsibilityCode(), UserContext.getHospId());

        Responsibility newResponsibility = BeanUtil.convertObj(dto, Responsibility.class);
        newResponsibility.setId(null)
                .setHospId(UserContext.getHospId())
                .setCreateTime(System.currentTimeMillis())
                .setParentId(dto.getParentId());
        // 如果变成了汇总中心 不存在分摊层级名称等
        if (dto.getIsGatherCenter() == 1) {
            newResponsibility.setShareId(null)
                    .setShareLevel(0)
                    .setShareName(null);
        }
        if (dto.getParentId() == 0) {
            // 永远为2的情况
            newResponsibility.setIsGatherCenter(2);
        }
        // 校验默认
        if (dto.getIsDefault() == 1) {
            this.checkIsDefault(UserContext.getHospId());
        }

        this.save(newResponsibility);
    }

    /**
     * 修的是父节点
     *
     * @param dto
     * @param responsibility
     * @param hospId
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateParent(ResponsibilityEditDTO dto, Responsibility responsibility, Long hospId) {

        // 删除原有的父节点数据
        Long id = dto.getId();
        this.removeById(id);
        List<Responsibility> child = this.list(new QueryWrapper<Responsibility>().lambda().eq(Responsibility::getParentId, id));
        // 如果修改是否汇总中心 从是 -> 否那么子节点直接删除
        if (responsibility.getIsGatherCenter() == 1 && dto.getIsGatherCenter() == 2) {
            this.removeByIds(child.stream().map(Responsibility::getId).collect(Collectors.toList()));
//            return;
        }

        this.checkCode(dto.getResponsibilityCode(), hospId);
        // 新增父节点数据
        Responsibility newResponsibility = BeanUtil.convertObj(dto, Responsibility.class);
        newResponsibility.setId(null).setHospId(responsibility.getHospId()).setCreateTime(System.currentTimeMillis());

        // 如果是汇总中心，那么不存在分摊级别
        Integer isGatherCenter = newResponsibility.getIsGatherCenter();
        if (isGatherCenter == 1) {
            newResponsibility.setShareId(null);
            newResponsibility.setShareLevel(0);
            newResponsibility.setShareName("");
        }
        // 父节点不允许为非汇总中心
        Responsibility byId = this.getById(id);
        if (Objects.nonNull(byId) && (byId.getIsGatherCenter() == 2)) {
            throw new CostException(500, "非汇总中心不允许添加");
        }
        if (dto.getIsDefault() == 1) {
            this.checkIsDefault(hospId);
        }

        this.save(newResponsibility);

        // 将原来所有父节点下数据关联到新的父节点下
        child.forEach(i -> {
            i.setParentId(newResponsibility.getId());
            i.setIsGatherCenter(2);
        });
        this.updateBatchById(child);

    }

    /**
     * 修改当前的节点
     *
     * @param dto
     * @param responsibility
     * @param hospId
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateCurrent(ResponsibilityEditDTO dto, Responsibility responsibility, Long hospId) {
        // 删除原有的父节点数据
        Long id = dto.getId();
        this.removeById(id);

        this.checkCode(dto.getResponsibilityCode(), hospId);

        Responsibility newResponsibility = BeanUtil.convertObj(dto, Responsibility.class);
        newResponsibility.setId(null)
                .setHospId(responsibility.getHospId())
                .setCreateTime(System.currentTimeMillis())
                .setParentId(dto.getParentId());
        // 暂时先这样处理
        if (dto.getIsGatherCenter() == 1) {
            newResponsibility.setShareId(null)
                    .setShareLevel(0)
                    .setShareName(null)
                    .setParentId(0L);
        }
        this.save(newResponsibility);
    }


    /**
     * 删除责任中心
     *
     * @param id
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteCenter(Integer id) {
        Responsibility center = this.getById(id);
        if (Objects.isNull(center)) {
            throw new CostException(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        Long parentId = center.getParentId();
        if (parentId == 0) {
            this.deleteAllSonCenter(id);
            return;
        }
        this.removeById(id);
    }

    /**
     * 删除父节点以及所有子节点责任中心
     *
     * @param id
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteAllSonCenter(Integer id) {
        this.removeById(id);
        this.remove(new LambdaQueryWrapper<Responsibility>().eq(Responsibility::getParentId, id));
    }

    /**
     * 获取部门树列表
     *
     * @return
     */
    @Override
    public List<CenterDepartmentVO> getParentSon() {
        List<CostResponsibilityVO> costResponsibilityVOS = this.getCostResponsibilityVO();
        List<CenterDepartmentVO> centerDepartmentVOS = costResponsibilityVOS.stream().map(i -> {
            CenterDepartmentVO vo = BeanUtil.convertObj(i, CenterDepartmentVO.class);
            vo.setResponsibilityId(i.getId());
            vo.setResponsibilityCode(i.getResponsibilityCode());
            return vo;
        }).collect(Collectors.toList());

        List<SysDepartment> departmentFilter = centerService.getDepartmentFilter(null);
        Map<Long,String> departmentMap = departmentFilter.stream().collect(Collectors.toMap(sysDepartment -> Long.valueOf(sysDepartment.getId()), SysDepartment::getName, (a, b) -> b));
        Map<Long,String> departmentCodeMap = departmentFilter.stream().collect(Collectors.toMap(sysDepartment -> Long.valueOf(sysDepartment.getId()), SysDepartment::getCode, (a, b) -> b));

        List<ResponsibilityDepartment> responsibilityDepartment = responsibilityDepartmentRepository.getResponsibilityDepartment();
        if(!CollectionUtils.isEmpty(responsibilityDepartment)){
            Map<Long, List<ResponsibilityDepartment>> collect = responsibilityDepartment.stream().collect(Collectors.groupingBy(ResponsibilityDepartment::getResponsibilityId));
            //组装科室
            Map<Long,List<DepartVO> > responsibilityDepartmentMap = new HashMap<>();
            collect.forEach((k,v)->{
                List<DepartVO> departVOS = new ArrayList<>();
                for (ResponsibilityDepartment department : v) {
                    DepartVO vo = new DepartVO();
                    String departName = departmentMap.get(department.getDepartmentId());
                    if(!StringUtils.isEmpty(departName)){
                        vo.setDepartmentId(department.getDepartmentId());
                        vo.setDepartmentName(departName +departmentCodeMap.get(department.getDepartmentId()));
                        vo.setDepartmentCode(department.getDepartmentCode());
                    }
                    departVOS.add(vo);
                }
                responsibilityDepartmentMap.put(k,departVOS);
            });
//            for (Long aLong : collect.keySet()) {
//                List<ResponsibilityDepartment> responsibilityDepartments = collect.get(aLong);
//                List<DepartVO> departVOS = new ArrayList<>();
//                for (ResponsibilityDepartment department : responsibilityDepartments) {
//                    DepartVO vo = new DepartVO();
//                    String departName = departmentMap.get(department.getDepartmentId());
//                    if(!StringUtils.isEmpty(departName)){
//                        vo.setDepartmentId(department.getDepartmentId());
//                        vo.setDepartmentName(departName +departmentCodeMap.get(department.getDepartmentId()));
//                    }
//                    departVOS.add(vo);
//                }
//                responsibilityDepartmentMap.put(aLong,departVOS);
//            }

            centerDepartmentVOS.forEach(centerDepartmentVO -> centerDepartmentVO.setDepartments(responsibilityDepartmentMap.get(centerDepartmentVO.getResponsibilityId())));

        }
        //
        Map<Long, List<CenterDepartmentVO>> collectParentGroup = centerDepartmentVOS.stream().collect(Collectors.groupingBy(CenterDepartmentVO::getParentId));
        //获取父类
        List<CenterDepartmentVO> voList = collectParentGroup.get(NumberConstant.ZERO_L);

        for (CenterDepartmentVO centerDepartmentVO : voList) {
            List<CenterDepartmentVO> departmentVOS = collectParentGroup.get(centerDepartmentVO.getId());
            if(!CollectionUtils.isEmpty(departmentVOS)){
                for (CenterDepartmentVO departmentVO : departmentVOS) {
                    handleTree(departmentVO,collectParentGroup);
                }
            }

            centerDepartmentVO.setIsParent(true);
            centerDepartmentVO.setChild(departmentVOS);
        }

        return voList;//        return centerDepartmentVOS.stream().filter(i -> i.getParentId() == 0)
//                .peek(i -> {
//                    List<CenterDepartmentVO> responsibilityChildrenForRelation = this.getResponsibilityChildrenForRelation(i, centerDepartmentVOS);
//                    if (CollUtil.isEmpty(responsibilityChildrenForRelation)) {
//                        i.setDepartments(responsibilityDepartMapper.getDepartByCenterId(i.getResponsibilityId()));
//                        i.setIsParent(false);
//                        i.setDepartments(responsibilityDepartMapper.getDepartByCenterId(i.getResponsibilityId()));
//                    }
//                    i.setChild(responsibilityChildrenForRelation);
//                    i.setIsParent(true);
//                })
//                .collect(Collectors.toList());

    }
    private void handleTree(CenterDepartmentVO vo,Map<Long, List<CenterDepartmentVO>> collectParentGroup){
        List<CenterDepartmentVO> departmentVOS = collectParentGroup.get(vo.getId());
        if(!CollectionUtils.isEmpty(departmentVOS)){
            for (CenterDepartmentVO departmentVO : departmentVOS) {
                handleTree(departmentVO,collectParentGroup);
            }
            vo.setIsParent(false);
            vo.setChild(departmentVOS);
        }



    }

    private List<CenterDepartmentVO> getResponsibilityChildrenForRelation(CenterDepartmentVO
                                                                                  parent, List<CenterDepartmentVO> costResponsibilityVOS) {
        return costResponsibilityVOS.stream().filter(o -> o.getParentId().equals(parent.getId()))
                .peek(o -> {
                    o.setIsParent(true);
                    List<CenterDepartmentVO> responsibilityChildrenForRelation = this.getResponsibilityChildrenForRelation(o, costResponsibilityVOS);
                    if (CollUtil.isEmpty(responsibilityChildrenForRelation)) {
                        o.setIsParent(false);
                        o.setDepartments(responsibilityDepartMapper.getDepartByCenterId(o.getResponsibilityId()));
                    }
                    o.setChild(responsibilityChildrenForRelation);

                })
                .collect(Collectors.toList());

    }


    @Override
    public List<CommonVO> getParentList() {
        List<Responsibility> list = this.list(
                new LambdaQueryWrapper<Responsibility>().select(Responsibility::getId, Responsibility::getResponsibilityName)
                        .eq(Responsibility::getParentId, 0)
                        .eq(Responsibility::getHospId, UserContext.getHospId())
        );
        return list.stream().map(i -> {
            CommonVO commonVO = new CommonVO();
            commonVO.setId(i.getId());
            commonVO.setName(i.getResponsibilityName());
            return commonVO;
        }).collect(Collectors.toList());
    }

    /**
     * 获取可不是汇总中心列表
     *
     * @param hospId
     * @return
     */
    @Override
    public List<CostResponsibilityLevelVO> getLevelTwo(Long hospId) {
        List<Responsibility> responsibilities = baseMapper.selectList(new QueryWrapper<Responsibility>().lambda()
                .eq(Responsibility::getHospId, hospId)
                .eq(Responsibility::getIsGatherCenter, NumberConstant.TWO)
                .ne(Responsibility::getShareId, NumberConstant.ZERO));
        List<CostResponsibilityLevelVO> costResponsibilityLevelVOS = BeanUtil.convertList(responsibilities, CostResponsibilityLevelVO.class);
        List<CostShareLevelVO> costShareLevelServiceAll = costShareLevelService.getAll(hospId);
        Map<Long, List<CostShareLevelVO>> listMap = costShareLevelServiceAll.stream().collect(Collectors.groupingBy(CostShareLevelVO::getId));
        // 设置责任中心的计算方式
        costResponsibilityLevelVOS.forEach(i -> {
            i.setResponsibilityId(i.getId());
            Long shareId = i.getShareId();
            List<CostShareLevelVO> costShareLevelVOList = listMap.get(shareId);
            if (!CollectionUtils.isEmpty(costShareLevelVOList)) {
                i.setCalcType(costShareLevelVOList.get(0).getCalcType());
            }
        });
        return costResponsibilityLevelVOS;
    }

    /**
     * 责任中心在收入归集设置里面显示的列表
     *
     * @return
     */
    @Override
    public List<CostResponsibilityVO> responsibilityList() {
        // 1. 获取所有的列表然后组装
        List<CostResponsibilityVO> costResponsibilityVOS = this.getCostResponsibilityVO();
        List<CostResponsibilityVO> parentCostResponsibility = costResponsibilityVOS.stream()
                .filter(i -> i.getResponsibilityLevel().equals(1)).collect(Collectors.toList());

        parentCostResponsibility.forEach(i -> costResponsibilityVOS.forEach(j -> {
            if (j.getParentId().equals(i.getId())) {
                if (i.getResponsibilityLevel() == 1) {
                    i.setShareLevel(null);
                }
                List<CostResponsibilityVO> child = i.getChild();
                if (CollUtil.isEmpty(child)) {
                    child = new ArrayList<>();
                }
                j.setResponsibilityName(i.getResponsibilityName() + "/" + j.getResponsibilityName());
                child.add(j);
                i.setChild(child);
            }
        }));
        return parentCostResponsibility;
    }


    /**
     * 通过分摊级别id得到所有的责任中心
     *
     * @param levelId 分摊级别id
     * @param hospId  医院id
     * @return 责任中心
     */
    @Override
    public List<Responsibility> getByLevelIds(List<Long> levelId, Long hospId) {
        List<Responsibility> list = this.list(
                new LambdaQueryWrapper<Responsibility>()
                        .in(Responsibility::getShareId, levelId)
                        .eq(Responsibility::getHospId, hospId)
        );
        if (list.isEmpty()) {
            throw new CostException("责任中心未分配正确的分摊层级");
        }
        return list;
    }

    /**
     * 通过分摊层级列表得到对应的责任中心
     *
     * @param levelId 分摊层级id
     * @param hospId  医院id
     * @return 责任中心 可能存在null
     */
    @Override
    public List<Responsibility> getLevelIdByCode(Long levelId, Long hospId) {
        return this.list(
                new LambdaQueryWrapper<Responsibility>()
                        .in(Responsibility::getShareId, levelId)
                        .eq(Responsibility::getHospId, hospId)
        );
    }

    /**
     * 通过code得到名字
     *
     * @param valueResponsibilityCode
     * @param hospId
     * @return
     */
    @Override
    public String getByCode(String valueResponsibilityCode, Long hospId) {
        Responsibility one = this.getOne(
                new LambdaQueryWrapper<Responsibility>()
                        .eq(Responsibility::getResponsibilityCode, valueResponsibilityCode)
                        .eq(Responsibility::getHospId, hospId)
                        .last(Constant.LIMIT)
        );
        if (Objects.isNull(one)) {
            throw new CostException("数据异常");
        }
        return one.getResponsibilityName();

    }

    @Override
    public Long getLevelIdByCode(String responsibilityCode, Long hospId) {
        Responsibility one = this.getOne(
                new LambdaQueryWrapper<Responsibility>()
                        .eq(Responsibility::getResponsibilityCode, responsibilityCode)
                        .eq(Responsibility::getHospId, hospId)
                        .last(Constant.LIMIT)
        );
        if (Objects.isNull(one)) {
            throw new CostException("数据异常");
        }
        return one.getShareId();
    }

    /**
     * 获取某个医院所有叶子节点的收益中心的责任中心
     *
     * @param hospId 医院id
     * @return List
     */
    @Override
    public List<Responsibility> getLeafResp(Long hospId) {
        List<Responsibility> list = this.list(
                new LambdaQueryWrapper<Responsibility>()
                        .eq(Responsibility::getHospId, hospId)
                        .eq(Responsibility::getIsGatherCenter, 2)
                        .eq(Responsibility::getResponsibilityType, 1)
        );
        return list;
    }

    @Override
    public List<CostResponsibilityVO> getList(String filter) {
        List<CostResponsibilityVO> costResponsibilityVOS = new ArrayList<>();
            if(!StringUtils.isEmpty(filter)){
                costResponsibilityVOS = this.getCostResponsibilityVO(filter);
            }else {
                costResponsibilityVOS = this.getCostResponsibilityVO();

            }


        List<CostResponsibilityVO> finalCostResponsibilityVOS = costResponsibilityVOS;
        return costResponsibilityVOS.stream().filter(i -> i.getParentId() == 0)
                .peek(i -> i.setChild(this.getResponsibilityChildren(i, finalCostResponsibilityVOS)))
                .collect(Collectors.toList());
    }

    /**
     * @return
     */
    @Override
    public List<DictDataVo> getStandardShareLevel() {
        DictDataVo standardDict = centerService.getDict(Constant.STANDARD_SHARE_LEVEL);
        if(Objects.isNull(standardDict)){
            throw new CostException("未添加字典标准分摊层级字典");
        }
        List<DictDataVo> standardDictDataVoList = standardDict.getDataVoList();
        if(CollectionUtils.isEmpty(standardDictDataVoList)){
            throw new CostException("未添加字典标准分摊层级字典");
        }
        return standardDictDataVoList;
    }

    /**
     * @return
     */
    @Override
    public List<DictDataVo> getResponsibilityType() {
        DictDataVo responsibilityDict = centerService.getDict(Constant.RESPONSIBILITY_TYPE);
        if(Objects.isNull(responsibilityDict)){
            throw new CostException("未添加责任中心类型字典");
        }
        List<DictDataVo> dataVoList = responsibilityDict.getDataVoList();
        if(CollectionUtils.isEmpty(dataVoList)){
            throw new CostException("未添加责任中心类型字典");

        }
        return dataVoList;
    }

    private List<CostResponsibilityVO> getCostResponsibilityVO(String filter) {
        List<Responsibility> list = this.list(
                new LambdaQueryWrapper<Responsibility>()
                        .eq(Responsibility::getHospId, UserContext.getHospId())
                        .and(i->i.like(Responsibility::getResponsibilityCode,filter).or().like(Responsibility::getResponsibilityName,filter))
                        .orderByDesc(Responsibility::getCreateTime)
        );
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        // 拷贝组合
        return BeanUtil.convertList(list, CostResponsibilityVO.class);
    }
}