/*
* Copyright (c) 京北方信息技术股份有限公司 Corporation 2022 . All rights reserved.
*
*/
package net.northking.cctp.executePlan.api;

import cn.gjing.tools.auth.annotation.RequiredPermissions;
import cn.hutool.json.JSONUtil;
import com.hzbank.testteam.autotest.dependencies.authDependency.constants.AuthDependencyConstants;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.constants.BaseDefineDependencyConstants;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.vo.ResponseVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.northking.cctp.common.db.Pagination;
import net.northking.cctp.common.dto.AdvancedQueryOptions;
import net.northking.cctp.common.http.QueryByPage;
import net.northking.cctp.common.http.ResultWrapper;
import net.northking.cctp.executePlan.api.service.AtuPlanBatchApiService;
import net.northking.cctp.executePlan.api.service.AtuPlanInfoApiService;
import net.northking.cctp.executePlan.api.service.AtuPlanTaskApiService;
import net.northking.cctp.executePlan.db.entity.AtuPlanInfo;
import net.northking.cctp.executePlan.dto.planBatch.AtuBatchTaskPageDto;
import net.northking.cctp.executePlan.dto.planBatch.AtuPlanBatchPageDto;
import net.northking.cctp.executePlan.dto.planBatch.AtuPlanBatchQueryDto;
import net.northking.cctp.executePlan.dto.planBatch.BatchScriptReportDto;
import net.northking.cctp.executePlan.dto.planInfo.*;
import net.northking.cctp.executePlan.dto.planScript.*;
import net.northking.cctp.executePlan.dto.planTask.AtuPlanTaskPageDto;
import net.northking.cctp.executePlan.dto.planTask.AtuPlanTaskQueryDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Api(tags = "执行计划表")
@RequestMapping("/v1")
@RestController
public class AtuPlanInfoQueryCtrl
{
  /**
   * 日志
   */
  private final static Logger logger = LoggerFactory.getLogger(AtuPlanInfoQueryCtrl.class);

  @Autowired
  private AtuPlanInfoApiService planApiService;

  @Autowired
  private AtuPlanBatchApiService batchApiService;

  @Autowired
  private AtuPlanTaskApiService taskApiService;


  /**
   * 分页查询 执行计划表 列表
   *
   * @param queryByPage  查询条件
   * @return 数据列表
   */
  @ApiOperation(value = "分页查询列表：执行计划表")
  @RequiredPermissions("taskPlan")
  @PostMapping(value = "/paging/query/execPlan",
      produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
      consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
  public ResultWrapper<Pagination<AtuPlanInfoDetailDto>> pagingQueryPlan(
      @RequestBody @Validated QueryByPage<AtuPlanInfoQueryDto> queryByPage)
  {
    logger.info("start pagingQueryPlan: params =======> " + JSONUtil.toJsonStr(queryByPage));

    ResultWrapper<Pagination<AtuPlanInfoDetailDto>> wrapper = new ResultWrapper<>();
    Pagination<AtuPlanInfoDetailDto> page = planApiService.pagingQuery(queryByPage);

    logger.info("end pagingQueryPlan");

    return wrapper.success(page);
  }

  /**
   * 分页查询 执行批次表 列表
   *
   * @param queryByPage  查询条件
   * @return 数据列表
   */
  @RequiredPermissions("ui-queryPlanLog")
  @ApiOperation(value = "分页查询列表：执行批次表")
  @PostMapping(value = "/paging/query/execPlan/batch",
          produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
          consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
  public ResultWrapper<Pagination<AtuPlanBatchPageDto>> pagingQueryBatch(
          @RequestBody @Validated QueryByPage<AtuPlanBatchQueryDto> queryByPage)
  {
    logger.info("start pagingQueryBatch: params =======> " + JSONUtil.toJsonStr(queryByPage));

    ResultWrapper<Pagination<AtuPlanBatchPageDto>> wrapper = new ResultWrapper<>();
    Pagination<AtuPlanBatchPageDto> page = batchApiService.pagingQuery(queryByPage);

    logger.info("end pagingQueryBatch");

    return wrapper.success(page);
  }


  /**
   * 分页查询 执行任务表 列表
   *
   * @param queryByPage  查询条件
   * @return 数据列表
   */
  @ApiOperation(value = "分页查询列表：执行任务表")
  @PostMapping(value = "/paging/query/execPlan/task",
          produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
          consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
  public ResultWrapper<Pagination<AtuPlanTaskPageDto>> pagingQueryTask(
          @RequestBody @Validated QueryByPage<AtuPlanTaskQueryDto> queryByPage)
  {
    logger.info("start pagingQueryTask: params =======> " + JSONUtil.toJsonStr(queryByPage));

    ResultWrapper<Pagination<AtuPlanTaskPageDto>> wrapper = new ResultWrapper<>();
    Pagination<AtuPlanTaskPageDto> page = taskApiService.pagingQuery(queryByPage);

    logger.info("end pagingQueryTask");

    return wrapper.success(page);
  }

  @ApiOperation(value = "查询设备关联软件与设备")
  @GetMapping(value = "/query/execPlan/queryAppAndDevice/{planId}")
  public ResultWrapper<AtuPlanInfoAppAndDeviceDto> queryAppAndDevice(@PathVariable("planId") String planId){
    ResultWrapper<AtuPlanInfoAppAndDeviceDto> wrapper = new ResultWrapper<>();
    AtuPlanInfoAppAndDeviceDto dto = this.planApiService.queryPlanAppAndDevice(planId);
    return wrapper.success(dto);
  }

  @ApiOperation(value = "计划启用禁用")
  @PostMapping(value = "/update/execPlan/enable")
  public ResultWrapper<Integer> updatePlanEnable(@RequestParam("planId") String planId,@RequestParam("enable")Boolean enable){
    ResultWrapper<Integer> wrapper = new ResultWrapper<>();
    AtuPlanInfo atuPlanInfo = new AtuPlanInfo();
    atuPlanInfo.setEnabled(enable);
    atuPlanInfo.setId(planId);
    Integer result = this.planApiService.updatePlanEnable(atuPlanInfo);
    return wrapper.success(result);
  }

  @RequiredPermissions("ui-planTaskLive")
  @ApiOperation(value = "查询任务直播或视频")
  @GetMapping(value = "/query/planTask/live/{taskId}")
  public ResultWrapper<List<Map<String,Object>>> queryTaskLive(@PathVariable("taskId") String taskId) {
    ResultWrapper<List<Map<String,Object>>> wrapper = new ResultWrapper<>();
    List<Map<String,Object>> map = this.planApiService.queryTaskLive(taskId);
    return wrapper.success(map);
  }


  @RequiredPermissions("ui-queryPlanBatchReport")
  @ApiOperation(value = "计划批次报告")
  @GetMapping(value = "/query/planBatch/report/{batchId}")
  public ResultWrapper<BatchScriptReportDto> queryPlanBatchReport(@PathVariable String batchId){
    ResultWrapper<BatchScriptReportDto> wrapper = new ResultWrapper<>();
    BatchScriptReportDto result = this.planApiService.queryPlanBatchReport(batchId);
    return wrapper.success(result);
  }

  @ApiOperation("导出：导出执行结果")
  @RequiredPermissions("ui-exportPlanBatchReport")
  @GetMapping("/export/batchExecResult/{batchId}")
  public void exportBatchExecResult(HttpServletResponse response, @PathVariable String batchId) {
    logger.info("start exportBatchExecResult: batchId =======> " + batchId);
    this.planApiService.exportBatchExecResult(response, batchId);
    logger.info("end exportBatchExecResult");
  }

  @RequiredPermissions("ui-reportExport")
  @ApiOperation("导出：导出报告")
  @PostMapping("/export/batchReport")
  public void exportBatchReport(HttpServletResponse response, @RequestBody AtuPlanExportDto exportDto) {
    logger.info("start exportBatchReport: params =======> " + JSONUtil.toJsonStr(exportDto));
    this.planApiService.exportBatchReport(response, exportDto);
    logger.info("end exportBatchReport");
  }

  @ApiOperation(value = "根据批次id查询任务详情")
  @PostMapping(value = "/paging/query/execPlan/batchId",
          produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
          consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
  public ResultWrapper<AtuBatchTaskPageDto> pagingQueryTaskByBatchId(
          @RequestBody @Validated QueryByPage<AtuPlanTaskQueryDto> queryByPage) {
    ResultWrapper<AtuBatchTaskPageDto> wrapper = new ResultWrapper<>();
    AtuBatchTaskPageDto atuBatchTaskPageDto = this.batchApiService.queryPlanByBatch(queryByPage);
    return wrapper.success(atuBatchTaskPageDto);
  }

  @ApiOperation(value = "计划保存脚本")
  @PostMapping(value = "/save/plan/byScript")
  public ResultWrapper<String> selectScriptByPlan(@RequestBody AtuPlanScriptDto dto){
    ResultWrapper<String> wrapper = new ResultWrapper<>();
    String result = planApiService.selectScriptByPlan(dto);
    return wrapper.success(result);
  }


  @RequiredPermissions(value = {"ui-savePlanData","ui-addPlanData"})
  @ApiOperation(value = "保存计划数据")
  @PostMapping(value = "/save/planData")
  public ResultWrapper<String> savePlanData(@RequestBody @Validated AtuPlanInfoAddDto inputDto) {
    ResultWrapper<String> wrapper = new ResultWrapper<>();
    String result = planApiService.savePlanData(inputDto);
    return wrapper.success(result);
  }

  @ApiOperation(value = "查询计划关联的脚本")
  @GetMapping(value = "/page/query/linkMd/{planId}")
  public ResultWrapper<AtuPlanScriptResultDto> queryLinkMd(
        @PathVariable("planId") String planId){
    ResultWrapper<AtuPlanScriptResultDto> wrapper = new ResultWrapper<>();
    AtuPlanScriptResultDto resultDto = planApiService.queryLinkMdPage(planId);
    return wrapper.success(resultDto);
  }

  @ApiOperation(value = "删除计划关联脚本")
  @PostMapping(value = "/delete/script/linkMd")
  @RequiredPermissions(value = {"ui-savePlanData","ui-addPlanData"})
  public ResultWrapper<Integer> deleteMdLink(@RequestBody AtuPlanScriptDeleteDto deleteDto) {
    ResultWrapper<Integer> wrapper = new ResultWrapper<>();
    Integer integer = planApiService.deletePlanScriptLinkMd(deleteDto);
    return wrapper.success(integer);
  }

  @ApiOperation(value = "feign调用:根据计划id查询关联脚本id")
  @GetMapping(value = "/feign/query/scriptList/{planId}")
  public ResultWrapper<List<String>> queryScriptLinkByPlan(@PathVariable("planId") String planId){
    ResultWrapper<List<String>> wrapper = new ResultWrapper<>();
    List<String> result = planApiService.queryPlanScriptList(planId);
    return wrapper.success(result);
  }

  @ApiOperation(value = "设置计划状态")
  @GetMapping(value = "/status/update/{planId}")
  public ResultWrapper<Integer> updatePlanStatus(@PathVariable("planId") String planId){
    ResultWrapper<Integer> wrapper = new ResultWrapper<>();
    Integer result = planApiService.updatePlanStatus(planId);
    return wrapper.success(result);
  }

  @ApiOperation(value = "根据脚本id查询是否有关联")
  @PostMapping(value = "/check/scriptByPlan")
  public Boolean checkScript(@RequestBody List<String> ids){
    return planApiService.checkScript(ids);
  }

  @ApiOperation(value = "分页查询计划内关联的脚本")
  @PostMapping(value = "/page/plan/scriptLink")
  public ResultWrapper<AtuPlanScriptPageDto> queryPlanScriptPage(@RequestBody QueryByPage<AtuPlanScriptQueryDto> queryByPage){
    ResultWrapper<AtuPlanScriptPageDto> wrapper = new ResultWrapper<>();
    AtuPlanScriptPageDto result = planApiService.queryScriptPage(queryByPage);
    return wrapper.success(result);
  }

  @ApiOperation(value = "计划内保存勾选的脚本")
  @PostMapping(value = "/save/plan/scriptList")
  public ResultWrapper<String> savePlanScript(@RequestBody AtuPlanScriptSaveDto dto){
    ResultWrapper<String> wrapper = new ResultWrapper<>();
    String result = planApiService.savePlanScript(dto);
    return wrapper.success(result);
  }

  @ApiOperation(value = "计划分配负责人")
  @PostMapping(value = "/update/plan/principal")
  public ResultWrapper<String> updatePrincipal(@RequestBody AtuPlanPrincipalDto dto){
    ResultWrapper<String> wrapper = new ResultWrapper<>();
    String result = planApiService.updatePrincipal(dto);
    return wrapper.success(result);
  }

  @ApiOperation(value = "根据脚本id查询用例集是否有关联")
  @PostMapping(value = "/check/dataSet")
  public Boolean checkDataSetUsedByScriptIdList(@RequestBody List<String> scriptIdList){
    return planApiService.checkDataSetUsedByScriptIdList(scriptIdList);
  }

  @ApiOperation(value = "分页查询:前置计划列表")
  @PostMapping(value = "/page/query/upFrontPlan")
  public ResultWrapper<Pagination<AtuPlanInfoDetailDto>> pageUpFrontPlan(@RequestBody QueryByPage<AtuPlanInfoPageDto> queryByPage){
    ResultWrapper<Pagination<AtuPlanInfoDetailDto>> wrapper = new ResultWrapper<>();
    Pagination<AtuPlanInfoDetailDto> result = planApiService.pageUpFrontPlan(queryByPage);
    return wrapper.success(result);
  }

    @ApiOperation(value = "获取高级查询相关配置数据:创建人，更新人，责任人")
    @GetMapping(value = "/plan/advancedQueryOptions")
    public ResponseVO<AdvancedQueryOptions> advancedQueryOptions(
            @ApiParam(value = "系统ID", required = true, example = "36602691803153920")
            @RequestHeader(AuthDependencyConstants.REQUEST_HEADER_PROJECT_ID) String projectId) {
      logger.debug("start advancedQueryOptions");
      ResponseVO<AdvancedQueryOptions> responseVO = new ResponseVO<>();
      AdvancedQueryOptions result = planApiService.advancedQueryOptions(projectId);
      responseVO.setCode(BaseDefineDependencyConstants.SYSTEM_RESPONSE_CODE_SUCCESS);
      responseVO.setData(result);
      responseVO.setMessage("获取成功");
      logger.debug("end advancedQueryOptions");
      return responseVO;
    }
}


