package com.xdap.self_development.controller;

import com.definesys.mpaas.common.http.Response;
import com.definesys.mpaas.query.db.PageQueryResult;
import com.xdap.self_development.common.BusinessDatabase;
import com.xdap.self_development.controller.form.*;
import com.xdap.self_development.domain.dto.ApprovalNodesDTO;
import com.xdap.self_development.domain.view.ApprovalFlowNodeView;
import com.xdap.self_development.domain.view.DepartmentUserView;
import com.xdap.self_development.domain.view.TemplateChangeView;
import com.xdap.self_development.exception.CommonException;
import com.xdap.self_development.service.TemplateApprovalService;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;

/**
 * 模板审批控制器
 * 提供模板审批相关的功能，包括发起审批、处理审批、查询审批列表、获取审批流程等
 *
 * @version 1.0
 * @since 2025
 */
@RestController
@RequestMapping("/custom/approval")
public class TemplateApprovalController {
    @Resource
    private TemplateApprovalService templateApprovalService;
    @Resource
    private BusinessDatabase bd;

    /**
     * 修改后继续流程
     *
     * @param flowId 流程ID
     * @param userId 用户ID
     * @return 操作结果响应
     */
    @GetMapping("/continueApproval")
    public Response continueApproval(
            @NotBlank @RequestParam String flowId,
            @NotBlank @RequestParam String userId
    ) {
        templateApprovalService.continueApproval(flowId, userId);
        return Response.ok();
    }

    /**
     * 获取可修改节点
     *
     * @param flowId 流程ID
     * @return 可修改节点列表
     */
    @GetMapping("/getEditableNodes")
    public Response getEditableNodes(
            @NotBlank @RequestParam String flowId
    ) {
        List<String> nodes = templateApprovalService.getEditableNodes(flowId);
        return Response.ok().data(nodes);
    }

    /**
     * 修改节点
     *
     * @param form 更新节点表单
     * @return 操作结果响应
     */
    @PostMapping("/updateNode")
    public Response updateNode(
            @RequestBody UpdateNodeForm form
    ) {
        templateApprovalService.updateNode(form);
        return Response.ok();
    }

    /**
     * 修改流程主题
     *
     * @param flowId 流程ID
     * @param title  标题
     * @return 操作结果响应
     */
    @GetMapping("/updateFlowTitle")
    public Response updateFlowTitle(
            @NotBlank @RequestParam String flowId,
            @NotBlank @RequestParam String title
    ) {
        templateApprovalService.updateFlowTitle(flowId, title);
        return Response.ok();
    }


    /**
     * 获取是否直送
     *
     * @param flowId 流程ID
     * @return 是否直送标志
     */
    @GetMapping("/getIsDirect")
    public Response getIsDirect(
        @RequestParam String flowId
    ) {
        boolean flag = templateApprovalService.getIsDirect(flowId);
        return Response.ok().data(flag);
    }

    /**
     * 获取流程审批人
     *
     * @param templateId 模板ID
     * @return 审批节点信息
     */
    @GetMapping("/getApprovalUsers")
    public Response getApprovalUsers(
            @NotBlank @RequestParam String templateId
    ) {
        ApprovalNodesDTO nodes = templateApprovalService.getApprovalUsers(templateId);
        return Response.ok().data(nodes);
    }

    /**
     * 获取用户和部门
     *
     * @param name 用户名
     * @return 部门用户视图列表
     */
    @GetMapping("/getUsersByCondition")
    public Response getUsersByCondition(
        @RequestParam String name
    ) {
        List<DepartmentUserView> users = bd.getSystemDatabase()
                .viewQueryMode(true)
                .view("getUserAndDept")
                .like("username", name)
                .doQuery(DepartmentUserView.class);
        return Response.ok().data(users);
    }
    /**
     * 发起人发起审批
     *
     * @param request       开始审批请求
     * @param bindingResult 绑定结果
     * @return 审批结果数据
     */
    @PostMapping("/startApproval")
    public Response startApproval(
            @RequestBody @Valid StartApprovalRequest request,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                throw new CommonException(error.getDefaultMessage());
            });
        }
        return Response.ok().data(templateApprovalService.startApproval(request));
    }

    /**
     * 直送回退回的节点
     *
     * @param templateId 模板ID
     * @param userId     用户ID
     * @return 操作结果响应
     */
    @GetMapping("/directSendingApproval")
    public Response directSendingApproval(
            @RequestParam @NotBlank String templateId,
            @RequestParam @NotBlank String userId
    ) {
        templateApprovalService.directSendingApproval(templateId, userId);
        return Response.ok();
    }

    /**
     * 查询审批列表
     *
     * @param form          审批列表表单
     * @param bindingResult 绑定结果
     * @return 审批列表数据
     */
    @GetMapping("/getApprovalList")
    public Response getTodoList(
            @Valid ApprovalListForm form,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                throw new CommonException(error.getDefaultMessage());
            });
        }
        return Response.ok().data(templateApprovalService.getApprovalList(form));
    }

    /**
     * 处理人处理审批通过还是拒绝
     *
     * @param request       处理审批请求
     * @param bindingResult 绑定结果
     * @return 操作结果响应
     */
    @PostMapping("/handleApproval")
    public Response handleApproval(
            @RequestBody @Valid HandleApprovalRequest request,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                throw new CommonException(error.getDefaultMessage());
            });
        }
        templateApprovalService.handleApproval(request);
        return Response.ok();
    }

    /**
     * 获取可退回节点
     *
     * @param flowId 流程ID
     * @return 可退回节点列表
     */
    @GetMapping("/getReturnNodes")
    public Response getReturnNodes(
            @NotBlank @RequestParam String flowId
    ) {
        List<String> result = templateApprovalService.getReturnNodes(flowId);
        return Response.ok().data(result);
    }

    /**
     * 处理人退回指定节点
     *
     * @param form          处理退回节点表单
     * @param bindingResult 绑定结果
     * @return 操作结果响应
     */
    @PostMapping("/handleReturnToNode")
    public Response handleReturnToNode(
            @RequestBody @Valid HandleReturnNodeForm form,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                throw new CommonException(error.getDefaultMessage());
            });
        }
        templateApprovalService.handleReturnToNode(form);
        return Response.ok();
    }

    /**
     * 发起人撤回审批
     *
     * @param request       处理审批请求
     * @param bindingResult 绑定结果
     * @return 操作结果响应
     */
    @PostMapping("/handleReturn")
    public Response handleReturn(
            @RequestBody @Valid HandleApprovalRequest request,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                throw new CommonException(error.getDefaultMessage());
            });
        }
        templateApprovalService.handleReturn(request);
        return Response.ok();
    }

    /**
     * 获取模板变动
     *
     * @param form          审批和参数表单
     * @param bindingResult 绑定结果
     * @return 模板变动分页结果
     */
    @GetMapping("/getTemplateChanges")
    public Response getTemplateChanges(
            @Valid ApprovalAndParameterForm form,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                throw new CommonException(error.getDefaultMessage());
            });
        }
        PageQueryResult<TemplateChangeView> result = templateApprovalService.getTemplateChanges(form);
        return Response.ok().data(result);
    }

    /**
     * 获取审批流程
     *
     * @param form          审批流程表单
     * @param bindingResult 绑定结果
     * @return 审批流程节点视图
     */
    @GetMapping("/getApprovalProcess")
    public Response getApprovalProcess(
            @Valid ApprovalFlowForm form,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                throw new CommonException(error.getDefaultMessage());
            });
        }
        ApprovalFlowNodeView approvalFlowView = templateApprovalService.getApprovalProcess(form);
        return Response.ok().data(approvalFlowView);
    }
}
