package com.microservices.pms.pipeline.service.impl;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.DateUtils;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.core.utils.YamlValidatorUtils;
import com.microservices.common.core.web.page.GenericsTableDataInfo;
import com.microservices.common.httpClient.domain.EntryDto;
import com.microservices.common.httpClient.domain.FileEntryDto;
import com.microservices.common.httpClient.util.GitLinkRequestHelper;
import com.microservices.common.security.utils.SecurityUtils;
import com.microservices.pms.common.service.IPmsCommonService;
import com.microservices.pms.enterprise.domain.PmsEnterprise;
import com.microservices.pms.enterprise.service.IPmsEnterpriseService;
import com.microservices.pms.pipeline.domain.PmsCiPipelineGraphics;
import com.microservices.pms.pipeline.domain.vo.*;
import com.microservices.pms.pipeline.service.IPmsCiPipelineGraphicsService;
import com.microservices.pms.utils.PmsConstants;
import com.microservices.pms.utils.PmsGitLinkRequestUrl;
import com.microservices.pms.utils.YamlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.microservices.pms.pipeline.mapper.PmsCiPipelinesMapper;
import com.microservices.pms.pipeline.domain.PmsCiPipelines;
import com.microservices.pms.pipeline.service.IPmsCiPipelinesService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;

import static com.microservices.common.core.utils.JSONUtils.convertObjectToJSONObject;
import static com.microservices.common.core.utils.PageUtils.startPage;
import static com.microservices.common.core.utils.PageUtils.toPage;
import static com.microservices.common.core.utils.sign.Base64.base64ToDecoderString;
import static com.microservices.common.core.utils.sign.Base64.contentToBase64;
import static com.microservices.pms.utils.PmsConstants.*;

/**
 * 流水线Service业务层处理
 * 
 * @author wanjia
 * @date 2024-03-02
 */
@Service
public class PmsCiPipelinesServiceImpl implements IPmsCiPipelinesService {
    private static final Logger logger = LoggerFactory.getLogger(PmsCiPipelinesServiceImpl.class);

    @Autowired
    private PmsCiPipelinesMapper pmsCiPipelinesMapper;

    @Autowired
    private IPmsEnterpriseService pmsEnterpriseService;

    @Autowired
    private IPmsCommonService pmsCommonService;

    @Autowired
    private GitLinkRequestHelper gitLinkRequestHelper;

    @Autowired
    private IPmsCiPipelineGraphicsService pmsCiPipelineGraphicsService;

    /**
     * 查询流水线
     *
     * @param id 流水线主键
     * @return 流水线
     */
    @Override
    public PmsCiPipelinesDetailVo selectPmsCiPipelinesById(Long id) {
        PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
        if (pmsCiPipelines == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", id);
        }
        PmsCiPipelinesDetailVo pmsCiPipelinesDetailVo = buildPmsCiPipelinesDetailVo(pmsCiPipelines);
        completeFileContent(pmsCiPipelines, pmsCiPipelinesDetailVo);
        return pmsCiPipelinesDetailVo;
    }

    /**
     * 查询流水线列表
     *
     * @param enterpriseIdentifier 企业标识
     * @param pipelineName         流水线名
     * @param pipelineType
     * @return 流水线
     */
    @Override
    public GenericsTableDataInfo<PmsCiPipelinesDetailVo> selectPmsCiPipelinesList(String enterpriseIdentifier, String pipelineName, Integer pipelineType) {
        PmsEnterprise pmsEnterprise = pmsEnterpriseService.selectPmsEnterpriseByIdentifier(enterpriseIdentifier);
        PmsCiPipelines pmsCiPipelines = new PmsCiPipelines();
        pmsCiPipelines.setPipelineName(pipelineName);
        pmsCiPipelines.setPmsEnterpriseId(pmsEnterprise.getId());
        pmsCiPipelines.setPipelineType(pipelineType);
        startPage();
        List<PmsCiPipelines> pipelinesList = pmsCiPipelinesMapper.selectPmsCiPipelinesList(pmsCiPipelines);
        return toPage(pipelinesList, this::buildPmsCiPipelinesDetailVo);
    }

    private PmsCiPipelinesDetailVo buildPmsCiPipelinesDetailVo(PmsCiPipelines pmsCiPipelines) {
        PmsCiPipelinesDetailVo pmsCiPipelinesDetailVo = new PmsCiPipelinesDetailVo();
        BeanUtils.copyProperties(pmsCiPipelines, pmsCiPipelinesDetailVo);
        pmsCiPipelinesDetailVo.setCreator(pmsCommonService.getSimpleSysUserByUsername(pmsCiPipelines.getCreateBy()));
        return pmsCiPipelinesDetailVo;
    }

    /**
     * 新增流水线
     *
     * @param pmsCiPipelinesInputVo 流水线输入
     * @param enterpriseIdentifier  企业标识
     * @return 结果
     */
    @Override
    public JSONObject insertPmsCiPipelines(PmsCiPipelinesInputVo pmsCiPipelinesInputVo, String enterpriseIdentifier) {
        checkPipelineExistence(pmsCiPipelinesInputVo);
        PmsCiPipelines pmsCiPipelines = buildPmsCiPipelines(pmsCiPipelinesInputVo, enterpriseIdentifier);
        pmsCiPipelinesMapper.insertPmsCiPipelines(pmsCiPipelines);
        JSONObject result = new JSONObject();
        result.put("id", pmsCiPipelines.getId());
        return result;
    }

    private void checkPipelineExistence(PmsCiPipelinesInputVo pmsCiPipelinesInputVo) {
        int pmsCiPipelineCount = pmsCiPipelinesMapper.selectCountByPipelineNameAndRepoInfo(
                pmsCiPipelinesInputVo.getPipelineName(),
                pmsCiPipelinesInputVo.getOwner(),
                pmsCiPipelinesInputVo.getRepoIdentifier(),
                pmsCiPipelinesInputVo.getBranch());
        if (pmsCiPipelineCount > 0) {
            throw new ServiceException("该项目流水线已存在(流水线名[%s])", pmsCiPipelinesInputVo.getPipelineName());
        }

    }

    /**
     * 修改流水线
     *
     * @param pmsCiPipelines 流水线
     * @return 结果
     */
    @Override
    public int updatePmsCiPipelines(PmsCiPipelines pmsCiPipelines) {
        PmsCiPipelines pmsCiPipelinesOld = pmsCiPipelinesMapper.selectPmsCiPipelinesById(pmsCiPipelines.getId());
        if (pmsCiPipelinesOld == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", pmsCiPipelines.getId());
        }
        //声明式流水线不允许修改为图形化流水线
        if (PIPELINE_TYPE_CODE.equals(pmsCiPipelinesOld.getPipelineType())) {
            pmsCiPipelines.setPipelineType(PIPELINE_TYPE_CODE);
        }
        pmsCiPipelines.setUpdateTime(DateUtils.getNowDate());
        return pmsCiPipelinesMapper.updatePmsCiPipelines(pmsCiPipelines);
    }

    /**
     * 批量删除流水线
     *
     * @param ids 需要删除的流水线主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deletePmsCiPipelinesByIds(Long[] ids) {
        for (Long id : ids) {
            PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
            if (pmsCiPipelines != null && pmsCiPipelines.getFilePath() != null) {
                FileEntryDto newestFileEntryDto = gitLinkRequestHelper.getFileEntryDto(
                        pmsCiPipelines.getOwner(),
                        pmsCiPipelines.getRepoIdentifier(),
                        pmsCiPipelines.getFilePath(),
                        pmsCiPipelines.getBranch());
                if (newestFileEntryDto != null) {
                    gitLinkRequestHelper.doDelete(
                            PmsGitLinkRequestUrl.DELETE_FILE(
                                    pmsCiPipelines.getOwner(),
                                    pmsCiPipelines.getRepoIdentifier(),
                                    pmsCiPipelines.getFilePath(),
                                    newestFileEntryDto.getEntries().getSha(),
                                    pmsCiPipelines.getBranch()));
                }
            }
        }
        pmsCiPipelineGraphicsService.deletePmsCiPipelineGraphicsByPipelineIds(ids);
        return pmsCiPipelinesMapper.deletePmsCiPipelinesByIds(ids);
    }

    /**
     * 删除流水线信息
     *
     * @param id 流水线主键
     * @return 结果
     */
    @Override
    public int deletePmsCiPipelinesById(Long id) {
        return pmsCiPipelinesMapper.deletePmsCiPipelinesById(id);
    }

    @Override
    public int createOrUpdatePmsCiPipelineFile(PmsCiPipelineFileInputVo pmsCiPipelineFileInputVo) {

        YamlValidatorUtils.validateYaml(pmsCiPipelineFileInputVo.getContent());
        PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(pmsCiPipelineFileInputVo.getId());
        if (pmsCiPipelines == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", pmsCiPipelineFileInputVo.getId());
        }
        String filePath = PIPELINE_FILE_DIRECTORY + pmsCiPipelines.getPipelineName() + PIPELINE_YML_FILE_SUFFIX;
        FileEntryDto updateBeforeFileEntryDto = new FileEntryDto();
        try {
            //获取路径下文件信息
            updateBeforeFileEntryDto = gitLinkRequestHelper.getFileEntryDto(
                    pmsCiPipelines.getOwner(),
                    pmsCiPipelines.getRepoIdentifier(),
                    filePath,
                    pmsCiPipelines.getBranch());
        } catch (ServiceException e) {
            if ("请求失败(你访问的文件不存在)".equals(e.getMessage())) {
                createFileOnGitlinkAndUpdateDatabase(pmsCiPipelineFileInputVo.getContent(), filePath, pmsCiPipelines);
            }
        }
        if (updateBeforeFileEntryDto != null && updateBeforeFileEntryDto.getEntries() != null) {
            //存在流水线文件则更新
            updateFileOnGitlinkAndUpdateDatabase(pmsCiPipelineFileInputVo.getContent(), filePath, pmsCiPipelines, updateBeforeFileEntryDto);
        }
        return 1;
    }

    @Override
    public JSONObject selectPipelineFileList(Long id) {

        PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
        if (pmsCiPipelines == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", id);
        }

        return gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_PIPELINE_FILE_LIST(pmsCiPipelines.getOwner(),
                pmsCiPipelines.getRepoIdentifier()));

    }

    @Override
    public JSONObject selectPipelineRunsList(Long id, PmsCiPipelinePageVo pmsCiPipelinePageVo) {
        PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
        if (pmsCiPipelines == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", id);
        }
        if (pmsCiPipelines.getFileName() != null) {
            JSONObject pmsCiPipelineRunsListQueryParams = new JSONObject();
            convertObjectToJSONObject(pmsCiPipelinePageVo, pmsCiPipelineRunsListQueryParams, null);
            pmsCiPipelineRunsListQueryParams.put("workflow", pmsCiPipelines.getFileName());
            try {
                return gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_PIPELINE_RUNS_LIST(pmsCiPipelines.getOwner(),
                        pmsCiPipelines.getRepoIdentifier(),
                        pmsCiPipelineRunsListQueryParams));
            } catch (URISyntaxException e) {
                logger.error("buildUri error: " + e);
                throw new ServiceException("输入参数转换为url出错");
            }
        }
        return new JSONObject();
    }

    @Override
    public JSONObject getPipelineRunsJob(Long id, String run, String job, PmsCiPipelineLogCursorsVo pmsCiPipelineLogCursorsVo) {
        PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
        if (pmsCiPipelines == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", id);
        }
        return gitLinkRequestHelper.doPost(PmsGitLinkRequestUrl.GET_PIPELINE_RUNS_JOB(pmsCiPipelines.getOwner(),
                        pmsCiPipelines.getRepoIdentifier(),
                        run,
                        job),
                pmsCiPipelineLogCursorsVo);
    }

    @Override
    public JSONObject enablePipeline(Long id) {
        PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
        if (pmsCiPipelines == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", id);
        }
        if (StringUtils.isEmpty(pmsCiPipelines.getFileName())) {
            throw new ServiceException("该项目流水线配置文件不存在(流水线名[%s])", pmsCiPipelines.getPipelineName());
        }
        JSONObject result = gitLinkRequestHelper.doPost(PmsGitLinkRequestUrl.ENABLE_PIPELINE_FILE(
                pmsCiPipelines.getOwner(),
                pmsCiPipelines.getRepoIdentifier(),
                pmsCiPipelines.getFileName()), null);
        pmsCiPipelines.setPipelineStatus(PIPELINE_ENABLE_STATUS);
        pmsCiPipelines.setUpdateTime(DateUtils.getNowDate());
        pmsCiPipelines.setUpdateBy(SecurityUtils.getUsername());
        pmsCiPipelinesMapper.updatePmsCiPipelines(pmsCiPipelines);
        return result;
    }

    @Override
    public JSONObject disablePipeline(Long id) {
        PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
        if (pmsCiPipelines == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", id);
        }
        if (StringUtils.isEmpty(pmsCiPipelines.getFileName())) {
            throw new ServiceException("该项目流水线配置文件不存在(流水线名[%s])", pmsCiPipelines.getPipelineName());
        }
        JSONObject result = gitLinkRequestHelper.doPost(PmsGitLinkRequestUrl.DISABLE_PIPELINE_FILE(
                pmsCiPipelines.getOwner(),
                pmsCiPipelines.getRepoIdentifier(),
                pmsCiPipelines.getFileName()), null);
        pmsCiPipelines.setPipelineStatus(PIPELINE_DISABLE_STATUS);
        pmsCiPipelines.setUpdateTime(DateUtils.getNowDate());
        pmsCiPipelines.setUpdateBy(SecurityUtils.getUsername());
        pmsCiPipelinesMapper.updatePmsCiPipelines(pmsCiPipelines);
        return result;
    }

    @Override
    public JSONObject selectNodes() {
        return gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_NODES());
    }

    @Override
    public JSONObject selectTemplates() {
        return gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_TEMPLATES());
    }

    @Override
    public JSONObject buildPipelineYamlByGraphJson(Long id, PmsCiPipelineBuildYamlInputVo pmsCiPipelineBuildInputVo) {
        PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
        if (pmsCiPipelines == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", id);
        }
        JSONObject requestBody = new JSONObject();
        convertObjectToJSONObject(pmsCiPipelineBuildInputVo, requestBody, null);
        return gitLinkRequestHelper.doPost(PmsGitLinkRequestUrl.BUILD_PIPELINE_YAML(pmsCiPipelines.getOwner(), pmsCiPipelines.getRepoIdentifier()), requestBody);
    }

    @Override
    public JSONObject savePipelineYamlByGraphicJson(Long id, PmsCiPipelineBuildYamlInputVo pmsCiPipelineBuildInputVo) {
        PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
        if (pmsCiPipelines == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", id);
        }
        //保存图形json文件到本地数据库
        saveOrUpdateGraphicJsonToLocal(id, pmsCiPipelineBuildInputVo);
        JSONObject requestBody = new JSONObject();
        pmsCiPipelineBuildInputVo.setBranch(pmsCiPipelines.getBranch());
        convertObjectToJSONObject(pmsCiPipelineBuildInputVo, requestBody, null);
        JSONObject result = gitLinkRequestHelper.doPost(PmsGitLinkRequestUrl.SAVE_PIPELINE_YAML(pmsCiPipelines.getOwner(), pmsCiPipelines.getRepoIdentifier()), requestBody);

        //同时更新流水线配置文件相关数据
        pmsCiPipelines.setFilePath(result.getString("file_name"));
        pmsCiPipelines.setPipelineStatus(PIPELINE_ENABLE_STATUS);
        pmsCiPipelines.setFileName(result.getString("pipeline_name") + PIPELINE_YML_FILE_SUFFIX);
        pmsCiPipelines.setSha(result.getString("sha"));
        pmsCiPipelinesMapper.updatePmsCiPipelines(pmsCiPipelines);
        return result;
    }

    @Override
    public JSONObject savePipelineYamlByGraphicJsonNew(Long id, PmsCiPipelineBuildYamlInputVo pmsCiPipelineBuildInputVo) {
        PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
        if (pmsCiPipelines == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", id);
        }

        try {
            PipelineVo vo = JSON.parseObject(JSON.toJSONString(pmsCiPipelineBuildInputVo), PipelineVo.class);
            List<PipelineVo.PipelineJson.Nodes> nodes = vo.getPipelineJson().getNodes();
            String pipelineName = vo.getPipelineName();
            NodeActionVo actionVo = new NodeActionVo();
            actionVo.buildName(pipelineName);
            nodes.forEach(s -> {
                List<Map<String, Object>> steps = new ArrayList<>();
                actionVo.parse(steps, s);
                actionVo.buildJobs("job", s.getLabel()+String.format("[%s]",s.getId().trim()), steps);
            });
            String yaml = YamlUtil.toYaml(actionVo);
            JSONObject result = new JSONObject();
            result.put("pipeline_yaml", yaml);
            return result;
        } catch (Exception e) {
           logger.error("流水线图形Json解析失败)", e);
           return null;
        }
    }

    @Override
    public JSONObject reRunPipelineRunsJob(Long id, String run, String job) {
        PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
        if (pmsCiPipelines == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", id);
        }
        return gitLinkRequestHelper.doPost(PmsGitLinkRequestUrl.RERUN_PIPELINE_RUNS_JOB(pmsCiPipelines.getOwner(),
                        pmsCiPipelines.getRepoIdentifier(),
                        run,
                        job), null);
    }

    @Override
    public JSONObject runPipelineRunsJob(Long id, String workflow, String ref) {
        PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
        if (pmsCiPipelines == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", id);
        }
        return gitLinkRequestHelper.doPost(PmsGitLinkRequestUrl.RUN_PIPELINE_RUNS_JOB(pmsCiPipelines.getOwner(),
                        pmsCiPipelines.getRepoIdentifier(),
                        workflow,
                        ref), null);
    }

    @Override
    public JSONObject reRunAllJobsInPipelineRun(Long id, String run) {
        PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
        if (pmsCiPipelines == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", id);
        }
        return gitLinkRequestHelper.doPost(PmsGitLinkRequestUrl.RERUN_ALL_JOBS_IN_PIPELINE_RUN(pmsCiPipelines.getOwner(),
                pmsCiPipelines.getRepoIdentifier(),
                run), null);
    }

    @Override
    public void getPipelineRunJobLogs(Long id, String run, String job, HttpServletResponse response) {
        PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
        if (pmsCiPipelines == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", id);
        }
        try {
            gitLinkRequestHelper.doGetResponse(PmsGitLinkRequestUrl.GET_PIPELINE_RUN_JOB_LOGS(pmsCiPipelines.getOwner(),
                    pmsCiPipelines.getRepoIdentifier(),
                    run, job), response);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceException("获取流水线运行日志失败");
        }
    }


    @Override
    public JSONObject getPipelineRunResults(Long id, String run) {
        PmsCiPipelines pmsCiPipelines = pmsCiPipelinesMapper.selectPmsCiPipelinesById(id);
        if (pmsCiPipelines == null) {
            throw new ServiceException("该项目流水线不存在(流水线ID[%s])", id);
        }
        try {
           return gitLinkRequestHelper.doGet(PmsGitLinkRequestUrl.GET_PIPELINE_RUN_RESULTS(pmsCiPipelines.getOwner(),
                    pmsCiPipelines.getRepoIdentifier(),
                    run));
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceException("获取流水线运行结果信息失败");
        }
    }

    private void saveOrUpdateGraphicJsonToLocal(Long id, PmsCiPipelineBuildYamlInputVo pmsCiPipelineBuildInputVo) {
        PmsCiPipelineGraphics existentialPmsCiPipelineGraphics = pmsCiPipelineGraphicsService.selectPmsCiPipelineGraphicsByPmsCiPipelineId(id);
        PmsCiPipelineGraphics pmsCiPipelineGraphics = new PmsCiPipelineGraphics();
        pmsCiPipelineGraphics.setPmsCiPipelineId(id);
        pmsCiPipelineGraphics.setPipelineName(pmsCiPipelineBuildInputVo.getPipelineName());
        pmsCiPipelineGraphics.setPmsCiPipelineGraphicJson(JSON.toJSONString(pmsCiPipelineBuildInputVo.getPipelineJson()));
        if (existentialPmsCiPipelineGraphics == null) {
            pmsCiPipelineGraphics.setCreateBy(SecurityUtils.getUsername());
            pmsCiPipelineGraphicsService.insertPmsCiPipelineGraphics(pmsCiPipelineGraphics);
        } else {
            pmsCiPipelineGraphics.setId(existentialPmsCiPipelineGraphics.getId());
            pmsCiPipelineGraphics.setUpdateBy(SecurityUtils.getUsername());
            pmsCiPipelineGraphicsService.updatePmsCiPipelineGraphics(pmsCiPipelineGraphics);
        }
    }

    private JSONObject openRepoActionModule(String repoOwner, String repoIdentifier) {
        JSONObject updateRepoActionBody = new JSONObject();
        updateRepoActionBody.put("has_actions", true);
        return gitLinkRequestHelper.doPatch(PmsGitLinkRequestUrl.UPDATE_REPO_ACTION_MODULE(repoOwner, repoIdentifier), updateRepoActionBody);
    }

    private void createFileOnGitlinkAndUpdateDatabase(String fileContent, String filePath, PmsCiPipelines pmsCiPipelines) {
        //调用GitLink创建文件接口，创建文件夹以及文件夹下文件
        JSONObject requestBody = new JSONObject();
        requestBody.put("base64_filepath", contentToBase64(filePath));
        requestBody.put("filepath", filePath);
        requestBody.put("branch", pmsCiPipelines.getBranch());
        requestBody.put("content", fileContent);
        requestBody.put("message", "Create " + filePath);
        JSONObject result = gitLinkRequestHelper.doPost(
                PmsGitLinkRequestUrl.CREATE_FILE(pmsCiPipelines.getOwner(), pmsCiPipelines.getRepoIdentifier()),
                requestBody);
        pmsCiPipelines.setFilePath(filePath);
        pmsCiPipelines.setPipelineStatus(PIPELINE_ENABLE_STATUS);
        pmsCiPipelines.setFileName(result.getString("name"));
        pmsCiPipelines.setSha(result.getString("sha"));
        pmsCiPipelines.setUpdateTime(DateUtils.getNowDate());
        pmsCiPipelines.setUpdateBy(SecurityUtils.getUsername());
        pmsCiPipelinesMapper.updatePmsCiPipelines(pmsCiPipelines);
    }

    private void updateFileOnGitlinkAndUpdateDatabase(String fileContent, String filePath, PmsCiPipelines pmsCiPipelines, FileEntryDto updateBeforeFileEntryDto) {
        JSONObject updateFile = new JSONObject();
        updateFile.put("base64_filepath", contentToBase64(filePath));
        updateFile.put("branch", pmsCiPipelines.getBranch());
        updateFile.put("content", base64ToDecoderString(fileContent));
        updateFile.put("message", "Update " + pmsCiPipelines.getFileName());
        updateFile.put("filepath", filePath);
        updateFile.put("sha", updateBeforeFileEntryDto.getEntries().getSha());
        gitLinkRequestHelper.doPut(PmsGitLinkRequestUrl.UPDATE_FILE(pmsCiPipelines.getOwner(), pmsCiPipelines.getRepoIdentifier()), updateFile);
        FileEntryDto updateAfterFileEntryDto = gitLinkRequestHelper.getFileEntryDto(
                pmsCiPipelines.getOwner(),
                pmsCiPipelines.getRepoIdentifier(),
                filePath,
                pmsCiPipelines.getBranch()
        );
        if (updateAfterFileEntryDto != null && updateAfterFileEntryDto.getEntries() != null) {
            EntryDto entryDto = updateAfterFileEntryDto.getEntries();
            pmsCiPipelines.setSha(entryDto.getSha());
            pmsCiPipelines.setUpdateTime(DateUtils.getNowDate());
            pmsCiPipelines.setUpdateBy(SecurityUtils.getUsername());
            pmsCiPipelinesMapper.updatePmsCiPipelines(pmsCiPipelines);
        }
    }

    private void completeFileContent(PmsCiPipelines pmsCiPipelines, PmsCiPipelinesDetailVo pmsCiPipelinesDetailVo) {
        //获取仓库流水线文件内容
        if (pmsCiPipelines.getFilePath() != null) {
            FileEntryDto fileEntryDto = gitLinkRequestHelper.getFileEntryDto(
                    pmsCiPipelines.getOwner(),
                    pmsCiPipelines.getRepoIdentifier(),
                    pmsCiPipelines.getFilePath(),
                    pmsCiPipelines.getBranch()
            );
            if (fileEntryDto != null && fileEntryDto.getEntries() != null) {
                EntryDto entryDto = fileEntryDto.getEntries();
                pmsCiPipelinesDetailVo.setFileContent(entryDto.getContent());
            }
        }
        //获取图形化JSON
        PmsCiPipelineGraphics pmsCiPipelineGraphics = pmsCiPipelineGraphicsService.selectPmsCiPipelineGraphicsByPmsCiPipelineId(pmsCiPipelines.getId());
        if (pmsCiPipelineGraphics != null) {
            pmsCiPipelinesDetailVo.setPipelineGraphicJson(JSONObject.parseObject(pmsCiPipelineGraphics.getPmsCiPipelineGraphicJson()));
        }
        //获取流水线模板JSON
        if (pmsCiPipelines.getPipelineTemplateJson() != null) {
            pmsCiPipelinesDetailVo.setPipelineTemplateJson(JSONObject.parseObject(pmsCiPipelines.getPipelineTemplateJson()));
        }
    }

    private PmsCiPipelines buildPmsCiPipelines(PmsCiPipelinesInputVo pmsCiPipelinesInputVo, String enterpriseIdentifier) {
        PmsEnterprise pmsEnterprise = pmsEnterpriseService.selectPmsEnterpriseByIdentifier(enterpriseIdentifier);
        PmsCiPipelines pmsCiPipelines = new PmsCiPipelines();
        BeanUtils.copyProperties(pmsCiPipelinesInputVo, pmsCiPipelines);
        if (pmsCiPipelinesInputVo.getPipelineTemplateJson() != null) {
            pmsCiPipelines.setPipelineTemplateJson(JSON.toJSONString(pmsCiPipelinesInputVo.getPipelineTemplateJson()));
        }
        pmsCiPipelines.setDeptId(pmsEnterprise.getDeptId());
        pmsCiPipelines.setPmsEnterpriseId(pmsEnterprise.getId());
        Date nowDate = DateUtils.getNowDate();
        pmsCiPipelines.setCreateTime(nowDate);
        pmsCiPipelines.setUpdateTime(nowDate);
        pmsCiPipelines.setCreateBy(SecurityUtils.getUsername());
        return pmsCiPipelines;
    }
}
