package com.bbd.bpm.controller.taskOperate;

import com.bbd.bpm.dto.SysCode;
import com.bbd.bpm.dto.request.CompleteTaskRequest;
import com.bbd.bpm.dto.request.PendingTaskListRequest;
import com.bbd.bpm.dto.request.QueryStartedPiByUserIdRequest;
import com.bbd.bpm.dto.response.BpmResponse;
import com.bbd.bpm.dto.response.PendingTaskListBean;
import com.bbd.bpm.dto.response.QueryPiByUserIdBean;
import com.bbd.bpm.util.validate.ValidateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by houkang on 2019/2/27.
 */
@RestController
@RequestMapping("/bpm/task")
@Api(tags = {"任务管理"})
public class TaskOperateController {
    private static final Logger Log = LoggerFactory.getLogger(TaskOperateController.class);

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private RuntimeService runtimeService;


    /**
     * taskStatus 1 已完成  2 未完成  3 全部
     * */
    @ApiOperation(value = "查询我发起的流程")
    @PostMapping("/queryStartedPiByUserId")
    public BpmResponse queryStartedPiByUserId(@RequestBody QueryStartedPiByUserIdRequest req) {
        BpmResponse resp = new BpmResponse();
        try{
            //数据校验
            String error = ValidateUtil.check_queryStartedPiByUserId(req);
            if(error!=null){
                Log.error("查询我发起的流程，数据校验失败"+error);
                resp.setCode(SysCode.VALIDATE_ERROR);
                resp.setMessage(error);
                resp.setSuccess(false);
                return resp;
            }
            // QueryPiByUserIdBean
            //任务办理人
            List<HistoricProcessInstance> listPi =   historyService.createHistoricProcessInstanceQuery().involvedUser(req.getUserId()).listPage(req.getPage().getPageNumber(),req.getPage().getPageSize());
            if(listPi!=null && !listPi.isEmpty()){
                List<QueryPiByUserIdBean> datalist = new ArrayList<>();
                for(HistoricProcessInstance hpi:listPi){
                    QueryPiByUserIdBean bean = new QueryPiByUserIdBean();
                    bean.setBusinessKey(hpi.getBusinessKey());
                    bean.setName(hpi.getName());
                    bean.setProcessInstanceId(hpi.getSuperProcessInstanceId());
                    bean.setStartTime(hpi.getStartTime());
                    bean.setEndTime(hpi.getEndTime());
                    if(hpi.getEndTime()!=null){
                        bean.setEnded(true);
                    }
                    if("1".equals(req.getTaskStatus())){
                        if(bean.isEnded()){
                            datalist.add(bean);
                        }
                    } else if("2".equals(req.getTaskStatus())){
                        if(!bean.isEnded()){
                            datalist.add(bean);
                        }
                    }else{
                        datalist.add(bean);
                    }
                }
                resp.setData(datalist);
            }

            resp.setCode(SysCode.SUCCESS_CODE);
            resp.setSuccess(true);
        }catch (Exception e){
            Log.error("查询我发起的流程失败",e);
            resp.setSuccess(false);
            resp.setCode(SysCode.SYS_ERROR);
            resp.setMessage("查询我发起的流程失败"+e.getMessage());
        }
        return resp;
    }





    @ApiOperation(value = "查询待处理任务")
    @GetMapping("/pendingTaskList")
    public BpmResponse pendingTaskList( @RequestBody PendingTaskListRequest req) {
        BpmResponse resp = new BpmResponse();
        try{
            //数据校验
            String error = ValidateUtil.check_pendingTaskList(req);
            if(error!=null){
                Log.error("查询待处理任务，数据校验失败"+error);
                resp.setCode(SysCode.VALIDATE_ERROR);
                resp.setMessage(error);
                resp.setSuccess(false);
                return resp;
            }
            //任务办理人
            List<Task> taskList = taskService.createTaskQuery().taskAssignee(req.getAssignee()).listPage(req.getPage().getPageNumber(),req.getPage().getPageSize());
            if(taskList!=null && taskList.size()>0){
                List<PendingTaskListBean> dataList = new ArrayList<>();
                for(Task task : taskList){
                    ProcessInstance pi =runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
                    PendingTaskListBean bean  = new PendingTaskListBean();
                    bean.setBusinessKey(pi.getBusinessKey());
                    bean.setStartUserId(pi.getStartUserId());
                    bean.setStartTime(pi.getStartTime());
                    bean.setTaskId(task.getId());
                    bean.setProcessInstanceId(task.getProcessInstanceId());
                    dataList.add(bean);
                }
                resp.setData(dataList);
            }
            resp.setSuccess(true);
            resp.setCode(SysCode.SUCCESS_CODE);
            resp.setMessage("查询待处理任务成功");
        }catch (Exception e){
            Log.error("查询待处理任务失败",e);
            resp.setSuccess(false);
            resp.setCode(SysCode.SYS_ERROR);
            resp.setMessage("查询待处理任务失败"+e.getMessage());
        }
        return resp;
    }

    @ApiOperation(value = "改变任务处理人")
    @GetMapping("/appointTaskTo")
    public BpmResponse appointTaskTo(String taskId,String userId) {
        BpmResponse resp = new BpmResponse();

        try{
            //校验参数
            if(StringUtils.isBlank(taskId)||StringUtils.isBlank(userId) ){
                resp.setMessage("请求参数"+SysCode.NOT_ALLOW_NULL);
                resp.setCode(SysCode.VALIDATE_ERROR);
                resp.setSuccess(false);
                return resp;
            }
            Task task=taskService.createTaskQuery().taskId(taskId).singleResult();
            //校验参数
            if(task==null || task.getId()==null){
                resp.setMessage("任务不存在或已完成");
                resp.setCode(SysCode.VALIDATE_ERROR);
                resp.setSuccess(false);
                return resp;
            }
            //任务处理人id
            taskService.delegateTask(taskId, userId);
            resp.setSuccess(true);
            resp.setMessage("改变任务处理人成功");
            resp.setCode(SysCode.SUCCESS_CODE);
        }catch (Exception e){
            Log.error("改变任务处理人失败",e);
            resp.setSuccess(false);
            resp.setMessage("改变任务处理人失败"+e.getMessage());
            resp.setCode(SysCode.SYS_ERROR);
        }
        return resp;
    }

    @ApiOperation(value = "删除任务")
    @GetMapping("/deleteTask")
    public BpmResponse deleteTask(String taskId) {
        BpmResponse resp = new BpmResponse();
        //todo
        try{
            taskService.deleteTask(taskId);
            resp.setSuccess(true);
            resp.setMessage("删除任务成功");
        }catch (Exception e){
            Log.error("删除任务失败",e);
            resp.setSuccess(false);
        }
        return resp;
    }

    @ApiOperation(value = "任务办理")
    @PostMapping("/completeTask")
    public BpmResponse completeTask(@RequestBody CompleteTaskRequest req ) {
        BpmResponse resp = new BpmResponse();
       try{
           //数据校验
           String error = ValidateUtil.check_completeTask(req);
           if(error!=null){
               Log.error("任务办理，数据校验失败"+error);
               resp.setCode(SysCode.VALIDATE_ERROR);
               resp.setMessage(error);
               resp.setSuccess(false);
               return resp;
           }

           Task task=taskService.createTaskQuery().taskId(req.getTaskId()).singleResult();
           //校验参数
           if(task==null || task.getId()==null){
               resp.setMessage("任务不存在或已完成");
               resp.setCode(SysCode.VALIDATE_ERROR);
               resp.setSuccess(false);
               return resp;
           }
           //增加批注
           if(req.getComments()!=null){
               taskService.addComment(req.getTaskId(), null, req.getComments());
           }
           Map<String, Object> variables = null;
           if(req.getVariables()==null){
               variables = new HashMap<String, Object>();
           }else{
               variables = req.getVariables();
           }
           variables.put("userId",task.getAssignee());
           taskService.complete(req.getTaskId(),variables);
           resp.setSuccess(true);
           resp.setMessage("任务办理成功");
           resp.setCode(SysCode.SUCCESS_CODE);
       }catch(Exception e){
           Log.error("任务办理失败",e);
           resp.setSuccess(false);
           resp.setMessage("任务办理失败"+e.getMessage());
           resp.setCode(SysCode.SYS_ERROR);
       }
        return resp;
    }
}
