package com.yihu.hos.system.controller;

import com.yihu.hos.system.service.ProcessManager;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@RequestMapping("/process")
@Controller
public class ProcessController  extends BaseController {

    @Autowired
    private ProcessManager processManager;
    /**
     *  流程管理界面
     *
     * @param model
     * @return
     */
    @RequestMapping("/initial")
    public String processInitial(Model model, Integer flowId) {
        model.addAttribute("flowId", flowId);
        model.addAttribute("contentPage", "system/process/process");
        return "partView";
    }

    @RequestMapping(value = "/getAllEndpoints", method = RequestMethod.GET)
    @ResponseBody
    public Result getAllEndpoints(String endpointName) {
        try {
            return processManager.getAllEndpoints(endpointName);
        } catch (Exception e) {
            return Result.error("查找端点失败");
        }
    }

    @RequestMapping(value = "/getAllProcessors", method = RequestMethod.GET)
    @ResponseBody
    public Result getAllProcessor(String processorName) {
        try {
            return processManager.getAllProcessor(processorName);
        } catch (Exception e) {
            return Result.error("查找所有转换器失败");
        }
    }

    @RequestMapping(value = "/chart", method = RequestMethod.GET)
    @ResponseBody
    public Result getFlowchart(Integer flowId) {
        try {
            if (flowId != null) {
                String flowchart = processManager.getFlowchart(flowId);
                return Result.success(flowchart);
            } else {
                return Result.success("无初始化数据");
            }
        } catch (Exception e) {
            return Result.error("生成业务流程失败");
        }
    }

    @RequestMapping(value = "/json", method = RequestMethod.POST)
    @ResponseBody
    public Result formatJson(String code, String name, String positionJson, String flowJson) {
        try {
            Integer flowId = processManager.generateFlow(code, name, flowJson);
            if (flowId == null) {
                return Result.error("生成业务流程失败,请确认流程图是否编辑错误");
            }
            processManager.saveProcess(code, name, flowId, positionJson, flowJson);

            return Result.success("生成业务流程成功");
        } catch (Exception e) {
            return Result.error("生成业务流程失败");
        }
    }
}
