package com.seer.teach.user.app.user.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.enums.UserRelationEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.user.app.convert.UserInfoConvert;
import com.seer.teach.user.app.user.controller.resp.AppMyFamilyResp;
import com.seer.teach.user.app.user.controller.resp.AppUserInfoResp;
import com.seer.teach.user.entity.UserEntity;
import com.seer.teach.user.entity.UserFamilyEntity;
import com.seer.teach.user.entity.UserRelationEntity;
import com.seer.teach.user.service.IUserFamilyService;
import com.seer.teach.user.service.IUserRelationService;
import com.seer.teach.user.service.IUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class AppMyFamilyService {

    private final IUserFamilyService userFamilyService;

    private final IUserRelationService userRelationService;

    private final IUserService userService;

    /**
     * 获取家庭下所有孩子
     *
     * @param userId   当前用户id
     * @param familyId 家庭id
     * @return 孩子列表
     */
    public List<AppUserInfoResp> getChildrenList(int userId, Integer familyId) {
        userFamilyService.checkUserFamily(userId, familyId);
        List<UserRelationEntity> userRelations = userRelationService.getUserRelationsByFamilyIdAndType(familyId, UserRelationEnum.PARENT_CHILD);
        if (CollectionUtil.isEmpty(userRelations)) {
            return Collections.emptyList();
        }
        Set<Integer> childrenIds = userRelations.stream().map(UserRelationEntity::getRelationId).collect(Collectors.toSet());
        List<UserEntity> users = userService.getListByUserIds(childrenIds);
        if (CollectionUtil.isEmpty(users)) {
            return Collections.emptyList();
        }
        return UserInfoConvert.INSTANCE.toUserInfoListResp(users);
    }

    /**
     * 获取家庭下所有监护人
     *
     * @param userId   当前用户id
     * @param familyId 家庭id
     * @return 监护人列表
     */
    public List<AppUserInfoResp> getGuardianList(int userId, Integer familyId) {
        userFamilyService.checkUserFamily(userId, familyId);
        List<UserRelationEntity> userRelations = userRelationService.getUserRelationsByFamilyIdAndType(familyId, UserRelationEnum.PARENT_CHILD);
        if (CollectionUtil.isEmpty(userRelations)) {
            return Collections.emptyList();
        }
        Set<Integer> userIds = userRelations.stream().map(UserRelationEntity::getUserId).collect(Collectors.toSet());
        List<UserEntity> users = userService.getListByUserIds(userIds);
        if (CollectionUtil.isEmpty(users)) {
            return Collections.emptyList();
        }
        UserFamilyEntity family = userFamilyService.getById(familyId);
        return UserInfoConvert.INSTANCE.toUserInfoListRespWithDefaultValue(users, family);
    }

    /**
     * 获取家庭详情
     *
     * @param userId   当前用户id
     * @param familyId 家庭id
     * @return 家庭详情
     */
    public AppMyFamilyResp getMyFamilyDetail(int userId, Integer familyId) {
        UserFamilyEntity family = userFamilyService.getById(familyId);
        AssertUtils.notNull(family, ResultCodeEnum.USER_FAMILY_NOT_EXIST);
        userFamilyService.checkUserFamily(userId, familyId);

        List<UserRelationEntity> userRelations = userRelationService.getUserRelationsByFamilyIdAndType(familyId, UserRelationEnum.PARENT_CHILD);
        if (CollectionUtil.isEmpty(userRelations)) {
            return new AppMyFamilyResp();
        }
        AppMyFamilyResp myFamilyResp = new AppMyFamilyResp();
        long guardianCount = userRelations.stream().mapToInt(UserRelationEntity::getUserId).distinct().count();
        long childrenCount = userRelations.stream().map(UserRelationEntity::getRelationId).distinct().count();
        myFamilyResp.setId(familyId);
        myFamilyResp.setGuardianCount(guardianCount);
        myFamilyResp.setChildrenCount(childrenCount);
        myFamilyResp.setName(family.getName());
        myFamilyResp.setIsPrimaryGuardian(Objects.equals(family.getPrimaryGuardianUserId(), userId));
        return myFamilyResp;
    }

    /**
     * 移除家庭下的监护人
     *
     * @param userId     当前用户id
     * @param familyId   家庭id
     * @param guardianId GuardianId
     */
    public boolean removeGuardian(int userId, Integer familyId, Integer guardianId) {
        // 1. 验证当前用户是否有权限操作该家庭
        UserFamilyEntity family = userFamilyService.getById(familyId);
        AssertUtils.notNull(family, ResultCodeEnum.USER_FAMILY_NOT_EXIST);
        if (!Objects.equals(family.getPrimaryGuardianUserId(), userId)) {
            throw new CommonException(ResultCodeEnum.USER_NO_PRIMARY_GUARDIAN);
        }
        // 2. 验证要移除的监护人是否存在于该家庭
        userFamilyService.checkUserFamily(userId, familyId);

        // 3. 验证不能移除自己（如果是监护人自己操作）
        if (userId == guardianId) {
            throw new CommonException(ResultCodeEnum.USER_CANNOT_REMOVE_SELF);
        }
        boolean removed = userRelationService.remove(new LambdaQueryWrapper<>(UserRelationEntity.class).eq(UserRelationEntity::getFamilyId, familyId).eq(UserRelationEntity::getUserId, guardianId));

        log.info("用户{}移除了家庭{}中的监护人{}的结果:{}", userId, familyId, guardianId, removed);
        return removed;
    }
}