package com.cmvr.vi.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmvr.test.enums.FlowSceneTypeEnum;
import com.cmvr.test.model.domain.TeDetectionItem;
import com.cmvr.test.model.vo.TeQueryTaskOrchestraItemVO;
import com.cmvr.test.model.vo.TeTaskOrchestraVO;
import com.cmvr.test.service.ITeDetectionItemService;
import com.cmvr.test.service.ITeTaskOrchestrationService;
import com.cmvr.vi.mapper.ViSchemeMapper;
import com.cmvr.vi.model.domain.ViScheme;
import com.cmvr.vi.service.IViSchemeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * 语音交互-方案Service业务层处理
 *
 * @author cmvr-iot
 */
@Service
@RequiredArgsConstructor
public class ViSchemeServiceImpl extends ServiceImpl<ViSchemeMapper, ViScheme> implements IViSchemeService {

    private final ITeTaskOrchestrationService teTaskOrchestrationService;
    private final ITeDetectionItemService detectionItemService;

    @Override
    public ViScheme selectViSchemeBySchemeId(String schemeId) {
        return this.getById(schemeId);
    }

    @Override
    public List<ViScheme> selectViSchemeList(ViScheme viScheme) {
        LambdaQueryWrapper<ViScheme> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ViScheme::getProjectId, viScheme.getProjectId())
                .eq(ObjUtil.isNotEmpty(viScheme.getSchemeName()), ViScheme::getSchemeName, viScheme.getSchemeName())
                .eq(ObjUtil.isNotEmpty(viScheme.getStatus()), ViScheme::getStatus, viScheme.getStatus())
                .orderByAsc(ViScheme::getSort);
        return this.list(wrapper);
    }

    @Override
    public int insertViScheme(ViScheme viScheme) {
        // 先插方案
        int insert = this.baseMapper.insert(viScheme);

        String taskId = viScheme.getProjectId();
        Integer sort = viScheme.getSort();

        // 获取对应场景流程id
        String key = FlowSceneTypeEnum.fromCode(viScheme.getSceneType()).getSceneCode();
        TeDetectionItem item = detectionItemService.selectTeDetectionItemBySceneType(key);
        String itemId = item.getId();

        // 查询已有编排项
        List<TeQueryTaskOrchestraItemVO> items = teTaskOrchestrationService.queryByTaskId(taskId);

        // 插入新编排项
        TeQueryTaskOrchestraItemVO itemVO = new TeQueryTaskOrchestraItemVO();
        itemVO.setItemId(itemId);
        itemVO.setOrderNum(sort);
        if (CollUtil.isEmpty(items)) {
            items = new ArrayList<>();
        }
        items.add(itemVO);

        // 保存并归一化
        saveAndNormalizeItems(taskId, items);

        return insert;
    }

    @Override
    public int updateViScheme(ViScheme viScheme) {
        int update = this.baseMapper.updateById(viScheme);

        String taskId = viScheme.getProjectId();

        // 更新后，直接查询并归一化
        List<TeQueryTaskOrchestraItemVO> items = teTaskOrchestrationService.queryByTaskId(taskId);
        saveAndNormalizeItems(taskId, items);

        return update;
    }

    @Override
    public int deleteViSchemeBySchemeIds(String[] schemeIds) {
        List<String> schemeIdList = Arrays.asList(schemeIds);

        // 查要删除的方案，获取对应 taskId 和流程 itemId
        List<ViScheme> schemes = this.baseMapper.selectBatchIds(schemeIdList);
        int delete = this.baseMapper.deleteBatchIds(schemeIdList);

        // 每个 taskId 单独归一化一次
        Map<String, List<ViScheme>> taskSchemeMap = schemes.stream()
                .collect(Collectors.groupingBy(ViScheme::getProjectId));

        for (String taskId : taskSchemeMap.keySet()) {
            List<TeQueryTaskOrchestraItemVO> items = teTaskOrchestrationService.queryByTaskId(taskId);

            if (items != null && !items.isEmpty()) {
                // 找出要删的流程 itemId
                List<String> deleteItemIds = taskSchemeMap.get(taskId).stream()
                        .map(s -> {
                            String key = FlowSceneTypeEnum.fromCode(s.getSceneType()).getSceneCode();
                            return detectionItemService.selectTeDetectionItemBySceneType(key).getId();
                        })
                        .collect(Collectors.toList());

                // 移除这些 item
                items.removeIf(i -> deleteItemIds.contains(i.getItemId()));

                // 保存并归一化
                saveAndNormalizeItems(taskId, items);
            }
        }

        return delete;
    }

    @Override
    public List<ViScheme> querySchemesByProjectId(String projectId) {
        LambdaQueryWrapper<ViScheme> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ViScheme::getProjectId, projectId)
                .orderByAsc(ViScheme::getSort);
        return this.list(wrapper);
    }

    /**
     * 保存并归一化 taskId 的编排项
     */
    private void saveAndNormalizeItems(String taskId, List<TeQueryTaskOrchestraItemVO> items) {
        if (items == null || items.isEmpty()) {
            return;
        }

        // 按顺序排序
        items.sort(Comparator.comparing(TeQueryTaskOrchestraItemVO::getOrderNum));

        // 重新归一化 1..N
        for (int i = 0; i < items.size(); i++) {
            items.get(i).setOrderNum(i + 1);
        }

        // 落库
        List<String> itemIds = items.stream()
                .map(TeQueryTaskOrchestraItemVO::getItemId)
                .collect(Collectors.toList());

        TeTaskOrchestraVO orchestraVO = new TeTaskOrchestraVO();
        orchestraVO.setTaskId(taskId);
        orchestraVO.setItemIds(itemIds);

        teTaskOrchestrationService.insertTeTaskOrchestration(orchestraVO);
    }


}
