package com.test.test.service.impl;

import java.util.ArrayList;
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.qo.GroupDelectQO;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.test.test.mapper.TestGroupMapper;
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;

    /**
     * 查询节点（文件夹）列表
     */
    @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;
            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;
    }
}
