/*
 * 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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.northking.cctp.common.http.ResultWrapper;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
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.constants.PlanConstant;
import net.northking.cctp.executePlan.dto.planBatch.BatchRetryDto;
import net.northking.cctp.executePlan.dto.planInfo.AtuPlanInfoDetailDto;
import net.northking.cctp.executePlan.dto.planInfo.AtuPlanRunDto;
import net.northking.cctp.executePlan.dto.planTask.AtuPlanTaskDetailDto;
import net.northking.cctp.executePlan.dto.planTask.AtuTaskSendBugDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 执行计划表 => Restful 类型 HTTP/HTTPS 接口
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */
@Api(tags = "执行计划表")
@RequestMapping("/v1/execPlan")
@RestController
public class AtuPlanInfoRestfulCtrl {
    /**
     * 日志
     */
    private final static Logger logger = LoggerFactory.getLogger(AtuPlanInfoRestfulCtrl.class);

    @Autowired
    private AtuPlanInfoApiService planApiService;

    @Autowired
    private AtuPlanBatchApiService batchApiService;

    @Autowired
    private AtuPlanTaskApiService taskApiService;

    @Autowired
    private RedisLockRegistry redisLockRegistry;

    /**
     * Restful接口-get： 获取执行计划表
     *
     * @param planId 主键
     * @return 接口数据传输对象
     */
    @ApiOperation(value = "获取：执行计划表")
    @GetMapping(
            value = "/{planId}",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<AtuPlanInfoDetailDto> findPlanByPK(
            @PathVariable("planId") String planId) {
        logger.info("start findByPK: planId =======> " + planId);

        ResultWrapper<AtuPlanInfoDetailDto> wrapper = new ResultWrapper<>();
        AtuPlanInfoDetailDto dto = planApiService.findByPK(planId);

        logger.info("end findByPK");

        return wrapper.success(dto);
    }

    /**
     * Restful接口-delete： 删除执行计划表
     *
     * @param planId 主键
     * @return 删除的记录数量
     */
    @RequiredPermissions("ui-deletePlan")
    @ApiOperation(value = "删除：执行计划表")
    @DeleteMapping(
            value = "/{planId}",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<Integer> deletePlanByPK(
            @PathVariable("planId") String planId) {
        logger.info("start deleteByPK: planId =======> " + planId);

        ResultWrapper<Integer> wrapper = new ResultWrapper<>();
        Integer count = planApiService.deleteByPK(planId);

        logger.info("end deleteByPK");

        return wrapper.success(count);
    }

    /**
     * Restful接口-get： 计划设备是否离线
     *
     * @param planId 主键
     * @return 结果
     */
    @ApiOperation(value = "校验计划设备是否离线")
    @GetMapping(
            value = "/checkDeviceOffline",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<Map<String, Object>> checkDeviceOffline(
            @RequestParam("planId") String planId, @RequestParam("batchId") String batchId) {
        logger.info("start checkDeviceOffline: planId => {}, batchId => {}", planId, batchId);

        Map<String, Object> result = planApiService.checkDeviceOffline(planId, batchId);

        logger.info("end checkDeviceOffline");

        return new ResultWrapper<Map<String, Object>>().success(result);
    }

    /**
     * Restful接口-get： 计划执行
     *
     * @param atuPlanRunDto 执行参数
     * @return 结果
     */
    @RequiredPermissions(value = {"ui-execPlan"})
    @ApiOperation(value = "计划立即执行")
    @PostMapping(
            value = "/run",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<Object> run(@Validated @RequestBody AtuPlanRunDto atuPlanRunDto) {
        logger.info("start run: params =======> " + JSONUtil.toJsonStr(atuPlanRunDto));

        atuPlanRunDto.setExecutedBy(NKSecurityContext.getUserId());
        atuPlanRunDto.setTriggerType(PlanConstant.TRIGGER_TYPE_MANUAL);
        planApiService.run(atuPlanRunDto);

        logger.info("end run");

        return new ResultWrapper<>().success();
    }

    /**
     * Restful接口-get： 计划批次停止
     *
     * @param batchId 主键
     * @return 结果
     */
    @RequiredPermissions("ui-stopPlanBatch")
    @ApiOperation(value = "计划立即停止")
    @GetMapping(
            value = "/batch/stop/{batchId}",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<Boolean> stop(
            @PathVariable("batchId") String batchId) {
        logger.info("start stop: batchId =======> " + batchId);

        ResultWrapper<Boolean> wrapper = new ResultWrapper<>();
        Boolean flag = taskApiService.stop(batchId);

        logger.info("end stop");

        return wrapper.success(flag);
    }

    /**
     * Restful接口-get： 获取任务详情
     *
     * @param taskId 主键
     * @return 接口数据传输对象
     */
    @RequiredPermissions("ui-queryPlanTask")
    @ApiOperation(value = "获取：任务详情")
    @GetMapping(
            value = "/task/{taskId}",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<AtuPlanTaskDetailDto> findTaskById(
            @PathVariable("taskId") String taskId) {
        logger.info("start findTaskById: taskId =======> " + taskId);

        ResultWrapper<AtuPlanTaskDetailDto> wrapper = new ResultWrapper<>();
        AtuPlanTaskDetailDto dto = taskApiService.findTaskDetailById(taskId);

        logger.info("end findTaskById");

        return wrapper.success(dto);
    }

    /**
     * 任务重试
     *
     * @param retryDto 任务id集合
     * @return 结果
     */
    @RequiredPermissions("ui-planTaskRetry")
    @ApiOperation(value = "任务重试")
    @PostMapping("/taskRetry")
    public ResultWrapper<Boolean> taskRetry(@Validated @RequestBody BatchRetryDto retryDto) {

        logger.info("start taskRetry: retryDto =======> " + JSONUtil.toJsonStr(retryDto));

        ResultWrapper<Boolean> wrapper = new ResultWrapper<>();
        Boolean result = taskApiService.taskRetry(retryDto);

        logger.info("end taskRetry");

        return wrapper.success(result);
    }

    @ApiOperation(value = "根据任务id查询任务发送缺陷信息")
    @GetMapping("/querySendBugTaskInfo/{taskId}")
    public ResultWrapper<AtuTaskSendBugDto> querySendBugTaskInfo(@PathVariable("taskId") String taskId) {

        logger.info("start querySendBugTaskInfo: taskId =======> {}", taskId);

        ResultWrapper<AtuTaskSendBugDto> wrapper = new ResultWrapper<>();
        AtuTaskSendBugDto result = taskApiService.querySendBugTaskInfo(taskId);

        logger.info("end querySendBugTaskInfo");

        return wrapper.success(result);
    }

}
