package com.codvision.workflow.controller;


import com.codvision.commoncore.common.ResponseEntity;
import com.codvision.commoncore.exception.BusinessException;
import com.codvision.workflow.entity.vo.WorkFlowViewerVO;
import com.codvision.workflow.service.WorkFlowInstanceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author hxl
 */
@Slf4j
@Api(tags = "工作流流程实例管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/flowInstance")
public class WorkFlowInstanceController {

    private final WorkFlowInstanceService service;

    @ApiOperation("根据流程定义id启动流程实例")
    @PostMapping("/start/{procDefId}")
    public ResponseEntity<String> start(@PathVariable(value = "procDefId") String procDefId,
                                        @RequestBody Map<String, Object> variables) {
        ResponseEntity<String> responseEntity = new ResponseEntity<>();
        if (StringUtils.isBlank(procDefId)) {
            throw new BusinessException(30002);
        }

        service.startProcessInstanceById(procDefId, variables);
        return responseEntity.ok();
    }

    @ApiOperation("删除流程实例")
    @PostMapping("/del")
    public ResponseEntity<String> del(@RequestBody List<String> instanceIds,
                                      @RequestParam(required = false) String deleteReason) {
        ResponseEntity<String> responseEntity = new ResponseEntity<>();
        if (CollectionUtils.isEmpty(instanceIds)) {
            throw new BusinessException(30002);
        }

        service.del(instanceIds, deleteReason);
        return responseEntity.ok();
    }

    @ApiOperation("流程执行进度")
    @GetMapping("/flowPace")
    public ResponseEntity<WorkFlowViewerVO> flowPace(@RequestParam(value = "instanceId") String instanceId,
                                                     @RequestParam(value = "deployId") String deployId) {
        ResponseEntity<WorkFlowViewerVO> responseEntity = new ResponseEntity<>();
        if (StringUtils.isBlank(instanceId) || StringUtils.isBlank(deployId)) {
            throw new BusinessException(30002);
        }
        return responseEntity.data(service.flowPace(instanceId, deployId));
    }
}
