package com.ruoyi.ibs.list.service.impl;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ibs.list.domain.FamilyMember;
import com.ruoyi.ibs.list.domain.Member;
import com.ruoyi.ibs.list.domain.RelationPath;
import com.ruoyi.ibs.list.mapper.FamilyMemberMapper;
import com.ruoyi.ibs.list.service.FamilyPathService;
import com.ruoyi.ibs.list.service.IFamilyMemberService;
import com.ruoyi.system.mapper.SysDictDataMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-03
 */
@Service
@Transactional
public class FamilyMemberServiceImpl implements IFamilyMemberService
{

    private static final Logger log = LoggerFactory.getLogger(FamilyMemberServiceImpl.class);
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private FamilyPathService pathService;
    @Autowired
    private SysDictDataMapper dictDataMapper;
    @Resource
    RedisCache redisCache;

    /**
     * 查询【请填写功能名称】
     * 
     * @param idCard 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public FamilyMember selectFamilyMemberByIdCard(String idCard)
    {
        return familyMemberMapper.selectFamilyMemberByIdCard(idCard);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param familyMember 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param familyMember 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.insertFamilyMember(familyMember);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param familyMember 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.updateFamilyMember(familyMember);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param idCards 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIdCards(String[] idCards)
    {
        return familyMemberMapper.deleteFamilyMemberByIdCards(idCards);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param idCard 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIdCard(String idCard)
    {
        return familyMemberMapper.deleteFamilyMemberByIdCard(idCard);
    }
    @Override
    // 修改后的构建方法（支持多级子孙）
    public Map<String, Object> buildFamilyGraph(String idCard) {
        Map<String, Object> result = new LinkedHashMap<>();

        // 获取当前成员信息
        FamilyMember currentMember = familyMemberMapper.getMemberByIdCard(idCard);
        log.info("根据当前身份证号获取的基准客户信息"+idCard+":"+currentMember);
        if(currentMember == null) throw new RuntimeException("成员不存在");

        // 构建主家庭树
        List<FamilyMember> mainFamily = familyMemberMapper.getMembersByFamilyId2(currentMember.getFamilyId());
        log.info("根据当前身份证号获取的主家庭树"+mainFamily);
        Map<String, RelationPath> mapPath= pathService.findAllPaths(idCard);
        log.info("根据当前身份证号到其余家庭成员的路径与称呼"+mainFamily);
        List<FamilyMember> allMembers = new ArrayList<>();
        allMembers.addAll(mainFamily);
        //List<FamilyMember> mainFamilySpouse = familyMemberMapper.getMembersSpouseByFamilyId(currentMember.getFamilyId());
        mainFamily = buildThreeFamilyTree(currentMember,mainFamily);

        mainFamily = mainFamily.stream().map(m->{
            RelationPath  relationPath = mapPath.get(m.getIdCard());
            if (relationPath!=null){
                m.setCallName(relationPath.getTitleFinal());
            }
            if (m.getIdCard().equals(idCard)){
                m.setCallName("自身");
            }
            if (m.getSpouse()!=null){
                RelationPath  relationPathSpouse = mapPath.get(m.getSpouse().getIdCard());
                m.getSpouse().setCallName(relationPathSpouse.getTitleFinal());
            }
            return m;
        }).collect(Collectors.toList());
        log.info("动态获取3代家族成员"+mainFamily);
        List<FamilyMember> mainRoot = buildFamilyTree(mainFamily,currentMember.getFamilyId(),allMembers);
        for (int i = 0; i < mainRoot.size(); i++) {
            FamilyMember node = mainRoot.get(i);
            setLevels(node);

        }
        result.put("mainFamily", mainRoot);
        log.info("构建成功的家族树"+mainRoot);
        // 构建配偶家庭树

        String spouseFamilyId = familyMemberMapper.getSpouseFamilyId(idCard);
        if(spouseFamilyId != null && !spouseFamilyId.equals(currentMember.getFamilyId())) {
            FamilyMember spouseMember = familyMemberMapper.getMemberByIdCard(currentMember.getSpouseCard());
            log.info("根据当前身份证号获取的基准客户配偶信息"+currentMember.getSpouseCard()+":"+spouseMember);
            List<FamilyMember> spouseFamily = familyMemberMapper.getMembersByFamilyId2(spouseFamilyId);
            List<FamilyMember> allMembersSpouse = new ArrayList<>();
            allMembersSpouse.addAll(spouseFamily);
            log.info("根据当前身份证号配偶的家庭id查询出配偶家族成员"+spouseFamily);
            spouseFamily = buildThreeFamilyTree(spouseMember,spouseFamily);
            log.info("动态根据当前身份证号配偶的家庭id查询出配偶三代家族成员"+spouseFamily);
            spouseFamily = spouseFamily.stream().map(m->{
                RelationPath relationPath = mapPath.get(m.getIdCard());
                if (relationPath!=null){
                    m.setCallName(relationPath.getTitleFinal());
                }
                if (m.getSpouse()!=null){
                    RelationPath  relationPathSpouse = mapPath.get(m.getSpouse().getIdCard());
                    m.getSpouse().setCallName(relationPathSpouse.getTitleFinal());
                }
                return m;
            }).collect(Collectors.toList());
            List<FamilyMember> spouseRoot = buildFamilyTree(spouseFamily,spouseFamilyId,allMembersSpouse);
            for (int i = 0; i < spouseRoot.size(); i++) {
                FamilyMember node = spouseRoot.get(i);
                setLevels(node);
            }

            result.put("spouseFamily", spouseRoot);


        }else {
            result.put("spouseFamily", new ArrayList<>());
        }

        return result;
    }
    public void setLevels(FamilyMember familyMember){
        if (familyMember==null) return;
         setLevel(familyMember,1L);
    }
    private void setLevel(FamilyMember member,Long level){
        member.setLevel(level);
        if (member.getChildren()!=null){
            for (FamilyMember child:member.getChildren()){
                setLevel(child,level+1);
            }
        }

    }

    public  List<FamilyMember> buildThreeFamilyTree(FamilyMember member,List<FamilyMember> familyMembers){
        List<FamilyMember> returnList = new LinkedList<>();
        returnList.add(member);
        List<FamilyMember> sonList = familyMembers.stream().filter(m->member.getIdCard().equals(m.getFatherCard())||
                member.getIdCard().equals(m.getMotherCard())).collect(Collectors.toList());
        returnList.addAll(sonList);
        returnList.addAll(familyMembers.stream().filter(m->member.getIdCard().equals(m.getSpouseCard())).collect(Collectors.toList()));
        //当前节点是根节点，则获取配偶节点，向下两级直系子女节点，兄弟姐妹节点
        if (StringUtils.isBlank(member.getFatherCard())&&StringUtils.isBlank(member.getMotherCard())){
             if (member.getBsId()!=null){
                 returnList.addAll(familyMembers.stream().filter(m->member.getBsId().equals(m.getBsId())).collect(Collectors.toList()));
             }
             //查询子节点的子节点
             if (sonList.size()>0){
                 for (int i = 0; i < sonList.size(); i++) {
                     int finalI = i;
                     returnList.addAll(familyMembers.stream().filter(m->sonList.get(finalI).getIdCard().equals(m.getFatherCard())||
                             sonList.get(finalI).getIdCard().equals(m.getMotherCard())).collect(Collectors.toList()));
                     returnList.addAll(familyMembers.stream().filter(m->sonList.get(finalI).getIdCard().equals(m.getSpouseCard())).collect(Collectors.toList()));
                 }
             }


        }
        //当前节点是中间节点，向上向下各扩展一级，向上展示父母，向下展示子女，同级展示兄弟姐妹
        else if (StringUtils.isNotBlank(member.getFatherCard())||StringUtils.isNotBlank(member.getMotherCard())&&sonList.size()>0) {
            //添加父母节点
            returnList.addAll(familyMembers.stream().filter(m->m.getIdCard().equals(member.getFatherCard()
                    )||m.getIdCard().equals(member.getMotherCard())).collect(Collectors.toList()));
            List<FamilyMember> fatherMembers = familyMembers.stream().filter(m->m.getIdCard().equals(member.getFatherCard())).collect(Collectors.toList());
            if (fatherMembers.size()>0){
                FamilyMember fatherMember = fatherMembers.get(0);
                if (StringUtils.isNotBlank(fatherMember.getBsId())){
                    List<FamilyMember> membersFatherSiblings = familyMembers.stream().filter(m->m.getBsId()!=null&&fatherMember.getBsId().equals(m.getBsId())).collect(Collectors.toList());
                    returnList.addAll(membersFatherSiblings);
                }
            }

            //添加兄弟节点
            if (StringUtils.isNotBlank(member.getBsId())){
                returnList.addAll(familyMembers.stream().filter(m->member.getBsId().equals(m.getBsId())).collect(Collectors.toList()));
            }
        }
        //当前节点是最下面节点，展示配偶，父母，兄弟姐妹,祖父母
         if (sonList.size()==0) {
            List<FamilyMember> parentList = familyMembers.stream().filter(m->m.getIdCard().equals(member.getFatherCard()
            )||m.getIdCard().equals(member.getMotherCard())).collect(Collectors.toList());
            returnList.addAll(parentList);

            if (member.getBsId()!=null){
                returnList.addAll(familyMembers.stream().filter(m->member.getBsId().equals(m.getBsId())).collect(Collectors.toList()));
            }
            if (parentList.size()>0){
                for (int i = 0; i < parentList.size(); i++) {
                    int finalI = i;
                    returnList.addAll(familyMembers.stream().filter(m->m.getIdCard().equals(parentList.get(finalI).getFatherCard())||
                            m.getIdCard().equals(parentList.get(finalI).getMotherCard())).collect(Collectors.toList()));
                }
            }
        }
         returnList = returnList.stream().collect(
                 Collectors.collectingAndThen(Collectors.toCollection(
                         () -> new TreeSet<>(Comparator.comparing(p -> p.getIdCard()))), ArrayList::new)
         );
         Map<String,List<FamilyMember>> mp = familyMembers.stream().collect(Collectors.groupingBy(FamilyMember::getIdCard));

        for (int i = 0; i < returnList.size(); i++) {
            if (returnList.get(i).getSpouse()==null&&StringUtils.isNotBlank(returnList.get(i).getSpouseCard())){
                List<FamilyMember> spouse = mp.get(returnList.get(i).getSpouseCard()) ;
                if (spouse!=null&&spouse.size()>0){
                    Member s = new Member();
                    BeanUtils.copyProperties(spouse.get(0),s);
                    returnList.get(i).setSpouse(s);
                }


            }


        }

     return returnList;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addRelatePerson(String idCard, String relation, Member familyMember) {
        if(familyMember.getIdCard().equals(idCard)){
            throw new RuntimeException("基准证件号不能与插入证件号一致");
        }
        FamilyMember memberOrigin = familyMemberMapper.getMemberByIdCard(idCard);
        if (memberOrigin==null){
            throw new RuntimeException("基准证件号不存在");
        }
        if (StringUtils.isBlank(familyMember.getIdCard())){
            throw new RuntimeException("插入成员证件号不能为空");
        }
        if(memberOrigin.getIsVirtual()){
            throw new RuntimeException("虚拟用户禁止添加关系");
        }
        //查询出要插入的客户是否已经存在
        FamilyMember memberInsert = familyMemberMapper.selectFamilyMemberByIdCard(familyMember.getIdCard());
        List<FamilyMember> familyMembers = familyMemberMapper.getChildrenByAnyParent(idCard);
        if (relation.equals("son")){
            if ("M".equals(memberOrigin.getGender())){
                familyMember.setFatherCard(idCard);
                familyMember.setFamilyId(memberOrigin.getFamilyId());
            }else {
                familyMember.setMotherCard(idCard);
            }
            if (StringUtils.isNotBlank(memberOrigin.getSpouseCard())){
                FamilyMember memberOriginSpouse = familyMemberMapper.getMemberByIdCard(memberOrigin.getSpouseCard());
                if ("M".equals(memberOrigin.getGender())){
                    familyMember.setMotherCard(memberOrigin.getSpouseCard());
                }else {
                    familyMember.setFatherCard(memberOrigin.getSpouseCard());
                    familyMember.setFamilyId(memberOriginSpouse.getFamilyId());
                }
            }else{
                familyMember.setFamilyId(memberOrigin.getFamilyId());
            }

            if (familyMembers!=null&&familyMembers.size()>0){
                //存在兄弟姐妹，插入相同bsId
                String bsId = familyMembers.get(0).getBsId();
                if (StringUtils.isNotBlank(bsId)){
                    familyMember.setBsId(bsId);
                }else{
                    bsId = UUID.randomUUID().toString();
                    familyMember.setBsId(bsId);
                    String finalBsId = bsId;
                    familyMembers = familyMembers.stream().map(m->{
                        m.setBsId(finalBsId);
                        return m;
                    }).collect(Collectors.toList());
                    for (int i = 0; i < familyMembers.size(); i++) {
                        updateFamilyMember(familyMembers.get(i));
                    }

                }
            }
        } else if (relation.equals("father")||relation.equals("mother")) {
            //添加父节点，其家庭id与子相同，母节点暂时为其身份证号
            if (relation.equals("father")){
                if (StringUtils.isNotBlank(memberOrigin.getFatherCard())&&!memberOrigin.getFatherCard().equals(familyMember.getIdCard())){
                    FamilyMember father = familyMemberMapper.getMemberByIdCard(memberOrigin.getFatherCard());
                    if (father!=null && !father.getIsVirtual()){
                        throw new IllegalArgumentException("当前节点已存在父亲，不允许新增");
                    }
                    if (father!=null && father.getIsVirtual()){
                        // 继承虚拟节点的父母关系 删除虚拟节点
                        familyMember.setFatherCard(father.getFatherCard());
                        familyMember.setMotherCard(father.getMotherCard());
                        familyMemberMapper.deleteFamilyMemberByIdCard(father.getIdCard());
                    }
                }
                familyMember.setFamilyId(memberOrigin.getFamilyId());
                memberOrigin.setFatherCard(familyMember.getIdCard());
                if (StringUtils.isNotBlank(memberOrigin.getMotherCard())){
                    FamilyMember mother = familyMemberMapper.getMemberByIdCard(memberOrigin.getMotherCard());
                    if (mother!=null){
                        mother.setSpouseCard(familyMember.getIdCard());
                        updateFamilyMember(mother);
                        familyMember.setSpouseCard(mother.getIdCard());
                    }
                }
            }
            if (relation.equals("mother")){
                if (StringUtils.isNotBlank(memberOrigin.getMotherCard())&&!memberOrigin.getMotherCard().equals(familyMember.getIdCard())){
                    FamilyMember mother = familyMemberMapper.getMemberByIdCard(memberOrigin.getMotherCard());
                    if (mother!=null){
                        throw new IllegalArgumentException("当前节点已存在母亲，不允许新增");
                    }
                }
                //若原来不存在该节点，则先设置其家庭id为身份证，后续有了家庭成员再更新即可
                if (memberInsert==null){
                    familyMember.setFamilyId(familyMember.getIdCard());
                }
                memberOrigin.setMotherCard(familyMember.getIdCard());
                if (StringUtils.isNotBlank(memberOrigin.getFatherCard())){
                    FamilyMember father = familyMemberMapper.getMemberByIdCard(memberOrigin.getFatherCard());
                    if (father!=null){
                        father.setSpouseCard(familyMember.getIdCard());
                        updateFamilyMember(father);
                        familyMember.setSpouseCard(father.getIdCard());
                    }
                }
            }
            updateFamilyMember(memberOrigin);
            String bs = memberOrigin.getBsId();
            if (StringUtils.isNotBlank(bs)){
                List<FamilyMember> bros = familyMemberMapper.selectFamilyMemberByBsId(bs);
                for (int i = 0; i < bros.size(); i++) {
                    FamilyMember m= bros.get(i);
                    if (relation.equals("father")){
                        m.setFatherCard(familyMember.getIdCard());
                    }
                    if (relation.equals("mother")){
                        m.setMotherCard(familyMember.getIdCard());
                    }
                    familyMemberMapper.updateFamilyMember(m);

                }
            }

        }else if (relation.equals("brother")){
            familyMember.setFatherCard(memberOrigin.getFatherCard());
            familyMember.setMotherCard(memberOrigin.getMotherCard());
            familyMember.setFamilyId(memberOrigin.getFamilyId());
            String bs = memberOrigin.getBsId();
            if (StringUtils.isNotBlank(bs)){
                familyMember.setBsId(bs);
            }else {
                String bsId = UUID.randomUUID().toString();
                memberOrigin.setBsId(bsId);
                familyMember.setBsId(bsId);
                updateFamilyMember(memberOrigin);
            }

        }else if (relation.equals("spouse")){
            if (StringUtils.isNotBlank(memberOrigin.getSpouseCard())&&!memberOrigin.getSpouseCard().equals(familyMember.getIdCard())){
                FamilyMember spouse = familyMemberMapper.getMemberByIdCard(memberOrigin.getSpouseCard());
                if (spouse!=null){
                    throw new IllegalArgumentException("当前节点已存在配偶，不允许新增配偶");
                }
            }
            familyMember.setSpouseCard(idCard);
            //familyMember.setSpouseFamilyId(memberOrigin.getFamilyId());
            //若原来不存在该节点，则先设置其家庭id为身份证，后续有了家庭成员再更新即可
            if (memberInsert==null){
                familyMember.setFamilyId(familyMember.getIdCard());
//                memberOrigin.setSpouseFamilyId(familyMember.getIdCard());
            }
            memberOrigin.setSpouseCard(familyMember.getIdCard());
            updateFamilyMember(memberOrigin);
            //当前节点存在子节点
            if (familyMembers!=null&&familyMembers.size()>0){

                    for (int i = 0; i < familyMembers.size(); i++) {
                        if ("M".equals(memberOrigin.getGender())){
                            familyMembers.get(i).setMotherCard(familyMember.getIdCard());
                        }else {
                            familyMembers.get(i).setMotherCard(familyMember.getIdCard());
                        }
                        updateFamilyMember(familyMembers.get(i));
                    }


            }

        }else if(relation.equals("grandson")){
            // 创建一个虚拟的家庭成员对象
            FamilyMember virtual = new FamilyMember();
            virtual.setName("虚拟成员");
            virtual.setAge(0L);
            // 为虚拟家庭成员设置唯一的身份证号，使用UUID确保唯一性
            virtual.setIdCard( UUID.randomUUID().toString());
            // 设置虚拟家庭成员的性别为男性
            virtual.setGender("M");
            // 将虚拟家庭成员的家族ID设置为原始成员的家族ID，保持家族关系的一致性
            virtual.setFamilyId(memberOrigin.getFamilyId());
            // 标记该家庭成员为虚拟成员
            virtual.setIsVirtual(Boolean.TRUE);
            // 根据原始成员的性别，确定虚拟成员与原始成员的关系
            if(memberOrigin.getGender().equals("M")){
                // 如果原始成员是男性，设置虚拟成员的生父身份证号为原始成员的身份证号
                virtual.setFatherCard(memberOrigin.getIdCard());
            }else{
                // 如果原始成员是女性，设置虚拟成员的生母身份证号为原始成员的身份证号
                virtual.setMotherCard(memberOrigin.getIdCard());
            }
            virtual.setCreateTime(new Date());
            // 插入虚拟家庭成员信息到数据库中
            insertFamilyMember(virtual);

            familyMember.setFatherCard(virtual.getIdCard());
            familyMember.setMotherCard(null);
            familyMember.setFamilyId(memberOrigin.getFamilyId());

        }
        FamilyMember member = new FamilyMember();
        BeanUtils.copyProperties(familyMember,member);
        member.setCreateBy(idCard);
        member.setCreateTime(new Date());
        member.setIsVirtual(Boolean.FALSE);
        if (memberInsert!=null && !memberInsert.getIsVirtual()){
            return updateFamilyMember(member);
        }else {
            return insertFamilyMember(member);
        }

    }

    @Override
    public int removeRelatePerson(String idCard) {
        List<FamilyMember> childrens = familyMemberMapper.getChildrenByAnyParent(idCard);
        if (childrens!=null&&childrens.size()>0){
            throw new IllegalStateException("当前节点存在子节点，不允许删除");
        }
        FamilyMember member = familyMemberMapper.getMemberByIdCard(idCard);
        FamilyMember member2 = new FamilyMember();
        if (member!=null){

            member2.setName(member.getName());
            member2.setIdCard(idCard);
            member2.setGender(member.getGender());
            //更改familyId，断除与已有成员关系
            UUID key = UUID.randomUUID();
            member2.setFamilyId(key.toString());
            member2.setAge(member.getAge());
            //配偶不为空，将配偶的配偶id置空
            if (StringUtils.isNotBlank(member.getSpouseCard())){
                FamilyMember memberSpouse = familyMemberMapper.getMemberByIdCard(member.getSpouseCard());
                if (memberSpouse!=null){
                    memberSpouse.setSpouseCard("");
                    updateFamilyMember(memberSpouse);
                }
            }
        }
        familyMemberMapper.deleteFamilyMemberByIdCard(idCard);
        return familyMemberMapper.insertFamilyMember(member2);
    }

    @Override
    public int addSelf(Member familyMember) {
        //初始时将家庭id设为身份证号，后续更新
        if (StringUtils.isNotBlank(familyMember.getIdCard())){
            FamilyMember m = familyMemberMapper.getMemberByIdCard(familyMember.getIdCard());
            if (m!=null){
                throw new IllegalArgumentException("当前节点已存在");
            }
        }
        familyMember.setFamilyId(familyMember.getIdCard());
        FamilyMember member = new FamilyMember();
        BeanUtils.copyProperties(familyMember,member);
        return familyMemberMapper.insertFamilyMember(member);
    }

    @Override
    public List<FamilyMember> selectFamilyMemberListByIdCard(String idCard) {
        FamilyMember currentMember = familyMemberMapper.selectFamilyMemberByIdCard(idCard);
        if (currentMember==null){
            return new ArrayList<>();
        }
        List<FamilyMember> familyMembers =  familyMemberMapper.getMembersByFamilyId2(currentMember.getFamilyId());
        String spouseFamilyId = familyMemberMapper.getSpouseFamilyId(idCard);
        if (StringUtils.isNotBlank(spouseFamilyId)){
            List<FamilyMember> spouseMembers  =  familyMemberMapper.getMembersByFamilyId2(currentMember.getFamilyId());
            if (spouseMembers!=null&&spouseMembers.size()>0){
                familyMembers.addAll(spouseMembers);
            }


        }
        //去重
        familyMembers = familyMembers.stream().collect(
                Collectors.collectingAndThen(Collectors.toCollection(
                        () -> new TreeSet<>(Comparator.comparing(p -> p.getIdCard()))), ArrayList::new)
        );
        familyMembers = familyMembers.stream().filter(m->!idCard.equals(m.getIdCard())).collect(Collectors.toList());
        Map<String, RelationPath> mapPath= pathService.findAllPaths(idCard);
        familyMembers = familyMembers.stream().map(m->{
            RelationPath  relationPath = mapPath.get(m.getIdCard());
            if (relationPath!=null){
                m.setCallName(relationPath.getTitleFinal());
            }
            if (m.getIdCard().equals(idCard)){
                m.setCallName("自身");
            }
            return m;
        }).collect(Collectors.toList());
        return familyMembers;
    }

    // 构建树结构核心算法
    private List<FamilyMember> buildFamilyTree(List<FamilyMember> members,String familyId,List<FamilyMember> allMembers) {
        Map<String, FamilyMember> memberMap = new HashMap<>();
        List<FamilyMember> familyMembers = new ArrayList<>();
        FamilyMember root = null;

        // 第一遍遍历：建立映射关系
        for (FamilyMember member : members) {
            memberMap.put(member.getIdCard(), member);
            if (familyId.equals(member.getFamilyId())&&StringUtils.isBlank(member.getFatherCard())&&StringUtils.isBlank(member.getMotherCard())) {
                root = member;
                if (!familyMembers.contains(root)){
                    familyMembers.add(root);
                }

            }
            if ((!familyId.equals(member.getFamilyId()))&&StringUtils.isBlank(member.getFatherCard())&&StringUtils.isBlank(member.getMotherCard())&&StringUtils.isBlank(member.getSpouseCard())) {
                root = member;
                if (!familyMembers.contains(root)){
                    familyMembers.add(root);
                }

            }
        }

        //虽有父母节点，但是在三代显示中其是根节点
        for (FamilyMember member : members) {
            if (familyId.equals(member.getFamilyId())&&memberMap.get(member.getFatherCard()) == null&&memberMap.get(member.getMotherCard())==null) {
                root = member;
                if (!familyMembers.contains(root)){
                    familyMembers.add(root);
                }
            }
            if ((!familyId.equals(member.getFamilyId()))&&memberMap.get(member.getFatherCard()) == null&&memberMap.get(member.getMotherCard())==null&&StringUtils.isBlank(member.getSpouseCard())) {
                root = member;
                if (!familyMembers.contains(root)){
                    familyMembers.add(root);
                }
            }
        }

        allMembers = allMembers.stream().filter(m->StringUtils.isNotBlank(m.getBsId())).collect(Collectors.toList());
        Map<String ,List<FamilyMember>> familyMemberListMap = allMembers.stream().collect(Collectors.groupingBy(FamilyMember::getBsId));

        // 第二遍遍历：构建关系
        for (FamilyMember member : members) {
            // 处理父子关系
            if (member.getFatherCard() != null||member.getMotherCard()!=null) {
                FamilyMember father = memberMap.get(member.getFatherCard());
                FamilyMember mother = memberMap.get(member.getMotherCard());
                if (father != null) {
                    if (father.getChildren()==null){
                        father.setChildren(new ArrayList<>());
                    }
                    if (!father.getChildren().contains(member)){
                        father.getChildren().add(member);
                    }

                }
                if (mother != null) {
                    if (mother.getChildren()==null){
                        mother.setChildren(new ArrayList<>());
                    }
                    if (!mother.getChildren().contains(member)){
                        mother.getChildren().add(member);
                    }
                }
            }

            // 处理母子关系
//            if (member.getMotherCard() != null) {
//                FamilyMember parent = memberMap.get(member.getMotherCard());
//                if (parent != null) {
//                    if (parent.getChildren()==null){
//                        parent.setChildren(new ArrayList<>());
//                    }
//                    parent.getChildren().add(member);
//                }
//            }

            // 处理兄弟关系
            if (StringUtils.isNotBlank(member.getBsId())){
                List<FamilyMember> sibs = familyMemberListMap.get(member.getBsId());
                List<Member> idCardSibs =sibs.stream().filter(m->!m.getIdCard().equals(member.getIdCard())).map(m->{
                    Member member1 = new Member();
                    BeanUtils.copyProperties(m,member1);
                    return  member1;
                }).collect(Collectors.toList());
                 member.setSibling(idCardSibs);
            }

            // 处理配偶关系
            if (member.getSpouseCard() != null&&familyId.equals(member.getFamilyId())) {
                if (StringUtils.isNotBlank(member.getSpouseCard())){
                    FamilyMember spouse = memberMap.get(member.getSpouseCard());
                    if (spouse != null) {
                        Member s = new Member();
                        BeanUtils.copyProperties(spouse,s);
                        member.setSpouse(s);
                    }
                }

            }
        }

        return familyMembers;
    }



    @Override
    public Map<String, String> getRelationShipMap() {

        Map<String,String> params = new HashMap<>();
        ArrayList<SysDictData> sysDictTypeArrayList = new ArrayList<SysDictData>(redisCache.getCacheObject("sys_dict:family_relation"));
        sysDictTypeArrayList.forEach(sdt -> {
            params.put(sdt.getDictValue(), sdt.getDictLabel());
        });
        return params;
    }




//    private List<FamilyMember> buildFamilyTreeNew(List<Member> members, String familyId) {
//        Map<String, Member> memberMap = new HashMap<>();
//        List<FamilyTree> familyMembers = new ArrayList<>();
//        FamilyTree root = null;
//
//        // 第一遍遍历：建立映射关系
//        for (Member member : members) {
//            memberMap.put(member.getIdCard(), member);
//            if (member.getFamilyId().equals(familyId)&&member.getFatherCard() == null&&member.getMotherCard()==null) {
//                root = new FamilyTree();
//                root.setSelf(member);
//                familyMembers.add(root);
//            }
//        }
//
//
//        // 第二遍遍历：构建关系
//        for (Member member : members) {
//            // 处理父子关系
//            if (member.getFatherCard() != null) {
//                Member parent = memberMap.get(member.getFatherCard());
//                if (parent != null) {
//                    if (parent.getChildren()==null){
//                        parent.setChildren(new ArrayList<>());
//                    }
//                    parent.getChildren().add(member);
//                }
//            }
//
//            // 处理父子关系
//            if (member.getMotherCard() != null) {
//                FamilyMember parent = memberMap.get(member.getMotherCard());
//                if (parent != null) {
//                    if (parent.getChildren()==null){
//                        parent.setChildren(new ArrayList<>());
//                    }
//                    parent.getChildren().add(member);
//                }
//            }
//
//            // 处理配偶关系
//            if (member.getSpouseCard() != null&&member.getFamilyId().equals(familyId)) {
//                FamilyMember spouse = memberMap.get(member.getSpouseCard());
//                if (spouse != null) {
//                    member.setSpouse(spouse);
//                }
//            }
//        }
//
//        return familyMembers;
//    }
}
