package com.erp.approval.controller;

import com.erp.approval.dto.*;
import com.erp.approval.service.AuditRuleService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import com.erp.common.core.model.PageResponse;
import java.util.Map;
import com.erp.common.core.model.ApiResponse;

/**
 * 审核规则管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/audit-rules")
@RequiredArgsConstructor
public class AuditRuleController {
    
    private final AuditRuleService auditRuleService;
    
    /**
     * 规则列表（支持分页/筛选/排序）
     */
    @GetMapping
    public ApiResponse<PageResponse<AuditRuleResponse>> listRules(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Boolean isActive,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false, defaultValue = "priority") String sortField,
            @RequestParam(required = false, defaultValue = "asc") String sortOrder) {
        
        AuditRuleQueryRequest request = AuditRuleQueryRequest.builder()
                .page(page)
                .pageSize(pageSize)
                .type(type)
                .isActive(isActive)
                .keyword(keyword)
                .sortField(sortField)
                .sortOrder(sortOrder)
                .build();
        
        PageResponse<AuditRuleResponse> result = auditRuleService.listRules(tenantId, request);
        return ApiResponse.success(result);
    }
    
    /**
     * 规则详情
     */
    @GetMapping("/{id}")
    public ApiResponse<AuditRuleResponse> getRule(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @PathVariable Long id) {
        
        return auditRuleService.getRuleById(tenantId, id)
                .map(ApiResponse::success)
                .orElse(ApiResponse.error(404, "规则不存在"));
    }
    
    /**
     * 创建规则
     */
    @PostMapping
    public ApiResponse<AuditRuleResponse> createRule(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @RequestHeader(value = "X-User-Id", defaultValue = "0") Long userId,
            @Valid @RequestBody AuditRuleCreateRequest request) {
        
        AuditRuleResponse result = auditRuleService.createRule(tenantId, userId, request);
        return ApiResponse.success(result);
    }
    
    /**
     * 更新规则
     */
    @PutMapping("/{id}")
    public ApiResponse<AuditRuleResponse> updateRule(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @RequestHeader(value = "X-User-Id", defaultValue = "0") Long userId,
            @PathVariable Long id,
            @Valid @RequestBody AuditRuleUpdateRequest request) {
        
        return auditRuleService.updateRule(tenantId, userId, id, request)
                .map(rule -> ApiResponse.success("规则更新成功", rule))
                .orElse(ApiResponse.error(404, "规则不存在"));
    }
    
    /**
     * 删除规则（软删除）
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteRule(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @PathVariable Long id) {
        
        boolean deleted = auditRuleService.deleteRule(tenantId, id);
        if (deleted) {
            return ApiResponse.success("规则已删除", null);
        }
        return ApiResponse.error(404, "规则不存在");
    }
    
    /**
     * 批量删除规则
     */
    @DeleteMapping("/batch")
    public ApiResponse<String> batchDeleteRules(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @Valid @RequestBody List<Long> ids) {
        
        int count = auditRuleService.batchDeleteRules(tenantId, ids);
        return ApiResponse.success("已删除 " + count + " 条规则", null);
    }
    
    /**
     * 批量启用/禁用规则
     */
    @PutMapping("/batch/toggle-active")
    public ApiResponse<String> batchToggleActive(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @RequestHeader(value = "X-User-Id", defaultValue = "0") Long userId,
            @RequestBody BatchToggleActiveRequest request) {
        
        int count = auditRuleService.batchToggleActive(tenantId, userId, request.getIds(), request.getIsActive());
        return ApiResponse.success("已更新 " + count + " 条规则", null);
    }
    
    /**
     * 调整优先级顺序（批量保存排序）
     */
    @PutMapping("/reorder")
    public ApiResponse<Void> reorderRules(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @RequestHeader(value = "X-User-Id", defaultValue = "0") Long userId,
            @Valid @RequestBody AuditRuleReorderRequest request) {
        
        auditRuleService.reorderRules(tenantId, userId, request);
        return ApiResponse.success("优先级排序已更新", null);
    }
    
    /**
     * 克隆规则
     */
    @PostMapping("/{id}/duplicate")
    public ApiResponse<AuditRuleResponse> duplicateRule(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @RequestHeader(value = "X-User-Id", defaultValue = "0") Long userId,
            @PathVariable Long id) {
        
        return auditRuleService.duplicateRule(tenantId, userId, id)
                .map(rule -> ApiResponse.success(rule))
                .orElse(ApiResponse.error(404, "规则不存在"));
    }
    
    /**
     * 测试规则（用指定数据验证规则匹配结果）
     */
    @PostMapping("/{id}/test")
    public ApiResponse<Map<String, Object>> testRule(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @PathVariable Long id,
            @Valid @RequestBody AuditRuleTestRequest request) {
        
        Map<String, Object> result = auditRuleService.testRule(tenantId, id, request);
        String message = (Boolean) result.get("matched") ? "规则匹配成功" : "规则未匹配";
        return ApiResponse.success(message, result);
    }
    
    /**
     * 模拟执行：根据规则类型对数据进行预审核
     */
    @PostMapping("/simulate")
    public ApiResponse<Map<String, Object>> simulateRules(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @Valid @RequestBody AuditRuleSimulateRequest request) {
        
        Map<String, Object> result = auditRuleService.simulateRules(tenantId, request);
        return ApiResponse.success("模拟执行完成", result);
    }
    
    /**
     * 获取支持的字段列表（供前端构建条件）
     */
    @GetMapping("/fields")
    public ApiResponse<Map<String, Object>> getFields(
            @RequestParam(required = false, defaultValue = "order") String type) {
        
        Map<String, Object> result = auditRuleService.getFields(type);
        return ApiResponse.success(result);
    }
    
    /**
     * 获取规则类型下拉列表
     */
    @GetMapping("/types")
    public ApiResponse<Map<String, String>> getTypes() {
        Map<String, String> result = auditRuleService.getTypes();
        return ApiResponse.success(result);
    }
    
    /**
     * 内部类：批量启用/禁用请求
     */
    @lombok.Data
    private static class BatchToggleActiveRequest {
        @jakarta.validation.constraints.NotEmpty(message = "ID列表不能为空")
        private List<Long> ids;
        
        @jakarta.validation.constraints.NotNull(message = "启用状态不能为空")
        private Boolean isActive;
    }
}
