package com.yunzhupaas.flowable.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.vo.PaginationVO;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.flowable.entity.TemplateEntity;
import com.yunzhupaas.flowable.entity.TemplateJsonEntity;
import com.yunzhupaas.flowable.entity.TriggerTaskEntity;
import com.yunzhupaas.flowable.model.monitor.MonitorModel;
import com.yunzhupaas.flowable.model.trigger.TriggerInfoListModel;
import com.yunzhupaas.flowable.model.trigger.TriggerPagination;
import com.yunzhupaas.flowable.model.trigger.TriggerTaskModel;
import com.yunzhupaas.flowable.service.TemplateJsonService;
import com.yunzhupaas.flowable.service.TemplateService;
import com.yunzhupaas.flowable.service.TriggerTaskService;
import com.yunzhupaas.flowable.util.TriggerUtil;
import com.yunzhupaas.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 任务流程
 *
 * @author YUNZHUPAASYUNZHUPAAS开发组
 * @version 5.0.x
 * @since 2024/9/21 9:57
 */
@Tag(name = "任务流程实例", description = "triggerTask")
@RestController
@RequestMapping("/api/workflow/trigger/task")
@Slf4j
public class TriggerTaskController {
    @Autowired
    private TriggerTaskService triggerTaskService;
    @Autowired
    private TriggerUtil triggerUtil;
    @Autowired
    private TemplateJsonService templateJsonService;
    @Autowired
    private TemplateService templateService;

    /**
     * 获取任务下的触发记录
     *
     * @param taskId 任务主键
     */
    @Operation(summary = "获取任务下的触发记录")
    @GetMapping("/List")
    public ActionResult list(@RequestParam("taskId") String taskId, @RequestParam("nodeCode") String nodeCode) {
        List<TriggerInfoListModel> list = triggerTaskService.getListByTaskId(taskId, nodeCode);
        return ActionResult.success(list);
    }

    /**
     * 任务流程列表
     *
     * @param pagination 分页参数
     */
    @Operation(summary = "任务流程列表")
    @GetMapping
    public ActionResult list(TriggerPagination pagination) {
        List<TriggerTaskEntity> list = triggerTaskService.getList(pagination);

        List<String> flowIds = list.stream().map(TriggerTaskEntity::getFlowId).collect(Collectors.toList());
        List<TemplateJsonEntity> versionList = new ArrayList<>();
        List<TemplateEntity> templateList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(flowIds)) {
            versionList = templateJsonService.listByIds(flowIds);
            List<String> templateIds = versionList.stream().map(TemplateJsonEntity::getTemplateId)
                    .collect(Collectors.toList());
            templateList = templateService.listByIds(templateIds);
        }
        List<TriggerTaskModel> voList = JsonUtil.getJsonToList(list, TriggerTaskModel.class);
        for (TriggerTaskModel model : voList) {
            model.setIsRetry(ObjectUtil.equals(model.getParentId(), "0") ? 0 : 1);
            TemplateJsonEntity version = versionList.stream()
                    .filter(e -> ObjectUtil.equals(model.getFlowId(), e.getId())).findFirst().orElse(null);
            if (null != version) {
                TemplateEntity template = templateList.stream()
                        .filter(e -> ObjectUtil.equals(version.getTemplateId(), e.getId())).findFirst().orElse(null);
                if (null != template) {
                    model.setTemplateStatus(template.getStatus());
                }
            }
        }
        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(voList, paginationVO);
    }

    /**
     * 重试
     *
     * @param id 主键
     */
    @Operation(summary = "重试")
    @PostMapping("/Retry/{id}")
    @SaCheckPermission(value = { "workFlow.flowMonitor" })
    public ActionResult retry(@PathVariable("id") String id) throws Exception {
        try {
            triggerTaskService.retry(id);
        } catch (Exception e) {
            // triggerUtil.createErrorRecord();
            throw e;
        }
        return ActionResult.success(MsgCode.SU005.get());
    }

    /**
     * 批量删除
     *
     * @param model 参数
     */
    @Operation(summary = "批量删除")
    @DeleteMapping
    @SaCheckPermission(value = { "workFlow.flowMonitor" })
    public ActionResult delete(@RequestBody MonitorModel model) {
        triggerTaskService.batchDelete(model.getIds());
        return ActionResult.success(MsgCode.SU003.get());
    }
}
