package com.microservices.pms.pipeline.controller;

import com.microservices.common.core.web.controller.BaseController;
import com.microservices.common.core.web.domain.AjaxResult;
import com.microservices.common.core.web.page.GenericsTableDataInfo;
import com.microservices.common.log.annotation.Log;
import com.microservices.common.log.enums.BusinessType;
import com.microservices.pms.pipeline.domain.PmsCiPipelines;
import com.microservices.pms.pipeline.domain.vo.*;
import com.microservices.pms.pipeline.service.IPmsCiPipelinesService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.microservices.common.log.annotation.Log;
import com.microservices.common.log.enums.BusinessType;
import com.microservices.pms.pipeline.service.IPmsCiPipelinesService;
import com.microservices.common.core.web.controller.BaseController;
import com.microservices.common.core.web.domain.AjaxResult;

import javax.servlet.http.HttpServletResponse;

/**
 * 流水线Controller
 * 
 * @author wanjia
 * @date 2024-03-02
 */
@RestController
@RequestMapping("/{enterpriseIdentifier}/pipelines")
@Api(tags = "项目管理-流水线相关接口")
public class PmsCiPipelinesController extends BaseController
{
    @Autowired
    private IPmsCiPipelinesService pmsCiPipelinesService;

    /**
     * 查询流水线列表
     */
//    @RequiresPermissions("pms:pipelines:list")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前记录起始索引", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示记录数", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "orderByColumn", value = "排序列（更新时间：updateTime，创建时间：createTime）", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isAsc", value = "排序的方向desc或者asc,默认asc", paramType = "query", dataType = "String")
    })
    @ApiOperation("流水线列表")
    public GenericsTableDataInfo<PmsCiPipelinesDetailVo> list(@ApiParam(name = "enterpriseIdentifier", value = "企业标识") @PathVariable String enterpriseIdentifier,
                                                              @ApiParam("流水线名称搜索") @RequestParam(required = false) String pipelineName,
                                                              @ApiParam("流水线构建类型 1-声明式流水线 2-图形化流水线") @RequestParam(required = false) Integer pipelineType)
    {

        return pmsCiPipelinesService.selectPmsCiPipelinesList(enterpriseIdentifier, pipelineName, pipelineType);
    }

    /**
     * 获取流水线详细信息
     */
//    @RequiresPermissions("pms:pipelines:query")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取流水线详情")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(pmsCiPipelinesService.selectPmsCiPipelinesById(id));
    }

    /**
     * 新增流水线
     */
//    @RequiresPermissions("pms:pipelines:add")
    @Log(title = "流水线", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增流水线")
    public AjaxResult add(@ApiParam(name = "enterpriseIdentifier", value = "企业标识") @PathVariable String enterpriseIdentifier,
                          @RequestBody @Validated PmsCiPipelinesInputVo pmsCiPipelinesInputVo)
    {
        return success(pmsCiPipelinesService.insertPmsCiPipelines(pmsCiPipelinesInputVo, enterpriseIdentifier));
    }

    /**
     * 修改流水线
     */
//    @RequiresPermissions("pms:pipelines:edit")
    @Log(title = "流水线", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("编辑流水线")
    public AjaxResult edit(@RequestBody PmsCiPipelinesUpdateVo pmsCiPipelinesUpdateVo)
    {
        return toAjax(pmsCiPipelinesService.updatePmsCiPipelines(pmsCiPipelinesUpdateVo.toPmsCiPipelines()));
    }

    /**
     * 修改流水线
     */
//    @RequiresPermissions("pms:pipelines:edit")
    @Log(title = "流水线", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/settingFile")
    @ApiOperation("编辑流水线配置文件")
    public AjaxResult editPipelineFile(@ApiParam(name = "enterpriseIdentifier", value = "企业标识") @PathVariable String enterpriseIdentifier,
                                       @RequestBody PmsCiPipelineFileInputVo pmsCiPipelineFileInputVo)
    {
        return toAjax(pmsCiPipelinesService.createOrUpdatePmsCiPipelineFile(pmsCiPipelineFileInputVo));
    }

    /**
     * 删除流水线
     */
//    @RequiresPermissions("pms:pipelines:remove")
    @Log(title = "流水线", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(pmsCiPipelinesService.deletePmsCiPipelinesByIds(ids));
    }

//    /**
//     * 流水线文件列表
//     */
//    @RequiresPermissions("pms:pipelines:list")
//    @GetMapping(value = "/{id}/actions")
//    @ApiOperation("流水线文件列表")
//    public AjaxResult getPipelineFileList(@ApiParam(name = "id", value = "流水线id")@PathVariable Long id)
//    {
//        return success(pmsCiPipelinesService.selectPipelineFileList(id));
//    }

    /**
     * 流水线执行记录列表
     */
//    @RequiresPermissions("pms:pipelines:list")
    @GetMapping(value = "/{id}/actions/runs")
    @ApiOperation("流水线执行记录列表")
    public AjaxResult getPipelineRunsList(@ApiParam(name = "id", value = "流水线id")@PathVariable Long id, PmsCiPipelinePageVo pmsCiPipelinePageVo)
    {
        return success(pmsCiPipelinesService.selectPipelineRunsList(id, pmsCiPipelinePageVo));
    }

    /**
     * 流水线执行记录任务详情
     */
//    @RequiresPermissions("pms:pipelines:query")
    @PostMapping(value = "/{id}/actions/runs/{run}/jobs/{job}")
    @ApiOperation("流水线执行记录任务详情")
    public AjaxResult getPipelineRunsJob(@ApiParam(name = "id", value = "流水线id")@PathVariable Long id,
                                         @ApiParam(name = "run", value = "执行记录序号")@PathVariable String run,
                                         @ApiParam(name = "job", value = "执行任务序号")@PathVariable String job,
                                         @RequestBody @Validated PmsCiPipelineLogCursorsVo pmsCiPipelineLogCursorsVo)
    {
        return success(pmsCiPipelinesService.getPipelineRunsJob(id, run, job, pmsCiPipelineLogCursorsVo));
    }

    /**
     * 启用流水线
     */
//    @RequiresPermissions("pms:pipelines:edit")
    @Log(title = "流水线", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/{id}/actions/enable")
    @ApiOperation("启用流水线")
    public AjaxResult enablePipeline(@ApiParam(name = "id", value = "流水线id")@PathVariable Long id)
    {
        return success(pmsCiPipelinesService.enablePipeline(id));
    }

    /**
     * 禁用流水线
     */
//    @RequiresPermissions("pms:pipelines:edit")
    @Log(title = "流水线", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/{id}/actions/disable")
    @ApiOperation("禁用流水线")
    public AjaxResult disablePipeline(@ApiParam(name = "id", value = "流水线id")@PathVariable Long id)
    {
        return success(pmsCiPipelinesService.disablePipeline(id));
    }

    @GetMapping(value = "/actions/nodes")
    @ApiOperation("节点列表")
    public AjaxResult getActionNodes()
    {
        return success(pmsCiPipelinesService.selectNodes());
    }

    @GetMapping(value = "/actions/templates")
    @ApiOperation("流水线模版列表")
    public AjaxResult getActionTemplates()
    {
        return success(pmsCiPipelinesService.selectTemplates());
    }

    @PostMapping(value = "/{id}/graphJsonToYaml")
    @ApiOperation("流水线图形json构建声明式yaml")
    public AjaxResult buildPipelineYaml(@ApiParam(name = "id", value = "流水线id")@PathVariable Long id,
                                        @RequestBody @Validated PmsCiPipelineBuildYamlInputVo pmsCiPipelineBuildInputVo)
    {
        return success(pmsCiPipelinesService.buildPipelineYamlByGraphJson(id, pmsCiPipelineBuildInputVo));
    }

    @PostMapping(value = "/{id}/savePipelineYaml")
    @ApiOperation("流水线图形构建声明式yaml并保存")
    public AjaxResult savePipelineYaml(@ApiParam(name = "id", value = "流水线id")@PathVariable Long id,
                                        @RequestBody @Validated PmsCiPipelineBuildYamlInputVo pmsCiPipelineBuildInputVo)
    {
        return success(pmsCiPipelinesService.savePipelineYamlByGraphicJson(id, pmsCiPipelineBuildInputVo));
    }

    /**
     * 启动流水线执行记录任务
     */
    @PostMapping(value = "/{id}/actions/runs/run")
    @ApiOperation("启动流水线执行记录任务")
    public AjaxResult runPipelineRunsJob(@ApiParam(name = "id", value = "流水线id") @PathVariable Long id,
                                         @ApiParam(name = "workflow", value = "流水线文件名称", required = true) @RequestParam String workflow,
                                         @ApiParam(name = "ref", value = "分支名称", required = true) @RequestParam String ref)
    {
        return success(pmsCiPipelinesService.runPipelineRunsJob(id, workflow, ref));
    }

    /**
     * 重启流水线执行记录任务
     */
    @PostMapping(value = "/{id}/actions/runs/{run}/jobs/{job}/rerun")
    @ApiOperation("重启流水线执行记录任务")
    public AjaxResult reRunPipelineRunsJob(@ApiParam(name = "id", value = "流水线id")@PathVariable Long id,
                                           @ApiParam(name = "run", value = "执行记录序号")@PathVariable String run,
                                           @ApiParam(name = "job", value = "执行任务序号")@PathVariable String job)
    {
        return success(pmsCiPipelinesService.reRunPipelineRunsJob(id, run, job));
    }

    /**
     * 重启所有流水线执行记录任务
     */
    @PostMapping(value = "/{id}/actions/runs/{run}/rerun")
    @ApiOperation("重启所有流水线执行记录任务")
    public AjaxResult reRunAllJobsInPipelineRun(@ApiParam(name = "id", value = "流水线id")@PathVariable Long id,
                                           @ApiParam(name = "run", value = "执行记录序号")@PathVariable String run)
    {
        return success(pmsCiPipelinesService.reRunAllJobsInPipelineRun(id, run));
    }

    /**
     * 流水线执行记录任务日志下载
     */
    @GetMapping(value = "/{id}/actions/runs/{run}/jobs/{job}/logs")
    @ApiOperation("流水线执行记录任务日志下载")
    public void getPipelineRunJobLogs(@ApiParam(name = "id", value = "流水线id") @PathVariable Long id,
                                      @ApiParam(name = "run", value = "执行记录序号") @PathVariable String run,
                                      @ApiParam(name = "job", value = "执行任务序号") @PathVariable String job,
                                      HttpServletResponse response) {
        pmsCiPipelinesService.getPipelineRunJobLogs(id, run, job, response);
    }

}
