package com.bbd.bpm.controller.taskHistory;

import com.bbd.bpm.dto.PageUtil;
import com.bbd.bpm.dto.SysCode;
import com.bbd.bpm.dto.request.PendingTaskListRequest;
import com.bbd.bpm.dto.response.ApprovedDetailBean;
import com.bbd.bpm.dto.response.BpmResponse;
import com.bbd.bpm.dto.response.CompletedTaskListBean;
import com.bbd.bpm.dto.response.PendingTaskListBean;
import com.bbd.bpm.util.validate.ValidateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
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.List;

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

    @Autowired
    private HistoryService historyService;
    @Autowired
    private TaskService taskService;

    @ApiOperation(value = "查询流程实例的审批详情")
    @GetMapping("/approvedDetail")
    public BpmResponse approvedDetail(String processInstanceId) {
        BpmResponse resp = new BpmResponse();
        try{
            //校验参数
            if(StringUtils.isBlank(processInstanceId) ){
                resp.setMessage("流程实例id"+SysCode.NOT_ALLOW_NULL);
                resp.setCode(SysCode.VALIDATE_ERROR);
                resp.setSuccess(false);
                return resp;
            }
            //打印审批过程
            List<HistoricActivityInstance> hislist=historyService.createHistoricActivityInstanceQuery()
                    .processInstanceId(processInstanceId)
                    // 查询已经完成的任务
                    //.finished()
                    .list();
            if(hislist != null && !hislist.isEmpty()){
                List<ApprovedDetailBean> datalist = new ArrayList<>();
                for(HistoricActivityInstance hai:hislist){
                    ApprovedDetailBean bean = new ApprovedDetailBean();
                    bean.setActivityName(hai.getActivityName());
                    bean.setAssigneeUserId(hai.getAssignee());
                    bean.setEndTime(hai.getEndTime());
                    bean.setStartTime(hai.getStartTime());
                    List<Comment> comments = taskService.getTaskComments(hai.getTaskId());
                    // 4）如果当前任务有批注信息，添加到集合中
                    if(comments!=null && comments.size()>0){
                        bean.setComments(comments.get(0).getFullMessage());
                    }
                    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 = "查询已办理任务")
    @PostMapping("/completedTaskList")
    public BpmResponse completedTaskList(PendingTaskListRequest req,PageUtil pageUtil) {
        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;
            }
            //任务办理人
            PageHelper.startPage(pageUtil.getPageNumber(),pageUtil.getPageSize());
            List<HistoricTaskInstance>  hisList =  historyService.createHistoricTaskInstanceQuery().taskAssignee(req.getAssignee()).listPage(pageUtil.getPageNumber(),pageUtil.getPageSize());
            if(hisList!=null && hisList.size()>0){
                List<CompletedTaskListBean> dataList = new ArrayList<>();
                for(HistoricTaskInstance hisTask : hisList){
                    HistoricProcessInstance pi =historyService.createHistoricProcessInstanceQuery().processInstanceId(hisTask.getProcessInstanceId()).singleResult();

                    CompletedTaskListBean bean  = new CompletedTaskListBean();
                    //业务密钥
                    bean.setBusinessKey(pi.getBusinessKey());
                    //任务发起人
                    bean.setStartUserId(pi.getStartUserId());
                    //任务开启时间
                    bean.setPiStartTime(pi.getStartTime());
                    //taskId
                    bean.setTaskId(hisTask.getId());
                    //流程实例id
                    bean.setProcessInstanceId(hisTask.getProcessInstanceId());
                    //审批开始时间
                    bean.setTaskEndTime(hisTask.getEndTime());
                    //审批结束时间
                    bean.setTaskStartTime(hisTask.getStartTime());
                    //流程结束时间
                    bean.setPiEndTime(pi.getEndTime());
                    //流程名字
                    bean.setProcessDefinitionName(pi.getProcessDefinitionName());
                    dataList.add(bean);
                }
                PageInfo pageInfo=new PageInfo(dataList);
                resp.setData(pageInfo);
            }
            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;
    }
}
