package cn.iocoder.yudao.module.bpm.controller.admin.task;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.vo.contract.BpmOAContractRespVO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.vo.invoice.BpmOAInvoiceRespVO;
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task.*;
import cn.iocoder.yudao.module.bpm.dal.dataobject.task.BpmHistoryProcessInstanceDO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.task.BpmTaskExtDO;
import cn.iocoder.yudao.module.bpm.service.oa.BpmOAContractService;
import cn.iocoder.yudao.module.bpm.service.oa.BpmOAInvoiceService;
import cn.iocoder.yudao.module.bpm.service.task.BpmHistoryProcessInstanceService;
import cn.iocoder.yudao.module.bpm.service.task.BpmTaskService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - 流程任务实例")
@RestController
@RequestMapping("/bpm/task")
@Validated
@Slf4j
@DataPermission(enable = false)
public class BpmTaskController {

    @Resource
    private BpmTaskService taskService;

    @Resource
    private AdminUserApi userApi;

    @Resource
    private BpmHistoryProcessInstanceService historyProcessInstanceService;

    @Resource
    private DeptApi deptApi;

    @Resource
    private BpmOAContractService bpmOAContractService;

    @Resource
    private BpmOAInvoiceService bpmOAInvoiceService;

    /**
     * add by yaojun 2024.1.3
     * 流程审核添加了抄送用户（多用户）的功能
     *
     * @param pageReqVO
     * @return
     */
    @GetMapping("cc-page")
    @Operation(summary = "获取 cc 抄送任务分页", description = "在【抄送我的】菜单中，进行调用")
    //@PreAuthorize("@ss.hasPermission('bpm:task:query')")
    //@PreAuthorize("@ss.hasPermission('bpm:process-instance:query')")
    public CommonResult<PageResult<BpmTaskCCPageItemRespVO>> getMyProcessInstancePage(
            @Valid BpmTaskDonePageReqVO pageReqVO) {
        return success(taskService.getCCTaskPage(SecurityFrameworkUtils.getLoginUserId(), pageReqVO));
    }


    @GetMapping("todo-page")
    @Operation(summary = "获取 Todo 待办任务分页")
    @PreAuthorize("@ss.hasPermission('bpm:task:query')")
    public CommonResult<PageResult<BpmTaskTodoPageItemRespVO>> getTodoTaskPage(@Valid BpmTaskTodoPageReqVO pageVO) {
        return success(taskService.getTodoTaskPage(getLoginUserId(), pageVO));
    }

    @GetMapping("get-todo-page")
    @Operation(summary = "获取 Todo 待办任务分页")
    @PreAuthorize("@ss.hasPermission('bpm:task:query')")
    public CommonResult<PageResult<BpmTaskTodoPageRespVO>> getTodoTaskPage1(@Valid BpmTaskTodoPageReqVO pageVO) {
        return success(taskService.getTodoTaskPage1(getLoginUserId(), pageVO));
    }

    @GetMapping("get-todo-dept")
    @Operation(summary = "获取 Todo 待办任务公司列表")
    @PreAuthorize("@ss.hasPermission('bpm:task:query')")
    public CommonResult<List<DeptRespDTO>> getTodoTaskDept(@Valid BpmTaskTodoPageReqVO pageVO) {

        List<Long> deptIds = taskService.getTodoTaskDept(pageVO, getLoginUserId());

        // 获取待审批的部门列表
        List<DeptRespDTO> deptList = deptApi.getDeptList(deptIds).getCheckedData();
        // 获取公司类型的部门信息
        List<DeptRespDTO> companyDeptList = deptApi.getCompanyDept().getCheckedData();

        List<DeptRespDTO> respVO = new ArrayList<>();
        for (DeptRespDTO companyDept : companyDeptList) {
            if (deptList.stream().anyMatch(dept -> dept.getFlag().contains(companyDept.getId().toString()))) {
                respVO.add(companyDept);
            }
        }

        return success(respVO);
    }

    @GetMapping("done-page")
    @Operation(summary = "获取 Done 已办任务分页")
    @PreAuthorize("@ss.hasPermission('bpm:task:query')")
    public CommonResult<PageResult<BpmTaskDonePageRespVO>> getDoneTaskPage(@Valid BpmTaskDonePageReqVO pageVO) {
        return success(taskService.getDoneTaskPage(getLoginUserId(), pageVO));
    }

    @GetMapping("/list-by-process-instance-id")
    @Operation(summary = "获得指定流程实例的任务列表", description = "包括完成的、未完成的")
    @Parameter(name = "processInstanceId", description = "流程实例的编号", required = true)
    @PreAuthorize("@ss.hasPermission('bpm:task:query')")
    public CommonResult<List<BpmTaskRespVO>> getTaskListByProcessInstanceId(
            @RequestParam("processInstanceId") String processInstanceId) {
        return success(taskService.getTaskListByProcessInstanceId(processInstanceId));
    }

    @PutMapping("/approve")
    @Operation(summary = "通过任务")
    @PreAuthorize("@ss.hasPermission('bpm:task:update')")
    public CommonResult<Boolean> approveTask(@Valid @RequestBody BpmTaskApproveReqVO reqVO) {
        taskService.approveTask(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/reject")
    @Operation(summary = "不通过任务")
    @PreAuthorize("@ss.hasPermission('bpm:task:update')")
    public CommonResult<Boolean> rejectTask(@Valid @RequestBody BpmTaskRejectReqVO reqVO) {
        taskService.rejectTask(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/update-assignee")
    @Operation(summary = "更新任务的负责人", description = "用于【流程详情】的【转派】按钮")
    @PreAuthorize("@ss.hasPermission('bpm:task:update')")
    public CommonResult<Boolean> updateTaskAssignee(@Valid @RequestBody BpmTaskUpdateAssigneeReqVO reqVO) {
        taskService.updateTaskAssignee(getLoginUserId(), reqVO);
        return success(true);
    }

    @GetMapping("/return-list")
    @Operation(summary = "获取所有可回退的节点", description = "用于【流程详情】的【回退】按钮")
    @Parameter(name = "taskId", description = "当前任务ID", required = true)
    @PreAuthorize("@ss.hasPermission('bpm:task:update')")
    public CommonResult<List<BpmTaskSimpleRespVO>> getReturnList(@RequestParam("taskId") String taskId) {
        return success(taskService.getReturnTaskList(taskId));
    }

    @PutMapping("/return")
    @Operation(summary = "回退任务", description = "用于【流程详情】的【回退】按钮")
    @PreAuthorize("@ss.hasPermission('bpm:task:update')")
    public CommonResult<Boolean> returnTask(@Valid @RequestBody BpmTaskReturnReqVO reqVO) {
        taskService.returnTask(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/delegate")
    @Operation(summary = "委派任务", description = "用于【流程详情】的【委派】按钮。和向前【加签】有点像，唯一区别是【委托】没有单独创立任务")
    @PreAuthorize("@ss.hasPermission('bpm:task:update')")
    public CommonResult<Boolean> delegateTask(@Valid @RequestBody BpmTaskDelegateReqVO reqVO) {
        taskService.delegateTask(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/create-sign")
    @Operation(summary = "加签", description = "before 前加签，after 后加签")
    @PreAuthorize("@ss.hasPermission('bpm:task:update')")
    public CommonResult<Boolean> createSignTask(@Valid @RequestBody BpmTaskAddSignReqVO reqVO) {
        taskService.createSignTask(getLoginUserId(), reqVO);
        return success(true);
    }

    @DeleteMapping("/delete-sign")
    @Operation(summary = "减签")
    @PreAuthorize("@ss.hasPermission('bpm:task:update')")
    public CommonResult<Boolean> deleteSignTask(@Valid @RequestBody BpmTaskSubSignReqVO reqVO) {
        taskService.deleteSignTask(getLoginUserId(), reqVO);
        return success(true);
    }

    @GetMapping("children-list")
    @Operation(summary = "获取能被减签的任务")
    @Parameter(name = "parentId", description = "父级任务 ID", required = true)
    @PreAuthorize("@ss.hasPermission('bpm:task:update')")
    public CommonResult<List<BpmTaskSubSignRespVO>> getChildrenTaskList(@RequestParam("parentId") String parentId) {
        return success(taskService.getChildrenTaskList(parentId));
    }

    @GetMapping("getCurrentTaskIdByProcessInstanceId")
    @Operation(summary = "根据流程实例ID，获取当前处理的taskId")
    @Parameter(name = "processInstanceId", description = "流程实例 ID", required = true)
    public CommonResult<String> getCurrentTaskIdByProcessInstanceId(@RequestParam("processInstanceId") String processInstanceId) {
        return success(taskService.getCurrentTaskIdByProcessInstanceId(processInstanceId));
    }

    @GetMapping("getAssigneeUserId")
    @Operation(summary = "根据流程实例ID，获取审批人信息")
    @Parameter(name = "processInstanceId", description = "流程实例 ID", required = true)
    @DataPermission(enable = false)
    public CommonResult<List<AdminUserRespDTO>> getAssigneeUserIdByProcessInstanceId(@RequestParam("processInstanceId") String processInstanceId) {

        List<AdminUserRespDTO> userRespDTO = new ArrayList<>();

        List<HistoricTaskInstance> tasks = taskService.getListTasksByProcessInstanceId(processInstanceId);

        // 获取用户信息
        List<String> userIds = tasks.stream().map(HistoricTaskInstance::getAssignee).distinct().collect(Collectors.toList());
        if (CollUtil.isEmpty(userIds)) {
            return success(userRespDTO);
        }
        Map<Long, AdminUserRespDTO> userMap = userApi.getUserMap(userIds.stream().map(Long::parseLong).collect(Collectors.toList()));

        return success(convertList(userIds, id -> userMap.get(Long.valueOf(id))));
    }

    @GetMapping("/get-history-task")
    @Operation(summary = "获得历史审批记录")
    @Parameter(name = "processInstanceId", description = "流程实例编号", required = true, example = "1024")
    public CommonResult<Map<String, List<BpmTaskRespVO>>> getHistoryTask(@RequestParam("processInstanceId") String processInstanceId) {

        BpmHistoryProcessInstanceDO historyProcessInstanceDO = historyProcessInstanceService.getHistoryProcessInstanceDO(processInstanceId);
        if (historyProcessInstanceDO == null) {
            return success(null);
        }

        List<String> historyProcessInstanceIds = historyProcessInstanceDO.getHistoryProcessInstanceIds();

        return success(taskService.getTaskListByProcessInstanceIds(historyProcessInstanceIds));
    }


    @GetMapping("getCurrentToDoProcessInstacePreAndNex-page")
    @Operation(summary = "获取当前待处理流程实例（带查询条件），上一个流程和下一个流程的实例ID")
    public CommonResult<Map<String, String>> getCurrentToDoProcessInstacePreAndNex(@RequestParam("processInstanceId") String processInstanceId, @Valid BpmTaskTodoPageReqVO pageVO) {
        return success(taskService.getCurrentToDoProcessInstacePreAndNex(getLoginUserId(), processInstanceId, pageVO));
    }

    @GetMapping("/get-crm-task")
    @Operation(summary = "获得CRM审批任务")
    @Parameter(name = "processDefinitionId", description = "流程定义编号", required = true, example = "1024")
    @Parameter(name = "isTodo", description = "是否待办", required = true)
    public CommonResult<PageResult<Map<String, Object>>> getCrmTask(BpmCrmTaskPageReqVO pageReqVO) {

        List<Map<String, Object>> respVOs = new ArrayList<>();

        PageResult<BpmTaskExtDO> tasks = taskService.getCrmTask(getLoginUserId(), pageReqVO);
        // 获取流程实例编号
        List<String> processInstanceIds = tasks.getList().stream().map(BpmTaskExtDO::getProcessInstanceId).distinct().collect(Collectors.toList());

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            switch (pageReqVO.getProcessDefinitionId()) {
                case "oa_contract":
                    List<BpmOAContractRespVO> contractRespVOS = bpmOAContractService.getListByProcessInstanceIds(processInstanceIds);
                    respVOs = contractRespVOS.stream()
                            .map(item -> objectMapper.convertValue(item, new TypeReference<Map<String, Object>>(){}))
                            .collect(Collectors.toList());
                    break;
                case "oa_invoice":
                    List<BpmOAInvoiceRespVO> invoiceRespVOS = bpmOAInvoiceService.getListByProcessInstanceIds(processInstanceIds);
                    respVOs = invoiceRespVOS.stream()
                            .map(item -> objectMapper.convertValue(item, new TypeReference<Map<String, Object>>(){}))
                            .collect(Collectors.toList());
                    break;
            }

            return success(new PageResult<>(respVOs, tasks.getTotal()));
        } catch (Exception e) {
            log.error("json parse err,json:{}", processInstanceIds, e);
            return success(null);
        }
    }
}
