package org.matrix.autotest.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import org.matrix.autotest.utils.PageTools;
import org.matrix.database.entity.ExecutionHistory;
import org.matrix.database.entity.ExecutionRecord;
import org.matrix.database.entity.TestData;
import org.matrix.database.service.IExecutionHistoryService;
import org.matrix.database.service.ITestDataService;
import org.matrix.database.vo.CommonResult;
import org.matrix.database.vo.CommonResultObj;
import org.matrix.database.vo.ExecutionHistoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author hxh
 */
@CrossOrigin
@RestController
@RequestMapping("/executionHistory")
@Api(tags = "对执行历史execution_history的基本操作")
public class ExecutionHistoryController {

    private final IExecutionHistoryService executionHistoryService;

    @Autowired
    ITestDataService testDataService;

    public ExecutionHistoryController(IExecutionHistoryService executionHistoryService) {
        this.executionHistoryService = executionHistoryService;
    }

    @ApiOperation(value = "分页查询执行历史详情",notes = "假如查询测试用例的执行历史，请入参caseId，假如查询测试任务的执行历史，请入参jobId")
    @GetMapping("/executionHistoryDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageSize",value="页码",required=true,paramType="query"),
            @ApiImplicitParam(name="pageNum",value="当前页显示调试",required=true,paramType="query"),
            @ApiImplicitParam(name="uniqueKey",value="执行历史批次号",paramType="query"),
            @ApiImplicitParam(name="jobId",value="测试任务ID",paramType="query"),
            @ApiImplicitParam(name="caseId",value="测试用例ID",paramType="query")
    })
    public  ResponseEntity<CommonResultObj<IPage<ExecutionHistoryVo>>> executionHistoryDetail(
            @RequestParam(defaultValue = "10")  int pageSize,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "-1") Long jobId,
            Long caseId,
            String uniqueKey
    ){
        Page<ExecutionHistory> results = Optional.of(executionHistoryService.page(Page.of(pageNum, pageSize)
                , Wrappers.lambdaQuery(ExecutionHistory.class)
                        .eq(jobId!=null, ExecutionHistory::getJobId, jobId)
                        .eq(caseId!=null, ExecutionHistory::getCaseId, caseId )
                        .eq(StringUtils.hasLength(uniqueKey), ExecutionHistory::getUniqueKey, uniqueKey)
        )).orElse(new Page<>());
        PageTools.pageTool(pageSize, pageNum, results);
        List<ExecutionHistory> records = results.getRecords();
        List<ExecutionHistoryVo> collect = records.stream().map(executionHistory -> {
            ExecutionHistoryVo executionHistoryVo = new ExecutionHistoryVo();
            BeanUtils.copyProperties(executionHistory, executionHistoryVo);
            TestData byId = testDataService.getById(executionHistory.getDataId());
            executionHistoryVo.setDataName(byId.getName());
            return executionHistoryVo;
        }).collect(Collectors.toList());
        Page<ExecutionHistoryVo> resultPage = new Page<>();
        BeanUtils.copyProperties(results, resultPage);
        resultPage.setRecords(collect);
        return resultPage.getRecords().size() != 0
                ? CommonResult.success(resultPage, "查询成功")
                : CommonResult.failed(resultPage, "查询失败或无数据");
    }

    @ApiOperation(value = "分页查询执行历史缩略",notes = "假如查询测试用例的执行历史，请入参caseId，假如查询测试任务的执行历史，请入参jobId")
    @GetMapping("/executionHistory")
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageSize",value="页码",required=true,paramType="query"),
            @ApiImplicitParam(name="pageNum",value="当前页显示调试",required=true,paramType="query"),
            @ApiImplicitParam(name="jobId",value="测试任务ID",paramType="query"),
            @ApiImplicitParam(name="caseId",value="测试用例ID",paramType="query"),
            @ApiImplicitParam(name="uniqueKey",value="执行历史批次号",paramType="query"),
    })
    public  ResponseEntity<CommonResultObj<IPage<ExecutionHistoryVo>>> findExecutionHistory(
                         @RequestParam(defaultValue = "10")  int pageSize,
                         @RequestParam(defaultValue = "1") int pageNum,
                         @RequestParam(defaultValue = "-1") Long jobId,
                         Long caseId,
                         String uniqueKey
    ){
        IPage<ExecutionHistoryVo> page = executionHistoryService.pageExecutionHistoryVoByCaseIdAndJobId(caseId, jobId,uniqueKey, pageNum, pageSize);
        return page.getRecords().size() != 0
                ? CommonResult.success(page, "查询成功")
                : CommonResult.failed(page, "查询失败或无数据");
    }

    @ApiOperation(value = "根据JobId或者caseId 取最近一次执行历史",notes = "假如查询测试用例的执行历史，请入参caseId，假如查询测试任务的执行历史，请入参jobId")
    @GetMapping("/lastExecution")
    @ApiImplicitParams({
            @ApiImplicitParam(name="jobId",value="测试任务ID",paramType="query"),
            @ApiImplicitParam(name="caseId",value="测试用例ID",paramType="query")
    })
    public  ResponseEntity<CommonResultObj<ExecutionHistoryVo>> lastExecution(
            @RequestParam(defaultValue = "-1") Long jobId,
            Long caseId
    ){
        ExecutionHistoryVo result = executionHistoryService.getLastExecutionHistory(caseId, jobId);
        return result!=null
                ? CommonResult.success(result, "查询成功")
                : CommonResult.failed(null, "查询失败或无数据");
    }

}
