package com.cmvr.aima.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.spring.service.impl.ServiceImpl;
import com.cmvr.aima.domain.AimaTaskTestCase;
import com.cmvr.aima.domain.AimaTestCase;
import com.cmvr.aima.domain.vo.AimaTaskVo;
import com.cmvr.aima.mapper.AimaTestCaseMapper;
import com.cmvr.test.model.domain.TeTaskConfigInfo;
import com.cmvr.test.model.vo.TeTaskOrchestraVO;
import com.cmvr.test.service.ITeTaskConfigInfoService;
import com.cmvr.test.service.ITeTaskOrchestrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cmvr.common.utils.DateUtils;
import com.cmvr.common.utils.SecurityUtils;
import com.cmvr.aima.mapper.AimaTaskMapper;
import com.cmvr.aima.mapper.AimaTaskTestCaseMapper;
import com.cmvr.aima.domain.AimaTask;
import com.cmvr.aima.service.IAimaTaskService;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class AimaTaskServiceImpl extends ServiceImpl<AimaTaskMapper, AimaTask> implements IAimaTaskService {
    @Autowired
    private AimaTaskMapper aimaTaskMapper;

    @Autowired
    private AimaTaskTestCaseMapper aimaTaskTestCaseMapper;

    @Autowired
    private AimaTestCaseMapper aimaTestCaseMapper;

    @Autowired
    private ITeTaskOrchestrationService teTaskOrchestrationService;

    @Autowired
    private ITeTaskConfigInfoService teTaskConfigInfoService;

    @Override
    public AimaTask selectAimaTaskById(String id) {
        return aimaTaskMapper.selectAimaTaskById(id);
    }

    @Override
    public List<AimaTask> selectAimaTaskList(AimaTask aimaTask) {
        return aimaTaskMapper.selectAimaTaskList(aimaTask);
    }

    @Override
    public List<AimaTaskVo> selectAimaTaskVoList(AimaTask aimaTask) {
        return aimaTaskMapper.selectAimaTaskVoList(aimaTask);
    }

    @Override
    public int insertAimaTask(AimaTask aimaTask) {
        // 生成UUID作为主键
        if (aimaTask.getId() == null || aimaTask.getId().isEmpty()) {
            aimaTask.setId(UUID.randomUUID().toString().replace("-", ""));
        }
        aimaTask.setCreateTime(DateUtils.getNowDate());
        aimaTask.setCreateBy(SecurityUtils.getUsername());
        // 同步新增任务配置到test模块
        TeTaskConfigInfo teTaskConfigInfo = TeTaskConfigInfo.builder()
                .taskName(aimaTask.getTaskName())
                .build();
        teTaskConfigInfoService.insertTeTaskConfigInfo(teTaskConfigInfo);
        aimaTask.setTaskConfigId(teTaskConfigInfo.getId());
        return aimaTaskMapper.insertAimaTask(aimaTask);
    }

    @Override
    public int updateAimaTask(AimaTask aimaTask) {
        aimaTask.setUpdateTime(DateUtils.getNowDate());
        aimaTask.setUpdateBy(SecurityUtils.getUsername());
        // 同步更新任务配置名称
        if (aimaTask.getTaskConfigId() != null) {
            TeTaskConfigInfo teTaskConfigInfo = teTaskConfigInfoService.selectTeTaskConfigInfoById(aimaTask.getTaskConfigId());
            if (teTaskConfigInfo != null) {
                teTaskConfigInfo.setTaskName(aimaTask.getTaskName());
                teTaskConfigInfoService.updateTeTaskConfigInfo(teTaskConfigInfo);
            }
        }
        return aimaTaskMapper.updateAimaTask(aimaTask);
    }

    @Override
    public int deleteAimaTaskByIds(String[] ids) {
        // 先删除关联表数据
        aimaTaskTestCaseMapper.deleteTaskTestCaseByTaskIds(ids);
        // 批量查询任务
        List<AimaTask> aimaTasks = this.baseMapper.selectBatchIds(Arrays.asList(ids));
        // 批量删除任务配置
        teTaskConfigInfoService.deleteTeTaskConfigInfoByIds(
            aimaTasks.stream().map(AimaTask::getTaskConfigId).toArray(String[]::new)
        );
        return aimaTaskMapper.deleteAimaTaskByIds(ids);
    }

    @Override
    public int deleteAimaTaskById(String id) {
        return aimaTaskMapper.deleteAimaTaskById(id);
    }

    @Override
    public void bindTestCases(String taskId, List<String> testCaseIds) {
        // 先删除旧的关联
        aimaTaskTestCaseMapper.deleteTaskTestCaseByTaskId(taskId);
        
        // 批量插入新的关联
        if (testCaseIds != null && !testCaseIds.isEmpty()) {
            List<AimaTaskTestCase> list = new ArrayList<>();
            for (int i = 0; i < testCaseIds.size(); i++) {
                AimaTaskTestCase taskTestCase = new AimaTaskTestCase();
                taskTestCase.setTaskId(taskId);
                taskTestCase.setTestCaseId(testCaseIds.get(i));
                taskTestCase.setSortOrder(i);
                list.add(taskTestCase);
            }
            aimaTaskTestCaseMapper.batchInsertTaskTestCase(list);
            
            // 更新任务的测试用例数量
            AimaTask task = new AimaTask();
            task.setId(taskId);
            task.setTestCaseCount(testCaseIds.size());
            aimaTaskMapper.updateAimaTask(task);
            
            // 查询测试用例，获取detectItemId列表
            List<AimaTestCase> testCases = aimaTestCaseMapper.selectBatchIds(testCaseIds);
            List<String> detectItemIds = testCases.stream()
                .map(AimaTestCase::getDetectItemId)
                .filter(itemId -> itemId != null && !itemId.isEmpty())
                .collect(Collectors.toList());
            
            // 同步任务编排到test模块
            if (!detectItemIds.isEmpty()) {
                AimaTask aimaTask = aimaTaskMapper.selectAimaTaskById(taskId);
                TeTaskOrchestraVO teTaskOrchestraVO = TeTaskOrchestraVO.builder()
                    .taskId(aimaTask.getTaskConfigId())
                    .itemIds(detectItemIds)
                    .build();
                teTaskOrchestrationService.insertTeTaskOrchestration(teTaskOrchestraVO);
            }
        }
    }

    @Override
    public List<AimaTestCase> getTestCaseIds(String taskId) {
        List<String> ids = aimaTaskTestCaseMapper.selectTestCaseIdsByTaskId(taskId);
        return aimaTestCaseMapper.selectList(new QueryWrapper<AimaTestCase>().in("id", ids));
    }
}
