package com.mosquito.project.permission;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 审批流程控制器
 */
@RestController
@RequestMapping("/api/approval")
public class ApprovalController {

    private final ApprovalFlowService approvalFlowService;

    public ApprovalController(ApprovalFlowService approvalFlowService) {
        this.approvalFlowService = approvalFlowService;
    }

    /**
     * 获取审批流列表
     */
    @GetMapping("/flows")
    public ResponseEntity<List<SysApprovalFlow>> getFlows() {
        return ResponseEntity.ok(approvalFlowService.getAllFlows());
    }

    /**
     * 获取启用的审批流
     */
    @GetMapping("/flows/enabled")
    public ResponseEntity<List<SysApprovalFlow>> getEnabledFlows() {
        return ResponseEntity.ok(approvalFlowService.getEnabledFlows());
    }

    /**
     * 提交审批申请
     */
    @PostMapping("/submit")
    public ResponseEntity<Map<String, Object>> submitApproval(@RequestBody ApprovalSubmitRequest request) {
        try {
            Map<String, Object> result = approvalFlowService.submitApproval(
                    request.getFlowId(),
                    request.getBizType(),
                    request.getBizId(),
                    request.getTitle(),
                    request.getApplicantId(),
                    request.getApplyReason()
            );
            return ResponseEntity.ok(buildSuccessResponse(result));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(buildErrorResponse(e.getMessage()));
        }
    }

    /**
     * 通过触发事件提交审批
     */
    @PostMapping("/submit-by-event")
    public ResponseEntity<Map<String, Object>> submitApprovalByEvent(@RequestBody ApprovalSubmitByEventRequest request) {
        try {
            Map<String, Object> result = approvalFlowService.submitApprovalByEvent(
                    request.getTriggerEvent(),
                    request.getBizType(),
                    request.getBizId(),
                    request.getTitle(),
                    request.getApplicantId(),
                    request.getApplyReason()
            );
            return ResponseEntity.ok(buildSuccessResponse(result));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(buildErrorResponse(e.getMessage()));
        }
    }

    /**
     * 获取待审批列表
     */
    @GetMapping("/pending")
    public ResponseEntity<List<SysApprovalRecord>> getPendingApprovals(@RequestParam Long userId) {
        return ResponseEntity.ok(approvalFlowService.getPendingApprovals(userId));
    }

    /**
     * 获取已审批列表
     */
    @GetMapping("/processed")
    public ResponseEntity<List<SysApprovalRecord>> getProcessedList(@RequestParam Long userId) {
        return ResponseEntity.ok(approvalFlowService.getApprovedList(userId));
    }

    /**
     * 获取我发起的审批
     */
    @GetMapping("/my")
    public ResponseEntity<List<SysApprovalRecord>> getMyApplications(@RequestParam Long userId) {
        return ResponseEntity.ok(approvalFlowService.getMyApplications(userId));
    }

    /**
     * 处理审批
     */
    @PostMapping("/handle")
    public ResponseEntity<Map<String, Object>> handleApproval(@RequestBody ApprovalHandleRequest request) {
        try {
            Map<String, Object> result = approvalFlowService.handleApproval(
                    request.getRecordId(),
                    request.getAction(),
                    request.getOperatorId(),
                    request.getComment()
            );
            return ResponseEntity.ok(buildSuccessResponse(result));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(buildErrorResponse(e.getMessage()));
        }
    }

    /**
     * 取消审批
     */
    @PostMapping("/cancel")
    public ResponseEntity<Map<String, Object>> cancelApproval(@RequestBody ApprovalCancelRequest request) {
        try {
            approvalFlowService.cancelApproval(request.getRecordId(), request.getOperatorId());
            return ResponseEntity.ok(buildSuccessResponse("审批已取消"));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(buildErrorResponse(e.getMessage()));
        }
    }

    /**
     * 获取审批记录详情
     */
    @GetMapping("/records/{id}")
    public ResponseEntity<Map<String, Object>> getRecordById(@PathVariable Long id) {
        Map<String, Object> record = approvalFlowService.getRecordById(id);
        if (record == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(record);
    }

    /**
     * 获取审批历史
     */
    @GetMapping("/records/{recordId}/history")
    public ResponseEntity<List<SysApprovalHistory>> getApprovalHistory(@PathVariable Long recordId) {
        return ResponseEntity.ok(approvalFlowService.getApprovalHistory(recordId));
    }

    private Map<String, Object> buildSuccessResponse(Object data) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("data", data);
        response.put("message", "操作成功");
        return response;
    }

    private Map<String, Object> buildErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", 400);
        response.put("message", message);
        return response;
    }

    /**
     * 提交审批请求体
     */
    public static class ApprovalSubmitRequest {
        private Long flowId;
        private String bizType;
        private Long bizId;
        private String title;
        private Long applicantId;
        private String applyReason;

        public Long getFlowId() { return flowId; }
        public void setFlowId(Long flowId) { this.flowId = flowId; }
        public String getBizType() { return bizType; }
        public void setBizType(String bizType) { this.bizType = bizType; }
        public Long getBizId() { return bizId; }
        public void setBizId(Long bizId) { this.bizId = bizId; }
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        public Long getApplicantId() { return applicantId; }
        public void setApplicantId(Long applicantId) { this.applicantId = applicantId; }
        public String getApplyReason() { return applyReason; }
        public void setApplyReason(String applyReason) { this.applyReason = applyReason; }
    }

    /**
     * 通过触发事件提交审批请求体
     */
    public static class ApprovalSubmitByEventRequest {
        private String triggerEvent;
        private String bizType;
        private Long bizId;
        private String title;
        private Long applicantId;
        private String applyReason;

        public String getTriggerEvent() { return triggerEvent; }
        public void setTriggerEvent(String triggerEvent) { this.triggerEvent = triggerEvent; }
        public String getBizType() { return bizType; }
        public void setBizType(String bizType) { this.bizType = bizType; }
        public Long getBizId() { return bizId; }
        public void setBizId(Long bizId) { this.bizId = bizId; }
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        public Long getApplicantId() { return applicantId; }
        public void setApplicantId(Long applicantId) { this.applicantId = applicantId; }
        public String getApplyReason() { return applyReason; }
        public void setApplyReason(String applyReason) { this.applyReason = applyReason; }
    }

    /**
     * 审批处理请求体
     */
    public static class ApprovalHandleRequest {
        private Long recordId;
        private String action;
        private Long operatorId;
        private String comment;

        public Long getRecordId() { return recordId; }
        public void setRecordId(Long recordId) { this.recordId = recordId; }
        public String getAction() { return action; }
        public void setAction(String action) { this.action = action; }
        public Long getOperatorId() { return operatorId; }
        public void setOperatorId(Long operatorId) { this.operatorId = operatorId; }
        public String getComment() { return comment; }
        public void setComment(String comment) { this.comment = comment; }
    }

    /**
     * 取消审批请求体
     */
    public static class ApprovalCancelRequest {
        private Long recordId;
        private Long operatorId;

        public Long getRecordId() { return recordId; }
        public void setRecordId(Long recordId) { this.recordId = recordId; }
        public Long getOperatorId() { return operatorId; }
        public void setOperatorId(Long operatorId) { this.operatorId = operatorId; }
    }
}
