package shop.alien.lawyer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LawyerLegalProblemScenario;
import shop.alien.lawyer.service.LawyerLegalProblemScenarioService;
import shop.alien.mapper.LawyerLegalProblemScenarioMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 法律问题场景 服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Transactional
@Service
@RequiredArgsConstructor
public class LawyerLegalProblemScenarioServiceImpl extends ServiceImpl<LawyerLegalProblemScenarioMapper, LawyerLegalProblemScenario> implements LawyerLegalProblemScenarioService {

    @Override
    public R<LawyerLegalProblemScenario> addLawyerLegalProblemScenario(LawyerLegalProblemScenario lawyerLegalProblemScenario) {
        boolean result = this.save(lawyerLegalProblemScenario);
        if (result) {
            return R.data(lawyerLegalProblemScenario);
        }
        return R.fail("新增失败");
    }

    @Override
    public R<LawyerLegalProblemScenario> editLawyerLegalProblemScenario(LawyerLegalProblemScenario lawyerLegalProblemScenario) {
        log.info("LawyerLegalProblemScenarioServiceImpl.editLawyerLegalProblemScenario?LawyerLegalProblemScenario={}", lawyerLegalProblemScenario);
        boolean result = this.updateById(lawyerLegalProblemScenario);
        if (result) {
            return R.data(lawyerLegalProblemScenario);
        }
        return R.fail("修改失败");
    }

    @Override
    public R<Boolean> deleteLawyerLegalProblemScenario(Integer id) {
        log.info("LawyerLegalProblemScenarioServiceImpl.deleteLawyerLegalProblemScenario?id={}", id);
        
        // 参数校验
        if (id == null) {
            log.warn("删除法律问题场景失败：ID为空");
            return R.fail("场景ID不能为空");
        }
        
        // 查询要删除的场景
        LawyerLegalProblemScenario scenario = this.getById(id);
        if (scenario == null) {
            log.warn("删除法律问题场景失败：场景不存在，id={}", id);
            return R.fail("场景不存在");
        }
        
        // 递归删除所有子场景
        List<Integer> allIdsToDelete = new ArrayList<>();
        allIdsToDelete.add(id);
        collectChildIds(id, allIdsToDelete);
        
        log.info("准备删除场景及其子场景，共{}个，ids={}", allIdsToDelete.size(), allIdsToDelete);
        
        // 批量删除所有场景（包括当前场景和所有子场景）
        boolean result = this.removeByIds(allIdsToDelete);
        if (result) {
            log.info("删除法律问题场景成功，共删除{}个场景", allIdsToDelete.size());
            return R.success("删除成功，共删除" + allIdsToDelete.size() + "个场景");
        }
        return R.fail("删除失败");
    }
    
    /**
     * 递归收集所有子场景的ID
     *
     * @param parentId 父场景ID
     * @param idsList  用于收集所有子场景ID的列表
     */
    private void collectChildIds(Integer parentId, List<Integer> idsList) {
        // 查询所有直接子场景（parentId = 当前场景ID）
        QueryWrapper<LawyerLegalProblemScenario> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId)
                .eq("delete_flag", 0);
        List<LawyerLegalProblemScenario> children = this.list(queryWrapper);
        
        if (!CollectionUtils.isEmpty(children)) {
            for (LawyerLegalProblemScenario child : children) {
                Integer childId = child.getId();
                idsList.add(childId);
                // 递归查找子场景的子场景
                collectChildIds(childId, idsList);
            }
        }
    }

    @Override
    public R<LawyerLegalProblemScenario> getCategoryTreeByFirstLevelId(Integer id) {
        log.info("LawyerLegalProblemScenarioServiceImpl.getCategoryTreeByFirstLevelId?id={}", id);

        // 验证一级场景是否存在
        LawyerLegalProblemScenario firstLevel = this.getById(id);
        if (firstLevel == null) {
            return R.fail("一级场景不存在");
        }
        if (firstLevel.getLevel() == null || firstLevel.getLevel() != 1) {
            return R.fail("该主键不是一级场景");
        }

        // 查询所有二级分类（父ID为一级场景ID，level=2）
        QueryWrapper<LawyerLegalProblemScenario> secondLevelQuery = new QueryWrapper<>();
        secondLevelQuery.eq("parent_id", id)
                .eq("level", 2)
                .eq("delete_flag", 0)
                .orderByAsc("sort_order", "id");
        List<LawyerLegalProblemScenario> secondLevelList = this.list(secondLevelQuery);

        // 如果二级分类为空，直接返回一级场景（children为空列表）
        if (CollectionUtils.isEmpty(secondLevelList)) {
            firstLevel.setChildren(new ArrayList<>());
            return R.data(firstLevel);
        }

        // 获取所有二级分类的ID列表
        List<Integer> secondLevelIds = secondLevelList.stream()
                .map(LawyerLegalProblemScenario::getId)
                .collect(Collectors.toList());

        // 查询所有三级分类（父ID在二级分类ID列表中，level=3）
        QueryWrapper<LawyerLegalProblemScenario> thirdLevelQuery = new QueryWrapper<>();
        thirdLevelQuery.in("parent_id", secondLevelIds)
                .eq("level", 3)
                .eq("delete_flag", 0)
                .orderByAsc("sort_order", "id");
        List<LawyerLegalProblemScenario> thirdLevelList = this.list(thirdLevelQuery);

        // 将三级分类按父ID分组
        Map<Integer, List<LawyerLegalProblemScenario>> thirdLevelMap = thirdLevelList.stream()
                .collect(Collectors.groupingBy(LawyerLegalProblemScenario::getParentId));

        // 为每个二级分类设置其下的三级分类列表
        for (LawyerLegalProblemScenario secondLevel : secondLevelList) {
            List<LawyerLegalProblemScenario> children = thirdLevelMap.get(secondLevel.getId());
            secondLevel.setChildren(children != null ? children : new ArrayList<>());
        }

        // 将二级分类列表设置到一级场景的children中
        firstLevel.setChildren(secondLevelList);

        return R.data(firstLevel);
    }

    @Override
    public R<Boolean> setStatus(Integer id, Integer status) {
        log.info("LawyerLegalProblemScenarioServiceImpl.setStatus?id={},status={}", id, status);

        // 参数校验
        if (id == null) {
            log.warn("设置法律场景状态失败：场景ID为空");
            return R.fail("场景ID不能为空");
        }

        if (status == null || (status != 0 && status != 1)) {
            log.warn("设置法律场景状态失败：状态参数无效，status={}", status);
            return R.fail("状态参数无效，必须为0（禁用）或1（启用）");
        }

        // 查询场景信息
        LawyerLegalProblemScenario scenario = this.getById(id);
        if (scenario == null) {
            log.warn("设置法律场景状态失败：场景不存在，场景ID={}", id);
            return R.fail("场景不存在");
        }

        // 更新状态
        scenario.setStatus(status);
        boolean result = this.updateById(scenario);
        if (result) {
            log.info("设置法律场景状态成功：场景ID={},状态={}", id, status);
            return R.success("设置成功");
        } else {
            log.warn("设置法律场景状态失败：更新数据库失败，场景ID={},状态={}", id, status);
            return R.fail("设置失败");
        }
    }

}

