package com.qmth.distributed.print.api;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.distributed.print.business.bean.result.EditResult;
import com.qmth.teachcloud.common.bean.dto.MqDto;
import com.qmth.teachcloud.common.bean.params.ArraysParams;
import com.qmth.teachcloud.common.bean.result.TaskListResult;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.entity.TBTask;
import com.qmth.teachcloud.common.enums.MqTagEnum;
import com.qmth.teachcloud.common.enums.TaskResultEnum;
import com.qmth.teachcloud.common.enums.TaskStatusEnum;
import com.qmth.teachcloud.common.enums.TaskTypeEnum;
import com.qmth.teachcloud.common.service.TBTaskService;
import com.qmth.teachcloud.common.util.RedisUtil;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import com.qmth.teachcloud.common.util.ServletUtil;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 导入导出任务表 前端控制器
 * </p>
 *
 * @author wangliang
 * @since 2021-03-19
 */
@Api(tags = "数据管理-任务管理Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + "/${prefix.url.data}")
@Validated
public class TBTaskController {
    private final static Logger log = LoggerFactory.getLogger(TBTaskController.class);

    @Resource
    TBTaskService tbTaskService;

    @Resource
    RedisUtil redisUtil;

    @ApiOperation(value = "任务管理查询接口")
    @RequestMapping(value = "/task/query", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "任务管理列表信息", response = TaskListResult.class)})
    public Result taskQuery(@ApiParam(value = "印刷计划id", required = false) @RequestParam(required = false) String printPlanId,
                            @ApiParam(value = "任务状态", required = false) @RequestParam(required = false) TaskStatusEnum status,
                            @ApiParam(value = "任务类型", required = false) @RequestParam(required = false) TaskTypeEnum type,
                            @ApiParam(value = "任务数据结果", required = false) @RequestParam(required = false) TaskResultEnum result,
                            @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                            @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        IPage<TaskListResult> taskListResultIPage = tbTaskService.query(new Page<>(pageNumber, pageSize), Objects.nonNull(ServletUtil.getRequestHeaderSchoolId()) ? Long.parseLong(ServletUtil.getRequestHeaderSchoolId().toString()) : null, SystemConstant.convertIdToLong(printPlanId), status, type, result);
        if (Objects.nonNull(taskListResultIPage) && Objects.nonNull(taskListResultIPage.getRecords()) && taskListResultIPage.getRecords().size() > 0) {
            List<TaskListResult> taskListResultList = taskListResultIPage.getRecords();
            for (TaskListResult taskListResult : taskListResultList) {
                if (Objects.equals(taskListResult.getStatus(), TaskStatusEnum.FINISH.getTitle()) && Objects.equals(taskListResult.getResult(), TaskResultEnum.ERROR.getTitle())
//                        && taskListResult.getResetCount() >= dictionaryConfig.sysDomain().getAutoCreatePdfResetMaxCount()
                        && Objects.equals(taskListResult.getType(), TaskTypeEnum.CREATE_PDF.getTitle())
                        && Objects.isNull(taskListResult.getErrorMessage())) {
                    taskListResult.setResetCreatePdf(true);
                }
            }
        }
        return ResultUtil.ok(taskListResultIPage);
    }

    @ApiOperation(value = "重新生成pdf")
    @RequestMapping(value = "/task/reset_create_pdf", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "重新生成pdf", response = EditResult.class)})
    public Result resetCreatePdf(@ApiParam(value = "任务id", required = true) @RequestParam String id) throws IOException {
        Long taskId = Long.parseLong(id);
        TBTask tbTask = tbTaskService.getById(taskId);
//        tbTask.setVersion(new AtomicInteger(tbTask.getVersion()).incrementAndGet());
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        Map<String, Object> map = new HashMap<>();
        if (Objects.nonNull(tbTask.getRemark())) {
            JSONArray jsonArray = JSONArray.parseArray(tbTask.getRemark());
            ArraysParams arraysParams = new ArraysParams(jsonArray.toArray(new Long[jsonArray.size()]));
            map.computeIfAbsent("examDetailCourseIds", v -> Arrays.asList(arraysParams.getIds()));
        }
        map.computeIfAbsent(SystemConstant.TASK, v -> tbTask);
        map.computeIfAbsent(SystemConstant.USER, v -> sysUser);
        map.computeIfAbsent(SystemConstant.MANUAL, v -> true);
//        asyncCreatePdfTempleteService.createPdf(map, null);
        MqDto mqDto = new MqDto(MqTagEnum.PDF.getCode(), map, String.valueOf(tbTask.getId()));
        redisUtil.sendMessage(mqDto.getTopic(), mqDto);
        return ResultUtil.ok(new EditResult());
    }

//    @ApiOperation(value = "任务管理_批量删除&清空接口")
//    @RequestMapping(value = "/task/delete", method = RequestMethod.POST)
//    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = EditResult.class)})
//    @Transactional
//    public Result taskDelete(@ApiParam(value = "数组id和选择类型", required = true) @RequestBody ChooseParams chooseParams) {
//        if ((Objects.isNull(chooseParams.getIds()) || chooseParams.getIds().length == 0) && Objects.isNull(chooseParams.getType())) {
//            throw ExceptionResultEnum.PARAMS_ERROR.exception("数据id或选择类型必须选一个");
//        }
//        if (Objects.nonNull(chooseParams.getType())) {
//            QueryWrapper<TBTask> tbTaskQueryWrapper = new QueryWrapper<>();
//            tbTaskQueryWrapper.lambda().eq(TBTask::getStatus, TaskStatusEnum.FINISH);
//            tbTaskService.remove(tbTaskQueryWrapper);
//        } else {
//            tbTaskService.removeByIds(Arrays.asList(chooseParams.getIds()));
//        }
//        return ResultUtil.ok();
//    }
}
