package cd.casic.ci.process.process.service.template.impl;


import cd.casic.ci.process.dto.req.template.TemplateQueryReq;
import cd.casic.ci.process.dto.resp.template.TemplateFindResp;
import cd.casic.ci.process.dto.resp.template.TemplateStageResp;
import cd.casic.ci.process.process.converter.TemplateConverter;
import cd.casic.ci.process.process.dao.template.TemplateManagerDao;
import cd.casic.ci.process.process.dao.template.TemplateStageDao;
import cd.casic.ci.process.process.dao.template.TemplateTaskDao;
import cd.casic.ci.process.process.dataObject.template.TemplateManager;
import cd.casic.ci.process.process.dataObject.template.TemplateStage;
import cd.casic.ci.process.process.dataObject.template.TemplateTask;
import cd.casic.ci.process.process.service.template.TemplateManagerService;
import cd.casic.framework.commons.exception.ServiceException;
import cd.casic.framework.commons.exception.enums.GlobalErrorCodeConstants;
import cd.casic.framework.commons.pojo.PageResult;
import cd.casic.framework.security.dal.user.AdminUserDO;
import cd.casic.framework.tenant.core.service.AdminUserServiceImpl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

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

/**
 * @author HopeLi
 * @version v1.0
 * @ClassName PipelineServiceImpl
 * @Date: 2025/5/13 10:31
 * @Description:
 */
@Service
@Slf4j
public class TemplateManagerServiceImpl extends ServiceImpl<TemplateManagerDao, TemplateManager> implements TemplateManagerService {

    @Resource
    private TemplateManagerDao templateManagerDao;

    @Resource
    private TemplateStageDao templateStageDao;

    @Resource
    private TemplateTaskDao templateTaskDao;

    @Resource
    private AdminUserServiceImpl adminUserService;
    @Resource
    private TemplateConverter templateConverter;

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public String createTemplate(PipelineCreateReq pipelineReq) {
//
//        PipPipeline pipeline = new PipPipeline();
//        BeanUtils.copyProperties(pipelineReq, pipeline);
//        // 随机颜色
//        int randomNumber = (int)(Math.random() * 5) + 1;
//        pipeline.setColor(randomNumber);
//
//        pipeline.setCreateTime(LocalDateTime.now());
//        if (Objects.isNull(pipeline.getCreator())){
//            pipeline.setCreator(String.valueOf(WebFrameworkUtils.getLoginUserId()));
//        }
//
//        pipeline.setState(1);
//        pipeline.setMachineId("1");
//
//        //新增对应的配置类数据
//        if (!ObjectUtils.isEmpty(pipelineReq.getResourceReq())){
//            PipResource resource = new PipResource();
//            BeanUtils.copyProperties(pipelineReq.getResourceReq(),resource);
//            resource.setCreator(pipeline.getCreator());
//            resource.setCreateTime(LocalDateTime.now());
//            resourceService.save(resource);
//
//            pipeline.setResourceId(resource.getId());
//        }
//
//        this.save(pipeline);
//
//        //TODO 根据模板覆写对应的阶段信息以及节点信息
////        List<StageReq> stageReqList = templateService.findStageById(pipelineReq.getTemplateId());
////        stageReqList.forEach(o->{
////            o.setPipelineId(pipeline.getId());
////        });
//        //新增初始阶段，无串行并行任务
//        PipStage stageReq1 = new PipStage();
//        stageReq1.setPipelineId(pipeline.getId());
//        stageReq1.setStageName("阶段-1");
//        stageReq1.setCreateTime(LocalDateTime.now());
//        stageReq1.setCreator(String.valueOf(WebFrameworkUtils.getLoginUserId()));
//        stageReq1.setStageSort(1);
//        stageReq1.setParentId("-1");
//        stageReq1.setCode(true);
//        stageService.save(stageReq1);
//
//        PipStage childStage1 = new PipStage();
//        childStage1.setPipelineId(pipeline.getId());
//        childStage1.setStageName("源码");
//        childStage1.setCreateTime(LocalDateTime.now());
//        childStage1.setCreator(String.valueOf(WebFrameworkUtils.getLoginUserId()));
//        childStage1.setStageSort(1);
//        childStage1.setCode(false);
//        childStage1.setParentId(stageReq1.getId());
//        stageService.save(childStage1);
//
//        PipTask childTask11 = new PipTask();
//        childTask11.setCreateTime(LocalDateTime.now());
//        childTask11.setCreator(String.valueOf(WebFrameworkUtils.getLoginUserId()));
//        childTask11.setTaskName("串行任务-1-1");
//        childTask11.setPipelineId(pipeline.getId());
//        childTask11.setTaskType("CODE");
//        childTask11.setTaskSort(1);
//        childTask11.setStageId(childStage1.getId());
//        taskService.save(childTask11);
//
//        //新增第二个阶段，包含串行和并行任务
//        PipStage stageReq2 = new PipStage();
//        stageReq2.setPipelineId(pipeline.getId());
//        stageReq2.setStageName("阶段-2");
//        stageReq2.setCreateTime(LocalDateTime.now());
//        stageReq2.setCreator(String.valueOf(WebFrameworkUtils.getLoginUserId()));
//        stageReq2.setStageSort(2);
//        stageReq2.setParentId("-1");
//        stageReq2.setCode(true);
//        stageService.save(stageReq2);
//
//        //新增并行阶段
//        PipStage childStage21 = new PipStage();
//        childStage21.setStageName("并行阶段-2-1");
//        childStage21.setPipelineId(pipeline.getId());
//        childStage21.setCreateTime(LocalDateTime.now());
//        childStage21.setCreator(String.valueOf(WebFrameworkUtils.getLoginUserId()));
//        childStage21.setStageSort(1);
//        childStage21.setCode(false);
//        childStage21.setParentId(stageReq2.getId());
//        stageService.save(childStage21);
//
//        //新增串行阶段
//        PipTask childTask21 = new PipTask();
//        childTask21.setPipelineId(pipeline.getId());
//        childTask21.setTaskName("串行任务-2-1");
//        childTask21.setCreateTime(LocalDateTime.now());
//        childTask21.setCreator(String.valueOf(WebFrameworkUtils.getLoginUserId()));
//        childTask21.setTaskType("TEST_CASE_GENERATION");
//        childTask21.setTaskSort(1);
//        childTask21.setStageId(childStage21.getId());
//        taskService.save(childTask21);
//
//        //------------------------------------------------------------------
////        PipStage childStage22 = new PipStage();
////        childStage22.setStageName("并行阶段-2-2");
////        childStage22.setPipelineId(pipeline.getId());
////        childStage22.setCreateTime(LocalDateTime.now());
////        childStage22.setCreator(String.valueOf(WebFrameworkUtils.getLoginUserId()));
////        childStage22.setStageSort(2);
////        childStage22.setCode(false);
////        childStage22.setParentId(stageReq2.getId());
////        stageService.save(childStage22);
////
////        PipTask childTask22 = new PipTask();
////        childTask22.setCreateTime(LocalDateTime.now());
////        childTask22.setCreator(String.valueOf(WebFrameworkUtils.getLoginUserId()));
////        childTask22.setTaskName("串行任务-2-2");
////        childTask22.setPipelineId(pipeline.getId());
////        childTask22.setTaskType("test");
////        childTask22.setTaskSort(2);
////        childTask22.setStageId(childStage22.getId());
////        taskService.save(childTask22);
//
//        //创建第三个阶段
//        PipStage stageReq3 = new PipStage();
//        stageReq3.setPipelineId(pipeline.getId());
//        stageReq3.setStageName("阶段-3");
//        stageReq3.setCreateTime(LocalDateTime.now());
//        stageReq3.setCreator(String.valueOf(WebFrameworkUtils.getLoginUserId()));
//        stageReq3.setStageSort(3);
//        stageReq3.setParentId("-1");
//        stageReq3.setCode(true);
//        stageService.save(stageReq3);
//
//        PipStage childStage31 = new PipStage();
//        childStage31.setStageName("并行任务-3-1");
//        childStage31.setPipelineId(pipeline.getId());
//        childStage31.setCreateTime(LocalDateTime.now());
//        childStage31.setCreator(String.valueOf(WebFrameworkUtils.getLoginUserId()));
//        childStage31.setStageSort(1);
//        childStage31.setCode(false);
//        childStage31.setParentId(stageReq3.getId());
//        stageService.save(childStage31);
//
//        PipTask childTask31 = new PipTask();
//        childTask31.setCreateTime(LocalDateTime.now());
//        childTask31.setCreator(String.valueOf(WebFrameworkUtils.getLoginUserId()));
//        childTask31.setTaskName("串行任务-3-1");
//        childTask31.setPipelineId(pipeline.getId());
//        childTask31.setTaskType("AFL");
//        childTask31.setTaskSort(1);
//        childTask31.setStageId(childStage31.getId());
//        taskService.save(childTask31);
//
//        //创建第四个阶段
//        //TODO
////        PipStage stageReq4 = new PipStage();
////        stageReq4.setPipelineId(pipeline.getId());
////        stageReq4.setStageName("阶段-4");
////        stageReq4.setCreateTime(LocalDateTime.now());
////        stageReq4.setCreator(String.valueOf(WebFrameworkUtils.getLoginUserId()));
////        stageReq4.setStageSort(4);
////        stageReq4.setParentId("-1");
////        stageReq4.setCode(true);
////        stageService.save(stageReq4);
////
////        PipStage childStage41 = new PipStage();
////        childStage41.setStageName("并行任务-4-1");
////        childStage41.setPipelineId(pipeline.getId());
////        childStage41.setCreateTime(LocalDateTime.now());
////        childStage41.setCreator(String.valueOf(WebFrameworkUtils.getLoginUserId()));
////        childStage41.setStageSort(1);
////        childStage41.setCode(false);
////        childStage41.setParentId(stageReq4.getId());
////        stageService.save(childStage41);
////
////        PipTask childTask41 = new PipTask();
////        childTask41.setCreateTime(LocalDateTime.now());
////        childTask41.setCreator(String.valueOf(WebFrameworkUtils.getLoginUserId()));
////        childTask41.setTaskName("串行任务-4-1");
////        childTask41.setPipelineId(pipeline.getId());
////        childTask41.setTaskType("REPORT");
////        childTask41.setTaskSort(1);
////        childTask41.setStageId(childStage41.getId());
////        taskService.save(childTask41);
//
//        //TODO 创建对应的鉴权关系
//        //TODO 创建对应的消息分发
//        return pipeline.getId();
//    }
//
//    @Override
//    public List<PipelineFindResp> findPipelineList(PipelineQueryReq pipelineQueryReq) {
//        QueryWrapper<PipPipeline> wrapper = new QueryWrapper<>();
//        if (!ObjectUtils.isEmpty(pipelineQueryReq.getId())){
//            wrapper.eq("id",pipelineQueryReq.getId());
//        }
//        if (!ObjectUtils.isEmpty(pipelineQueryReq.getIdList())){
//            wrapper.in("id",pipelineQueryReq.getId());
//        }
//        if (!ObjectUtils.isEmpty(pipelineQueryReq.getName())){
//            wrapper.like("name",pipelineQueryReq.getName());
//        }
//        if (!ObjectUtils.isEmpty(pipelineQueryReq.getCreator())){
//            wrapper.eq("creator",pipelineQueryReq.getCreator());
//        }
//        if (!ObjectUtils.isEmpty(pipelineQueryReq.getCollect())){
//            wrapper.eq("collect",pipelineQueryReq.getCollect());
//        }
//        if (!ObjectUtils.isEmpty(pipelineQueryReq.getGroupId())){
//            wrapper.eq("group_id",pipelineQueryReq.getGroupId());
//        }
////        Page<PipPipeline> page = new Page<>(pipelineQueryReq.getPageNo(), pipelineQueryReq.getPageSize());
////        Page<PipPipeline> pipPipelinePage = pipelineDao.selectPage(page, wrapper);
//
//        List<PipPipeline> pipPipelines = pipelineDao.selectList(wrapper);
//        if (ObjectUtils.isEmpty(pipPipelines)){
//            return new ArrayList<>(0);
//        }
//
//        List<PipelineFindResp> respList = PipelineConverter.INSTANCE.toRespList(pipPipelines);
//
//        //对流水线进行流水线信息赋值
//        respList.forEach(this::setStageAndTask);
//        //对用户姓名进行赋值
//        respList.forEach(this::setUserName);
//        return respList;
//    }
//
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void deletePipeline(PipelineReq req) {
//        if (StringUtils.isEmpty(req.getId())){
//            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"id不能为空");
//        }
//
//        String pipelineId = req.getId();
//
//        if (ObjectUtils.isEmpty(pipelineId)){
//            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"请求参数不能为空");
//        }
//
//        PipPipeline pipeline = pipelineDao.selectById(pipelineId);
//        if (ObjectUtils.isEmpty(pipeline)){
//            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"流水线不存在");
//        }
//        pipelineDao.deleteById(pipelineId);
//
//        //根据流水线id查询节点和配置信息
//        PipStage pipStage = new PipStage();
//        pipStage.setPipelineId(pipelineId);
//        List<PipStage> pipStageList = stageService.getPipStageList(pipStage);
//        if (!CollectionUtils.isEmpty(pipStageList)){
//            List<String> list = pipStageList.stream().map(PipStage::getId).toList();
//            pipStageDao.deleteByIds(list);
//        }
//
//        PipTask pipTask = new PipTask();
//        pipTask.setPipelineId(pipelineId);
//        List<PipTask> task = taskService.getTask(pipTask);
//        if (!CollectionUtils.isEmpty(task)){
//            List<String> list = task.stream().map(PipTask::getId).toList();
//            pipTaskDao.deleteByIds(list);
//        }
//
//        //删除resource表数据
//        if (StringUtils.isNotEmpty(pipeline.getResourceId())){
//            PipResource pipResource = pipResourceDao.selectById(pipeline.getResourceId());
//
//            if (!ObjectUtils.isEmpty(pipResource)){
//                pipResourceDao.deleteById(pipeline.getResourceId());
//            }
//        }
//    }
//
//    @Override
//    public void updatePipeline(PipelineUpdateReq pipeline) {
//        PipPipeline pipPipeline = new PipPipeline();
//        BeanUtils.copyProperties(pipeline,pipPipeline);
//        pipPipeline.setUpdateTime(LocalDateTime.now());
//        pipPipeline.setUpdater(String.valueOf(WebFrameworkUtils.getLoginUserId()));
//        pipelineDao.updateById(pipPipeline);
//    }
//
//    @Override
//    public PipelineFindResp findPipelineById(PipelineQueryReq pipelineQueryReq) {
//        if (StringUtils.isEmpty(pipelineQueryReq.getId())){
//            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"id参数不能为空");
//        }
//        PipPipeline pipeline = pipelineDao.selectById(pipelineQueryReq.getId());
//        if (ObjectUtils.isEmpty(pipeline)){
//            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"数据错误，请联系管理员");
//        }
//        PipelineFindResp resp = PipelineConverter.INSTANCE.toResp(pipeline);
//        setStageAndTask(resp);
//
//        return resp;
//    }

    @Override
    public PageResult<TemplateFindResp> findTemplatePage(TemplateQueryReq query) {

        QueryWrapper<TemplateManager> wrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(query.getId())){
            wrapper.eq("id",query.getId());
        }
        if (!ObjectUtils.isEmpty(query.getIdList())){
            wrapper.in("id",query.getId());
        }
        if (!ObjectUtils.isEmpty(query.getTemplateName())){
            wrapper.like("template_name",query.getTemplateName());
        }
        if (!ObjectUtils.isEmpty(query.getTemplateType())){
            wrapper.eq("template_type",query.getTemplateType());
        }
        if (!ObjectUtils.isEmpty(query.getTemplateCode())){
            wrapper.eq("template_code",query.getTemplateCode());
        }
        if (!ObjectUtils.isEmpty(query.getCreator())){
            wrapper.eq("creator",query.getCreator());
        }

        Page<TemplateManager> templateManagerPage = templateManagerDao.selectPage(new Page<>(query.getPageNo(), query.getPageSize()), wrapper);

        if (ObjectUtils.isEmpty(templateManagerPage)){
            return new PageResult<>();
        }

        List<TemplateFindResp> respList = TemplateConverter.INSTANCE.toRespList(templateManagerPage.getRecords());

        //对流水线模板进行流水线信息赋值
        respList.forEach(this::setStageAndTask);
        respList.forEach(this::setUserName);

        return new PageResult<>(respList,templateManagerPage.getTotal(),templateManagerPage.getCurrent(),templateManagerPage.getSize());
    }

    @Override
    public List<TemplateFindResp> findTemplateList(TemplateQueryReq query) {
        QueryWrapper<TemplateManager> wrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(query.getId())){
            wrapper.eq("id",query.getId());
        }
        if (!ObjectUtils.isEmpty(query.getIdList())){
            wrapper.in("id",query.getId());
        }
        if (!ObjectUtils.isEmpty(query.getTemplateName())){
            wrapper.like("template_name",query.getTemplateName());
        }
        if (!ObjectUtils.isEmpty(query.getTemplateType())){
            wrapper.eq("template_type",query.getTemplateType());
        }
        if (!ObjectUtils.isEmpty(query.getTemplateCode())){
            wrapper.eq("template_code",query.getTemplateCode());
        }
        if (!ObjectUtils.isEmpty(query.getCreator())){
            wrapper.eq("creator",query.getCreator());
        }

        Page<TemplateManager> templateManagerPage = templateManagerDao.selectPage(new Page<>(query.getPageNo(), query.getPageSize()), wrapper);

        if (ObjectUtils.isEmpty(templateManagerPage)){
            return new ArrayList<>();
        }

        List<TemplateFindResp> respList = TemplateConverter.INSTANCE.toRespList(templateManagerPage.getRecords());

        //对流水线模板进行流水线信息赋值
        respList.forEach(this::setStageAndTask);
        respList.forEach(this::setUserName);
        return respList;
    }

    @Override
    public TemplateFindResp findTemplateById(String id) {
        TemplateManager templateManager = templateManagerDao.selectById(id);
        TemplateFindResp resp = TemplateConverter.INSTANCE.toResp(templateManager);
        setStageAndTask(resp);
        setUserName(resp);
        return resp;
    }

    private void setUserName(TemplateFindResp templateFindResp) {
        if (!StringUtils.isEmpty(templateFindResp.getCreator())){
            AdminUserDO user = adminUserService.getUser(Long.valueOf(templateFindResp.getCreator()));
            if (!ObjectUtils.isEmpty(user)){
                templateFindResp.setCreatorName(user.getUsername());
            }
        }

        if (!StringUtils.isEmpty(templateFindResp.getUpdater())){
            AdminUserDO user = adminUserService.getUser(Long.valueOf(templateFindResp.getUpdater()));
            if (!ObjectUtils.isEmpty(user)){
                templateFindResp.setUpdaterName(user.getUsername());
            }
        }
    }





    private void setStageAndTask(TemplateFindResp o) {
        List<TemplateStageResp> list = new ArrayList<>();

        //拼接流水线模板主节点
        List<TemplateStage> stageMainStage = findAllMainStage(o.getId());
        if (!stageMainStage.isEmpty()){
            for (TemplateStage stage : stageMainStage) {
                String stagesId = stage.getId();
                //获取从节点
                List<TemplateStage> allStageStage = findSecondStageAndTask(stagesId);
                List<TemplateStageResp> stageRespList = allStageStage.stream().map(it -> {
//                BeanUtils.copyProperties(it, stageResp);
                    return JSON.parseObject(JSON.toJSONString(it), TemplateStageResp.class);
                }).toList();
                TemplateStageResp stageResp = templateConverter.stageTemplateToResp(stage);
                stageResp.setStageList(stageRespList);
                list.add(stageResp);
            }
            list.sort(Comparator.comparing(TemplateStageResp::getStageSort));
        }

        o.setStageList(list);
    }

    private List<TemplateStage> findSecondStageAndTask(String stagesId) {
        List<TemplateStage> otherStage = findSecondStage(stagesId);
        List<TemplateStage> list = new ArrayList<>();
        List<String> stageIdList = otherStage.stream().map(TemplateStage::getId).toList();
        if (stageIdList.isEmpty()) {
            throw new ServiceException(GlobalErrorCodeConstants.PIPELINE_ERROR.getCode(),"当前阶段下不存在节点");
        }
        Map<String, List<TemplateTask>> stageIdTaskMap = getTaskByStageIdList(stageIdList).stream().collect(Collectors.groupingBy(TemplateTask::getStageId));
        for (TemplateStage stage : otherStage) {
            //获取阶段配置及任务
            String otherId = stage.getId();
            List<TemplateTask> allStageTask = stageIdTaskMap.get(otherId);
            allStageTask.sort(Comparator.comparing(TemplateTask::getTaskSort));
            stage.setTaskValues(allStageTask);
            list.add(stage);
        }
        return list;
    }

    private List<TemplateTask> getTaskByStageIdList(List<String> stageIdList) {
        LambdaQueryWrapper<TemplateTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TemplateTask::getStageId,stageIdList);
        return templateTaskDao.selectList(wrapper);
    }

    private List<TemplateStage> findSecondStage(String stagesId) {
        LambdaQueryWrapper<TemplateStage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateStage::getParentId,stagesId);
        return templateStageDao.selectList(wrapper);
    }

    private List<TemplateStage> findAllMainStage(String id) {
        LambdaQueryWrapper<TemplateStage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateStage::getTemplateId,id);
        wrapper.eq(TemplateStage::getParentId,"-1");
        return templateStageDao.selectList(wrapper);
    }
}
