package com.bbd.bpm.controller.taskOperate;

import com.bbd.bpm.dto.SysCode;
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.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.List;

/**
 * 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();
        //todo
        try{
            //任务处理人id
            //String userId = UserUtil.getUserFromSession(session).getId();
            taskService.claim(taskId, userId);
            resp.setSuccess(true);
            resp.setMessage("改变任务处理人成功");
        }catch (Exception e){
            Log.error("改变任务处理人失败",e);
            resp.setSuccess(false);
        }

        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 = "任务处理")
    @GetMapping("/completeTask")
    public BpmResponse completeTask(String taskId) {
        BpmResponse resp = new BpmResponse();
        //todo
        taskService.complete(taskId);
        return resp;
    }
}
