package com.ruoyi.credit.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.credit.config.LoanValidationNotificationConfig;
import com.ruoyi.credit.service.LoanValidationNotificationService;

/**
 * 贷款验证通知管理控制器
 * 
 * @author ruoyi
 * @date 2025-12-31
 */
@RestController
@RequestMapping("/api/credit/loan-validation/notification")
public class LoanValidationNotificationController extends BaseController
{
    @Autowired
    private LoanValidationNotificationService loanValidationNotificationService;

    @Autowired
    private LoanValidationNotificationConfig notificationConfig;

    /**
     * 获取通知配置信息
     */
    @PreAuthorize("@ss.hasPermi('credit:validation:notification:query')")
    @GetMapping("/config")
    public AjaxResult getNotificationConfig()
    {
        try {
            return success(notificationConfig);
        } catch (Exception e) {
            logger.error("获取通知配置信息失败", e);
            return error("获取通知配置信息失败: " + e.getMessage());
        }
    }

    /**
     * 初始化通知模板
     */
    @PreAuthorize("@ss.hasPermi('credit:validation:notification:init')")
    @Log(title = "贷款验证通知", businessType = BusinessType.OTHER)
    @PostMapping("/templates/init")
    public AjaxResult initNotificationTemplates()
    {
        try {
            boolean result = loanValidationNotificationService.initializeNotificationTemplates();
            
            if (result) {
                return success("通知模板初始化成功");
            } else {
                return error("通知模板初始化失败");
            }
        } catch (Exception e) {
            logger.error("初始化通知模板失败", e);
            return error("初始化通知模板失败: " + e.getMessage());
        }
    }

    /**
     * 获取通知发送统计
     */
    @PreAuthorize("@ss.hasPermi('credit:validation:notification:query')")
    @GetMapping("/statistics")
    public AjaxResult getNotificationStatistics(
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate)
    {
        try {
            Map<String, Object> statistics = loanValidationNotificationService.getNotificationStatistics(startDate, endDate);
            return success(statistics);
        } catch (Exception e) {
            logger.error("获取通知发送统计失败", e);
            return error("获取通知发送统计失败: " + e.getMessage());
        }
    }

    /**
     * 测试通知发送功能
     */
    @PreAuthorize("@ss.hasPermi('credit:validation:notification:test')")
    @Log(title = "贷款验证通知", businessType = BusinessType.OTHER)
    @PostMapping("/test")
    public AjaxResult testNotification(
            @RequestParam("loanId") Long loanId,
            @RequestParam(value = "notificationType", defaultValue = "VALIDATION_FAILURE") String notificationType)
    {
        try {
            if (loanId == null) {
                return error("贷款ID不能为空");
            }

            boolean result = false;
            String message = "";

            switch (notificationType.toUpperCase()) {
                case "VALIDATION_FAILURE":
                    // 这里需要创建一个测试用的验证记录
                    message = "验证失败通知测试功能暂未实现";
                    break;
                case "VALIDATION_EXCEPTION":
                    result = loanValidationNotificationService.sendValidationExceptionAlert(
                        loanId, "这是一个测试异常消息", "HIGH");
                    message = result ? "异常告警测试通知发送成功" : "异常告警测试通知发送失败";
                    break;
                default:
                    return error("不支持的通知类型: " + notificationType);
            }

            if (result) {
                return success(message);
            } else {
                return error(message);
            }
        } catch (Exception e) {
            logger.error("测试通知发送功能失败", e);
            return error("测试通知发送功能失败: " + e.getMessage());
        }
    }

    /**
     * 获取支持的通知渠道
     */
    @PreAuthorize("@ss.hasPermi('credit:validation:notification:query')")
    @GetMapping("/channels")
    public AjaxResult getSupportedChannels()
    {
        try {
            return success(java.util.Arrays.asList("EMAIL", "SMS", "SYSTEM", "WECHAT", "APP_PUSH"));
        } catch (Exception e) {
            logger.error("获取支持的通知渠道失败", e);
            return error("获取支持的通知渠道失败: " + e.getMessage());
        }
    }

    /**
     * 获取通知模板列表
     */
    @PreAuthorize("@ss.hasPermi('credit:validation:notification:query')")
    @GetMapping("/templates")
    public AjaxResult getNotificationTemplates()
    {
        try {
            java.util.List<java.util.Map<String, Object>> templates = new java.util.ArrayList<>();
            
            java.util.Map<String, Object> template1 = new java.util.HashMap<>();
            template1.put("templateCode", "LOAN_VALIDATION_FAILURE");
            template1.put("templateName", "贷款一致性验证失败通知");
            template1.put("notificationType", "VALIDATION_FAILURE");
            template1.put("supportedChannels", "EMAIL,SMS,SYSTEM");
            template1.put("businessType", "LOAN_CONSISTENCY");
            templates.add(template1);
            
            java.util.Map<String, Object> template2 = new java.util.HashMap<>();
            template2.put("templateCode", "LOAN_REVALIDATION_SUCCESS");
            template2.put("templateName", "贷款重新验证成功通知");
            template2.put("notificationType", "REVALIDATION_SUCCESS");
            template2.put("supportedChannels", "EMAIL,SYSTEM");
            template2.put("businessType", "LOAN_CONSISTENCY");
            templates.add(template2);
            
            java.util.Map<String, Object> template3 = new java.util.HashMap<>();
            template3.put("templateCode", "LOAN_VALIDATION_EXCEPTION");
            template3.put("templateName", "贷款验证系统异常告警");
            template3.put("notificationType", "SYSTEM_ALERT");
            template3.put("supportedChannels", "EMAIL,SMS");
            template3.put("businessType", "LOAN_CONSISTENCY");
            templates.add(template3);
            
            return success(templates);
        } catch (Exception e) {
            logger.error("获取通知模板列表失败", e);
            return error("获取通知模板列表失败: " + e.getMessage());
        }
    }
}