package com.test.test.service.impl;

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

import com.test.common.utils.DateUtils;
import com.test.common.utils.StringUtils;
import com.test.test.domain.UiSceneSteps;
import com.test.test.domain.qo.GroupDelectQO;
import com.test.test.mapper.*;
import com.test.test.service.IUiElementService;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.test.test.domain.TestGroup;
import com.test.test.service.ITestGroupService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 节点（文件夹）Service业务层处理
 *
 * @author xiaoe
 */
@Service
public class TestGroupServiceImpl implements ITestGroupService {

    @Resource
    private TestGroupMapper testGroupMapper;

    @Resource
    @Lazy
    private TestApiServiceImpl testApiServiceImpl;

    @Resource
    private UiElementMapper uiElementMapper;

    @Resource
    private UiAutomationMapper uiAutomationMapper;

    @Resource
    private UiSceneStepsMapper  uiSceneStepsMapper;

    @Resource
    private UiHighSettingMapper uiHighSettingMapper;

    /**
     * 查询节点（文件夹）列表
     */
    @Override
    public List<TestGroup> selectTestGroupList(String type) {
        return testGroupMapper.selectTestGroupList(type);
    }

    /**
     * 新增节点（文件夹）
     */
    @Override
    public TestGroup insertTestGroup(TestGroup testGroup) {
        testGroup.setCreateTime(DateUtils.getNowDate());
        testGroupMapper.insertTestGroup(testGroup);
        return testGroup;
    }

    @Override
    public TestGroup selectGroup(String name, Long parentId, String type) {
        return testGroupMapper.selectGroup(name, parentId, type);
    }

    /**
     * 修改节点（文件夹）
     */
    @Override
    public int updateTestGroup(TestGroup testGroup) {
        testGroup.setUpdateTime(DateUtils.getNowDate());
        return testGroupMapper.updateTestGroup(testGroup);
    }

    /**
     * 删除节点（文件夹）信息
     */
    @Override
    @Transactional
    public int deleteTestGroupById(GroupDelectQO qo) throws Exception {
        // 获取所有叶子节点
        List<Long> idList = new ArrayList<>(List.of(qo.getId()));
        idList.addAll(getAllChildrenId(idList));
        // 删除节点
        switch (qo.getType()) {
            case "api":
                testApiServiceImpl.deleteTestApiByGroups(idList);
                break;
            case "case":
                System.out.println("case");
                break;
            case "task":
                System.out.println("task");
                break;
            case "element":
                uiElementMapper.deleteUiElementByGroupIds(idList);
                break;
            case "automation":
                for (Long id : idList) {
                    UiSceneSteps uiSceneSteps = new UiSceneSteps();
                    uiSceneSteps.setAutomationId(id);
                    uiSceneSteps.setDelFlag(0);
                    List<UiSceneSteps> uiSceneStepsList = uiSceneStepsMapper.selectUiSceneStepsList(uiSceneSteps);
                    for (UiSceneSteps sceneSteps : uiSceneStepsList) {
                        uiHighSettingMapper.deleteUiHighSettingById(sceneSteps.getId());
                    }
                    uiSceneStepsMapper.deleteUiSceneStepsById(id);
                }
                uiAutomationMapper.deleteUiAutomationByGroupIds(idList);
                break;
            default:
                throw new Exception(StringUtils.format("文件夹类型({})非法。 ", qo.getType()));
        }
        return testGroupMapper.deleteTestGroupByIds(idList);
    }

    private List<Long> getAllChildrenId(List<Long> parentIds) {
        List<Long> idList = testGroupMapper.selectTestGroupListByParentIds(parentIds).stream().map(TestGroup::getId).collect(Collectors.toList());
        if (!idList.isEmpty()) {
            List<Long> childrenIds = getAllChildrenId(idList);
            if (!childrenIds.isEmpty()) {
                idList.addAll(childrenIds);
            }
        }
        return idList;
    }

    /**
     * 根据ID获取所有子元素ID（包括自身）
     * @param id 要查询的ID
     * @return 所有子元素ID集合（包含自身ID）
     */
    public List<Long> getAllChildIds(Long id,String type) {
        List<TestGroup> allGroups = selectTestGroupList(type);
        List<Long> result = new ArrayList<>();

        // 如果传入的是根节点（parentId=0），则查询所有数据
        if (id != null && id == 0L) {
            return allGroups.stream()
                    .map(TestGroup::getId)
                    .collect(Collectors.toList());
        }

        // 添加自身ID
        result.add(id);
        // 递归查找子节点
        findChildrenIds(id, allGroups, result);

        return result;
    }

    /**
     * 构建组路径名称
     * @param groupId 组ID
     * @return 如"全部元素/测试"
     */
    public String buildGroupPath(Long groupId) {
        List<String> names = new ArrayList<>();

        // 递归查找父组
        Long currentId = groupId;
        while (currentId != null && currentId != 0L) {
            TestGroup group = testGroupMapper.selectTestGroupById(currentId);
            if (group != null) {
                names.add(group.getName());
                currentId = group.getParentId();
            } else {
                break;
            }
        }

        // 反转列表，使父组在前
        Collections.reverse(names);

        return String.join("/", names);
    }

    /**
     * 递归查找所有子节点ID
     * @param parentId 父节点ID
     * @param allGroups 所有数据
     * @param result 结果集合
     */
    private void findChildrenIds(Long parentId, List<TestGroup> allGroups, List<Long> result) {
        for (TestGroup group : allGroups) {
            if (parentId.equals(group.getParentId())) {
                result.add(group.getId());
                findChildrenIds(group.getId(), allGroups, result);
            }
        }
    }




}
