package com.ruoyi.web.flowable.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SysRoleEnum;
import com.ruoyi.flowable.domain.dto.FlowTaskDto;
import com.ruoyi.flowable.domain.vo.FlowTaskVo;
import com.ruoyi.flowable.domain.vo.StartTaskVO;
import com.ruoyi.flowable.service.IFlowBusinessKeyService;
import com.ruoyi.flowable.service.IFlowDefinitionService;
import com.ruoyi.flowable.service.IFlowInstanceService;
import com.ruoyi.flowable.service.IFlowTaskService;
import com.ruoyi.system.domain.FlowTaskEntity;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.yanzhu.jh.project.service.ISurProjectAuditinfoService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @version : V1.0
 * @ClassName: FlowTaskController
 * @Description: 工作流任务
 * @Auther: JiangYuQi
 * @Date: 2020/7/7 18:03
 */
@RestController
@RequestMapping("/wechat/flowTask")
public class WcFlowableController extends BaseController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IFlowTaskService flowTaskService;

    @Autowired
    private IFlowDefinitionService flowDefinitionService;

    @Autowired
    private IFlowInstanceService flowInstanceService;

    @Autowired
    private ISurProjectAuditinfoService surProjectAuditinfoService;

    @Autowired
    private IFlowBusinessKeyService flowBusinessKeyService;

    /**
     * 启动流程实例
     * @param startTaskVO
     * @return
     */
    @Log(title = "发起流程", businessType = BusinessType.INSERT)
    @PostMapping("/startProcessInstance")
    public AjaxResult startProcessInstance(@RequestBody StartTaskVO startTaskVO) {
        return flowDefinitionService.startProcessInstanceById(startTaskVO.getProcDefId(), startTaskVO.getUserId(), startTaskVO.getNickName(), startTaskVO.getVariables());
    }

    /**
     * 我的流程实例列表
     * @param username
     * @param category
     * @return
     */
    @GetMapping(value = "/myFlowDefinitionList")
    public AjaxResult myFlowDefinitionList(String username, String category) {
        return AjaxResult.success(flowDefinitionService.myList(username, category, null, 1, 1000));
    }

    /**
     * 查询流程节点
     * @param deployId
     * @return
     */
    @ApiOperation(value = "查询流程节点")
    @GetMapping("/readNotes/{deployId}")
    public AjaxResult readNotes(@ApiParam(value = "流程定义id") @PathVariable(value = "deployId") String deployId) {
        return success(flowDefinitionService.readNodes(deployId));
    }

    /**
     * 取消申请
     * @param flowTaskVo
     * @return
     */
    @ApiOperation(value = "取消申请", response = FlowTaskDto.class)
    @Log(title = "终止流程", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/stopProcess")
    public AjaxResult stopProcess(@RequestBody FlowTaskVo flowTaskVo) {
        return flowTaskService.stopProcess(flowTaskVo);
    }

    /**
     * 撤回流程
     * @param flowTaskVo
     * @return
     */
    @ApiOperation(value = "撤回流程", response = FlowTaskDto.class)
    @Log(title = "撤回流程", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/revokeProcess")
    public AjaxResult revokeProcess(@RequestBody FlowTaskVo flowTaskVo) {
        return flowTaskService.revokeProcess(flowTaskVo);
    }

    /**
     * 审批任务
     * @param flowTaskVo
     * @return
     */
    @ApiOperation(value = "审批任务")
    @Log(title = "审批流程", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/complete")
    public AjaxResult complete(@RequestBody FlowTaskVo flowTaskVo) {
        return flowTaskService.complete(flowTaskVo);
    }

    /**
     * 驳回任务
     * @param flowTaskVo
     * @return
     */
    @ApiOperation(value = "驳回任务")
    @Log(title = "驳回流程", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/reject")
    public AjaxResult taskReject(@RequestBody FlowTaskVo flowTaskVo) {
        flowTaskService.taskReject(flowTaskVo);
        return AjaxResult.success();
    }

    /**
     * 退回任务
     * @param flowTaskVo
     * @return
     */
    @ApiOperation(value = "退回任务")
    @Log(title = "退回流程", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/return")
    public AjaxResult taskReturn(@RequestBody FlowTaskVo flowTaskVo) {
        flowTaskService.taskReturn(flowTaskVo);
        return AjaxResult.success();
    }

    @ApiOperation(value = "删除流程实例")
    @Log(title = "删除流程", businessType = BusinessType.INSERT)
    @DeleteMapping(value = "/delete/{instanceId}")
    public AjaxResult delete(@ApiParam(value = "流程实例ID", required = true) @PathVariable String instanceId,
                             @ApiParam(value = "删除原因") @RequestParam(required = false) String deleteReason) {
        flowInstanceService.delete(instanceId,deleteReason);
        return AjaxResult.success();
    }

    /**
     * 获取所有可回退的节点
     * @param flowTaskVo
     * @return
     */
    @ApiOperation(value = "获取所有可回退的节点")
    @PostMapping(value = "/returnList")
    public AjaxResult findReturnTaskList(@RequestBody FlowTaskVo flowTaskVo) {
        return flowTaskService.findReturnTaskList(flowTaskVo);
    }

    /**
     * 根据流程Id查询操作日志
     * @param procInsId
     * @return
     */
    @GetMapping(value = "/findCommentByProcInsId")
    public AjaxResult findCommentByProcInsId(String procInsId) {
        return success(flowBusinessKeyService.selectCommentByProcInsId(procInsId));
    }

    /**
     * 根据流程Id查询表单数据
     * @param procInsId
     * @return
     */
    @GetMapping(value = "/findFormDatasByProcInsId")
    public AjaxResult findFormDatasByProcInsId(String procInsId) {
        return success(flowBusinessKeyService.selectFormDatasByProcInsId(procInsId));
    }

    /**
     * 根据条件查询我的代办任务
     * @param flowTaskEntity
     * @return
     */
    @PostMapping(value = "/myAwaitFlowTaskList")
    public TableDataInfo myAwaitFlowTaskList(@RequestBody FlowTaskEntity flowTaskEntity) {
        //这里不分页，这里实时查询用户角色
        flowTaskEntity.setRoleIds(sysUserService.selectUserRoles(flowTaskEntity.getNowUserName()));
        String nowDept = flowTaskEntity.getNowDept();
        if(flowTaskEntity.getRoleIds().contains(Convert.toLong(SysRoleEnum.ZGS.getCode()))){
            flowTaskEntity.setNowDept(Convert.toStr(sysDeptService.getZGSDeptId(Convert.toLong(nowDept))));
        }
        return getDataTable(flowBusinessKeyService.selectMyAwaitFlowTask(flowTaskEntity));
    }

    /**
     * 根据条件查询我的代办分组数量统计
     * @param flowTaskEntity
     * @return
     */
    @PostMapping(value = "/findAwaitCountGroupByCategory")
    public AjaxResult findAwaitCountGroupByCategory(@RequestBody FlowTaskEntity flowTaskEntity) {
        //这里不分页，这里实时查询用户角色
        flowTaskEntity.setRoleIds(sysUserService.selectUserRoles(flowTaskEntity.getNowUserName()));
        String nowDept = flowTaskEntity.getNowDept();
        if(flowTaskEntity.getRoleIds().contains(Convert.toLong(SysRoleEnum.ZGS.getCode()))){
            flowTaskEntity.setNowDept(Convert.toStr(sysDeptService.getZGSDeptId(Convert.toLong(nowDept))));
        }
        return success(flowBusinessKeyService.findAwaitCountGroupByCategory(flowTaskEntity));
    }

    /**
     * 根据条件查询我的代办任务数量
     * @param flowTaskEntity
     * @return
     */
    @PostMapping(value = "/myAwaitFlowTaskListCount")
    public AjaxResult myAwaitFlowTaskListCount(@RequestBody FlowTaskEntity flowTaskEntity) {
        //设置缓存
        //String key="wechat_flowTask_myAwaitFlowTaskListCount-nowRole="+flowTaskEntity.getNowRole()+"-nowDept="+flowTaskEntity.getNowDept()+"-nowUserName="+flowTaskEntity.getNowUserName()+"-nowUser="+flowTaskEntity.getNowUser();
        //Object obj=redisCache.getCacheObject(key);
        //if(obj!=null){
        //    return success(obj);
        //}
        //这里不分页，这里实时查询用户角色
        flowTaskEntity.setRoleIds(sysUserService.selectUserRoles(flowTaskEntity.getNowUserName()));
        String nowDept = flowTaskEntity.getNowDept();
        if(flowTaskEntity.getRoleIds().contains(Convert.toLong(SysRoleEnum.ZGS.getCode()))){
            flowTaskEntity.setNowDept(Convert.toStr(sysDeptService.getZGSDeptId(Convert.toLong(nowDept))));
        }
        Map<String, Object> dataMap = surProjectAuditinfoService.findMyTask(flowTaskEntity);
        //redisCache.setCacheObject(key, dataMap, Constants.CAPTCHA_EXPIRATION, TimeUnit.SECONDS);
        return success(dataMap);
    }


    /**
     * 根据条件查询我的已办任务
     * @param flowTaskEntity
     * @return
     */
    @GetMapping(value = "/myFinishedFlowTaskList")
    public TableDataInfo myFinishedFlowTaskList(FlowTaskEntity flowTaskEntity) {
        startPage();
        return getDataTable(flowBusinessKeyService.selectMyFinishedFlowTask(flowTaskEntity));
    }

    /**
     * 根据条件查询所有流任务
     * @param flowTaskEntity
     * @return
     */
    @GetMapping(value = "/allList")
    public TableDataInfo allList(FlowTaskEntity flowTaskEntity) {
        startPage();
        return getDataTable(flowBusinessKeyService.selectAllFlowTaskByParams(flowTaskEntity));
    }

    /**
     * 根据条件统计所有流任务
     * @param flowTaskEntity
     * @return
     */
    @GetMapping(value = "/queryCount")
    public AjaxResult queryCount(FlowTaskEntity flowTaskEntity) {
        return success(flowBusinessKeyService.quueryCount(flowTaskEntity));
    }

}
