package org.dromara.app.controller;

import cn.hutool.core.collection.CollectionUtil;
import org.dromara.biz.domain.BizTask;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.wflow.mapper.WflowSysUserMapper;
import org.dromara.wflow.utils.UserUtil;
import org.dromara.wflow.workflow.bean.vo.ProcessHandlerParamsVo;
import org.dromara.wflow.workflow.bean.vo.ProcessProgressVo;
import org.dromara.wflow.workflow.bean.vo.ProcessStartParamsVo;
import org.dromara.wflow.workflow.bean.vo.RuansiMissionTaskVo;
import org.dromara.wflow.workflow.service.ProcessInstanceService;
import org.dromara.wflow.workflow.service.ProcessTaskService;
import org.dromara.wflow.workflow.service.RuansiMissionService;
import org.dromara.wflow.workflow.service.RuansiMissionTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

/**
 * 我的待办列表控制层
 */
@RestController
@RequestMapping("app/wflow/mission")
public class RuansiMissionCenterControllerApp {

    @Autowired
    private RuansiMissionService missionService;

    @Autowired
    private ProcessInstanceService processService;

    @Autowired
    RuansiMissionTaskService ruansiMissionTaskService;

    @Autowired
    private WflowSysUserMapper wflowSysUserMapper;

    @Autowired
    private ProcessTaskService taskService;

    // 默认任务流程ID 对应wlfow-models表的form_id
    // 所有的流程内容存储在act_hi_varinst表
    public static final String default_code = "wf67fdbee6c717f47dcf804ac8";

    /**
     * 我发起的任务列表
     *
     * @param pageSize   每页显示条数
     * @param pageNum    页数
     * @param status     状态
     * @param title      任务标题
     * @param taskType   任务类型
     * @param deptId     机构代码
     * @param startTimes 起止时间数组
     */
    @GetMapping("mySubmitted")
    public TableDataInfo<RuansiMissionTaskVo> getUserSubmittedList(@RequestParam(defaultValue = "20") Integer pageSize,
                                                                   @RequestParam(defaultValue = "1") Integer pageNum,
                                                                   @RequestParam(required = false) String status,
                                                                   @RequestParam(required = false) String title,
                                                                   @RequestParam(required = false) String taskType,
                                                                   @RequestParam(required = false) String deptId,
                                                                   @RequestParam(required = false) String[] startTimes,
                                                                   @RequestParam(required = false) String level) {
        return missionService.getUserSubmittedList(pageSize, pageNum, LoginHelper.getUserId(), default_code,
                startTimes, taskType, title, status, deptId, level);
    }

    /**
     * 保存或者编辑审批流程
     *
     * @param defId  流程定义ID
     * @param params 参数
     * @return 操作结果
     */
    @PostMapping("start/{defId}")
    public R<Void> startTheProcess(@PathVariable String defId,
                                   @RequestBody ProcessStartParamsVo params) {
        Long userId = LoginHelper.getUserId();
        if (StringUtils.isNotBlank(params.getInstanceId())) {
            //编辑
            Boolean aBoolean = missionService.editProcess(params);
            String msg = aBoolean ? "编辑成功" : "编辑失败";
            return R.ok(msg);
        } else {
            String instanceId = processService.startProcess(defId, String.valueOf(userId), params);
            String msg = StringUtils.isNotBlank(instanceId) ? "保存成功" : "保存失败";
            return R.ok(msg);
        }
    }

    /**
     * 我已审批列表
     *
     * @param pageSize      每页显示条数
     * @param pageNum       页数
     * @param status        状态
     * @param title         任务标题
     * @param taskType      任务类型
     * @param startUserName 发起人
     * @param deptId        机构代码
     * @param startTimes    起止时间数组
     * @return
     */
    @GetMapping("idoList")
    public TableDataInfo<RuansiMissionTaskVo> getUserITodoList(@RequestParam(defaultValue = "20") Integer pageSize,
                                                               @RequestParam(defaultValue = "1") Integer pageNum,
                                                               @RequestParam(required = false) String status,
                                                               @RequestParam(required = false) String title,
                                                               @RequestParam(required = false) String taskType,
                                                               @RequestParam(required = false) String startUserName,
                                                               @RequestParam(required = false) String deptId,
                                                               @RequestParam(required = false) String[] startTimes,
                                                               @RequestParam(required = false) String level) {
        // 警号或姓名模糊搜索
        List<Long> userIds = null;
        if (StringUtils.isNotBlank(startUserName)) {
            userIds = wflowSysUserMapper.selectUsersLike(startUserName);
            if (CollectionUtil.isEmpty(userIds)) {
                TableDataInfo<RuansiMissionTaskVo> build = TableDataInfo.build();
                build.setMsg("未找到该发起人，请重新设置搜索条件");
                build.setRows(Collections.emptyList());
                return build;
            }
        }
        return ruansiMissionTaskService.getUserITodoList(pageSize, pageNum, userIds, default_code, startTimes, status, title, taskType, deptId, level);
    }

    /**
     * 待我审批列表
     *
     * @param pageSize
     * @return
     */
    @GetMapping("todoList")
    public TableDataInfo<RuansiMissionTaskVo> getUserTodoList(@RequestParam(defaultValue = "20") Integer pageSize,
                                                              @RequestParam(defaultValue = "1") Integer pageNum,
                                                              @RequestParam(required = false) String status,
                                                              @RequestParam(required = false) String title,
                                                              @RequestParam(required = false) String taskType,
                                                              @RequestParam(required = false) String startUserName,
                                                              @RequestParam(required = false) String deptId,
                                                              @RequestParam(required = false) String[] startTimes,
                                                              @RequestParam(required = false) String level) {
        //警号或姓名模糊搜索
        List<Long> userIds = null;
        if (StringUtils.isNotBlank(startUserName)) {
            userIds = wflowSysUserMapper.selectUsersLike(startUserName);
            if (CollectionUtil.isEmpty(userIds)) {
                TableDataInfo<RuansiMissionTaskVo> build = TableDataInfo.build();
                build.setMsg("未找到该发起人，请重新设置搜索条件");
                build.setRows(Collections.emptyList());
                return build;
            }
        }
        return ruansiMissionTaskService.getUserTodoList2(pageSize, pageNum, userIds, default_code, startTimes, status, title, taskType, deptId, level);
    }

    /**
     * 带我办理列表
     *
     * @param pageSize      每页显示条数
     * @param pageNum       页数
     * @param taskType      任务类型 1案件 2警情 3专项 4其他
     * @param startUserName 发起人
     * @param deptId        发起单位
     * @param title         任务标题
     * @param startTimes    发起时间
     * @param level         任务级别
     */
    @GetMapping("toHandleList")
    public TableDataInfo<BizTask> getToHandleList(@RequestParam(defaultValue = "20") Integer pageSize,
                                                  @RequestParam(defaultValue = "1") Integer pageNum,
                                                  @RequestParam(required = false) String taskType,
                                                  @RequestParam(required = false) String startUserName,
                                                  @RequestParam(required = false) String deptId,
                                                  @RequestParam(required = false) String title,
                                                  @RequestParam(required = false) String[] startTimes,
                                                  @RequestParam(required = false) String level) {
        return ruansiMissionTaskService.getToHandleList(pageSize, pageNum, taskType, startUserName, deptId, title, startTimes, level);
    }

    /**
     * 已办理列表
     *
     * @param pageSize      每页显示条数
     * @param pageNum       页数
     * @param taskType      任务类型 1案件 2警情 3专项 4其他
     * @param startUserName 发起人
     * @param deptId        发起单位
     * @param title         任务标题
     * @param startTimes    起止时间数组
     */
    @GetMapping("alreadyHandledList")
    public TableDataInfo<BizTask> alreadyHandledList(@RequestParam(defaultValue = "20") Integer pageSize,
                                                     @RequestParam(defaultValue = "1") Integer pageNum,
                                                     @RequestParam(required = false) String taskType,
                                                     @RequestParam(required = false) String startUserName,
                                                     @RequestParam(required = false) String deptId,
                                                     @RequestParam(required = false) String title,
                                                     @RequestParam(required = false) String[] startTimes,
                                                     @RequestParam(required = false) String level) {
        return ruansiMissionTaskService.alreadyHandledList(pageSize, pageNum, taskType, startUserName, deptId, title, startTimes, level);
    }

    /**
     * 查询流程表单数据及审批的进度步骤
     *
     * @param instanceId 流程实例ID
     * @return 流程进度及表单详情
     */
    @GetMapping("/{instanceId}")
    public R<BizTask> getProcessFormAndInstanceProgressApp(@PathVariable String instanceId) {
        return R.ok(missionService.getInstanceProgressApp(instanceId));
    }

    /**
     * 查询流程表单数据及审批的进度步骤
     *
     * @param instanceId 流程实例ID
     * @return 流程进度及表单详情
     */
    @GetMapping("/test/{instanceId}")
    public R<ProcessProgressVo> getProcessFormAndInstanceProgress(@PathVariable String instanceId) {
        ProcessProgressVo instanceProgressApp = missionService.getInstanceProgressApp(instanceId, null);
        return R.ok(instanceProgressApp);
    }


    /**
     * 用户处理任务，审批、转交、评论、撤销等操作
     *
     * @param params 操作参数
     * @return 操作结果
     */
    @PostMapping("handler")
    public R<Void> approvalTask(@RequestBody ProcessHandlerParamsVo params) {
        String userId = UserUtil.getLoginUserId();
        taskService.approvalTask(userId, userId, params);
        return R.ok();
    }
}
