package com.zcxk.process.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcxk.model.AjaxMessage;
import com.zcxk.model.Pagination;
import com.zcxk.model.ResultStatus;
import com.zcxk.process.dto.ProcessDefinitionDTO;
import com.zcxk.process.dto.TaskPorcessResult;
import com.zcxk.process.entity.ProcessDefinition;
import com.zcxk.process.service.WorkFlowService;
import com.zcxk.process.utils.Action;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/workflow/process/")
@Api(tags = "工作流管理")
public class WorkFlowController {
    @Autowired
    WorkFlowService workFlowService;

 /*   @GetMapping("/getTaskList")
    @ApiOperation(value = "获取流程节点列表")
    public AjaxMessage<Set<String>> getTaskList(
            @ApiParam(value = "站点ID，0为全部", required = false) @RequestParam(required = false) Integer siteId,
            @ApiParam(value = "场景ID，0为全部场景", required = false) @RequestParam(required = false) Integer channelId,
            @ApiParam(value = "工作流key", required = false) @RequestParam(required = false) String processKey) {
        LoginUser loginUser = UserUtil.getCurrentUser();

        Set<String> taskList = workFlowService.getUserTaskList(siteId, channelId, processKey);
        return new AjaxMessage<Set<String>>(ResultStatus.OK, taskList);
    }*/

    @GetMapping("/deploy")
    @ApiOperation(value = "部署")
    public AjaxMessage deployWorkFlow(
            @ApiParam(value = "流程id", required = true) @RequestParam(required = true) Integer id
    ) {
        workFlowService.deploy(id);
        return new AjaxMessage(ResultStatus.OK);
    }

    @GetMapping("/getPage")
    @ApiOperation(value = "流程查询(分页)")
    public AjaxMessage<Pagination<ProcessDefinitionDTO>> queryProcessDefinition(
            @ApiParam(value = "公司id", required = false) @RequestParam(required = false) Integer companyId,

            @ApiParam(value = "流程名称", required = false) @RequestParam(required = false) String name,
            @ApiParam(value = "页数,非必传，默认第一页", required = false, defaultValue = "1") @RequestParam(required = false, defaultValue = "1") int pageNum,
            @ApiParam(value = "条数，非必传，默认15条", required = false, defaultValue = "15") @RequestParam(required = false, defaultValue = "15") int pageSize
    ) {

        IPage<ProcessDefinitionDTO> iPage = new Page<>(pageNum, pageSize);
        ProcessDefinition processDefinition=new ProcessDefinition();
        processDefinition.setProcessName(name);
        processDefinition.setCompanyOrgId(companyId);
        iPage = workFlowService.selectPage(processDefinition, iPage);
        Pagination<ProcessDefinitionDTO> pages = new Pagination<>(iPage);
        return new AjaxMessage<>(ResultStatus.OK, pages);
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加流程")
   public AjaxMessage add(
            @ApiParam(value = "流程", required = true) @RequestBody(required = true) ProcessDefinition processDefinition
    ) {
        workFlowService.saveProcessDefinition(processDefinition);
        return new AjaxMessage(ResultStatus.OK);
    }


    @PutMapping("/edit")
    @ApiOperation(value = "编辑流程")
    public AjaxMessage edit(
            @ApiParam(value = "流程", required = true) @RequestBody(required = true) ProcessDefinition processDefinition
    ) {
        workFlowService.editProcessDefinition(processDefinition);
        return new AjaxMessage(ResultStatus.OK);
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除流程")
    public AjaxMessage delete(
            @ApiParam(value = "流程id", required = true) @RequestParam(required = true) Integer id
    ) {
        workFlowService.deleteProcessDefinition(id);
        return new AjaxMessage(ResultStatus.OK);
    }

    @GetMapping("/getBpmnContent")
    @ApiOperation(value = "获取流程BPMN内容")
    public AjaxMessage<String> getBpmnContent(
            @ApiParam(value = "流程id", required = true) @RequestParam(required = true) Integer id
    ) {

        String content = workFlowService.getProcessBPMNContent(id);
        return new AjaxMessage<>(ResultStatus.OK, content);
    }


    @PostMapping("/saveBpmnContent")
    @ApiOperation(value = "保存BPMN内容")
    public AjaxMessage saveBpmnContent(
            @ApiParam(value = "流程id", required = true) @RequestParam(required = true) Integer id,
            @ApiParam(value = "BPMN内容", required = true) @RequestParam(required = true) String content,
            @ApiParam(value = "BPMN ICON SVG", required = true) @RequestParam(required = true) String svg) {
        workFlowService.saveBPMNContent(id, content, svg);
        return new AjaxMessage(ResultStatus.OK);
    }
    @GetMapping("/image")
    @ApiOperation(value = "工单流程图片")
    public void image(
            @ApiParam(value = "流程实例id", required = true) @RequestParam(required = true) String processId,
         HttpServletResponse response
    ) throws Exception {
        InputStream inputStream =workFlowService.queryProHighLighted(processId);
        OutputStream out = response.getOutputStream();

        //设置响应头通知浏览器以图片的形式打开
        response.setContentType("image/png");
        //设置响应头控制浏览器不要缓存
        response.setDateHeader("expries", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        //ImageIO.write(imageCode.getImage(), "PNG", out);
        out.write(FileCopyUtils.copyToByteArray(inputStream));
        out.close();
    }
    @PostMapping("/deleteProcess")
    @ApiOperation(value = "终止流程")
    public AjaxMessage saveBpmnContent(
            @ApiParam(value = "流程实例id", required = true) @RequestParam(required = true) Integer processId) {
        workFlowService.deleteProcessDefinition(processId);
        return new AjaxMessage(ResultStatus.OK);
    }
    @GetMapping("/testStartProgress")
    @ApiOperation(value = "开启流程")
    public AjaxMessage testStartProgress( @RequestParam Integer id,@RequestParam String  tid,@RequestParam Integer cid) {
        ProcessDefinition processDefinition=workFlowService.findProcessDefinition(tid,cid,id);

        Map<String, Object> vars=new HashMap<>();
        vars.put("assineeFormUserId","55,66");
        //巡检发送系统消息所需参数
        vars.put("任务类型","mmm");
        vars.put("任务编号","12345678");
        vars.put("templateId",4);
        vars.put("msgType",4);
        //工单发送发送系统消息所需参数
        vars.put("工单类型","ttt");
        vars.put("工单编号","12345678");
        vars.put("templateId",7);
        vars.put("msgType",7);
        String startProcess = workFlowService.startProcess(processDefinition, vars);
        Task task = workFlowService.getProcessRuntimeTask(startProcess).get(0);
        Set<String> taskParticipator = workFlowService.getTaskParticipator(task.getId(), false, null);
        taskParticipator.add(task.getId());
        return new AjaxMessage(ResultStatus.OK,taskParticipator);
    }
    @PostMapping ("/testHandleTask")
    @ApiOperation(value = "流程流转")
    public AjaxMessage testHandleTask( String taskId,Integer actionId) {
        Map<String,Object>args=new HashMap<>();
        Action action=null;
        if(actionId==1){
            action=Action.ACTION_AUDIT;
        }
        else if(actionId==3){
            action=Action.ACTION_REJECT;
            args.put("assineeFormUserId","1891");
        }

        List<TaskPorcessResult> results = workFlowService.handleTask(action, taskId, args, "haowan");
        return new AjaxMessage(ResultStatus.OK,results);
    }
    @PostMapping ("/stopProgress")
    @ApiOperation(value = "流程流转")
    public AjaxMessage stopProgress( String processId) {

        workFlowService.stopProcessInstance(processId);
        return new AjaxMessage(ResultStatus.OK);
    }
}
