package cn.axzo.workflow.server.controller.web.bpmn;

import cn.axzo.workflow.client.feign.bpmn.ProcessVariableApi;
import cn.axzo.workflow.common.model.request.bpmn.RestBpmnProcessVariable;
import cn.axzo.workflow.core.service.BpmnProcessVariableService;
import cn.axzo.workflow.server.common.annotation.ErrorReporter;
import cn.azxo.framework.common.model.CommonResponse;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.Arrays;

import static cn.azxo.framework.common.model.CommonResponse.success;

/**
 * 流程变量相关控制器
 */
@Slf4j
@RequestMapping({"/web/v1/api/process/variable", "/api/process/variable"})
@RestController
@ErrorReporter
@Validated
public class BpmnProcessVariableController implements ProcessVariableApi {

    @Resource
    private BpmnProcessVariableService variableService;


    @Operation(summary = "新增流程变量")
    @GetMapping("/create/{executionId}")
    @Override
    public CommonResponse<Void> createVariable(@PathVariable @NotBlank(message = "流程实例 ID 不能为空") String executionId,
                                               @RequestBody @Validated RestBpmnProcessVariable restVariable) {
        variableService.createVariable(executionId, restVariable);
        return success();
    }

    @Operation(summary = "修改流程变量")
    @GetMapping("/update/{executionId}")
    @Override
    public CommonResponse<Void> updateVariable(@PathVariable @NotBlank(message = "流程实例 ID 不能为空") String executionId,
                                               @RequestBody @Validated RestBpmnProcessVariable restVariable) {
        variableService.updateVariable(executionId, restVariable);
        return success();
    }

    @Operation(summary = "批量删除流程变量")
    @DeleteMapping("/delete/{executionId}")
    @Override
    public CommonResponse<Void> deleteVariables(@PathVariable("executionId") String executionId,
                                                @RequestParam String variableNames,
                                                @RequestParam(value = "scope", required = false) String scope) {
        String[] varsArr = variableNames.split(",");
        variableService.deleteVariables(executionId, Arrays.asList(varsArr), scope);
        return success();
    }
}
