package com.ruoyi.credit.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.credit.domain.ValidationRule;
import com.ruoyi.credit.service.IValidationRuleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 验证规则配置Controller
 * 
 * @author ruoyi
 * @date 2025-12-30
 */
@RestController
@RequestMapping("/api/credit/validation-rules")
public class ValidationRuleController extends BaseController
{
    @Autowired
    private IValidationRuleService validationRuleService;

    /**
     * 查询验证规则配置列表
     */
    @PreAuthorize("@ss.hasPermi('credit:validation-rule:list')")
    @GetMapping("/list")
    public TableDataInfo list(ValidationRule validationRule)
    {
        startPage();
        List<ValidationRule> list = validationRuleService.selectValidationRuleList(validationRule);
        return getDataTable(list);
    }

    /**
     * 导出验证规则配置列表
     */
    @PreAuthorize("@ss.hasPermi('credit:validation-rule:export')")
    @Log(title = "验证规则配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ValidationRule validationRule)
    {
        List<ValidationRule> list = validationRuleService.selectValidationRuleList(validationRule);
        ExcelUtil<ValidationRule> util = new ExcelUtil<ValidationRule>(ValidationRule.class);
        util.exportExcel(response, list, "验证规则配置数据");
    }

    /**
     * 获取验证规则配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('credit:validation-rule:query')")
    @GetMapping(value = "/{ruleId}")
    public AjaxResult getInfo(@PathVariable("ruleId") Long ruleId)
    {
        return success(validationRuleService.selectValidationRuleByRuleId(ruleId));
    }

    /**
     * 根据规则名称获取验证规则配置
     */
    @PreAuthorize("@ss.hasPermi('credit:validation-rule:query')")
    @GetMapping(value = "/name/{ruleName}")
    public AjaxResult getInfoByName(@PathVariable("ruleName") String ruleName)
    {
        ValidationRule rule = validationRuleService.selectValidationRuleByRuleName(ruleName);
        if (rule == null) {
            return error("规则不存在: " + ruleName);
        }
        return success(rule);
    }

    /**
     * 获取激活状态的验证规则列表（按优先级排序）
     */
    @PreAuthorize("@ss.hasPermi('credit:validation-rule:query')")
    @GetMapping("/active")
    public AjaxResult getActiveRules()
    {
        List<ValidationRule> activeRules = validationRuleService.selectActiveValidationRules();
        return success(activeRules);
    }

    /**
     * 根据规则类型获取验证规则列表
     */
    @PreAuthorize("@ss.hasPermi('credit:validation-rule:query')")
    @GetMapping("/type/{ruleType}")
    public AjaxResult getRulesByType(@PathVariable("ruleType") String ruleType)
    {
        List<ValidationRule> rules = validationRuleService.selectValidationRulesByType(ruleType);
        return success(rules);
    }

    /**
     * 新增验证规则配置
     */
    @PreAuthorize("@ss.hasPermi('credit:validation-rule:add')")
    @Log(title = "验证规则配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ValidationRule validationRule)
    {
        try {
            // 设置创建人
            validationRule.setCreatedBy(getUsername());
            
            int result = validationRuleService.insertValidationRule(validationRule);
            if (result > 0) {
                return success("新增验证规则成功");
            } else {
                return error("新增验证规则失败");
            }
        } catch (IllegalArgumentException e) {
            return error(e.getMessage());
        } catch (Exception e) {
            logger.error("新增验证规则失败", e);
            return error("新增验证规则失败: " + e.getMessage());
        }
    }

    /**
     * 修改验证规则配置
     */
    @PreAuthorize("@ss.hasPermi('credit:validation-rule:edit')")
    @Log(title = "验证规则配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ValidationRule validationRule)
    {
        try {
            int result = validationRuleService.updateValidationRule(validationRule);
            if (result > 0) {
                return success("修改验证规则成功");
            } else {
                return error("修改验证规则失败，规则不存在");
            }
        } catch (IllegalArgumentException e) {
            return error(e.getMessage());
        } catch (Exception e) {
            logger.error("修改验证规则失败", e);
            return error("修改验证规则失败: " + e.getMessage());
        }
    }

    /**
     * 删除验证规则配置
     */
    @PreAuthorize("@ss.hasPermi('credit:validation-rule:remove')")
    @Log(title = "验证规则配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ruleIds}")
    public AjaxResult remove(@PathVariable Long[] ruleIds)
    {
        try {
            int result = validationRuleService.deleteValidationRuleByRuleIds(ruleIds);
            if (result > 0) {
                return success("删除验证规则成功，删除数量: " + result);
            } else {
                return error("删除验证规则失败，规则不存在");
            }
        } catch (Exception e) {
            logger.error("删除验证规则失败", e);
            return error("删除验证规则失败: " + e.getMessage());
        }
    }

    /**
     * 批量更新规则状态
     */
    @PreAuthorize("@ss.hasPermi('credit:validation-rule:edit')")
    @Log(title = "验证规则配置", businessType = BusinessType.UPDATE)
    @PutMapping("/batch-status")
    public AjaxResult batchUpdateStatus(@RequestBody BatchStatusUpdateRequest request)
    {
        try {
            if (request.getRuleIds() == null || request.getRuleIds().length == 0) {
                return error("请选择要更新的规则");
            }
            
            if (request.getRuleStatus() == null || request.getRuleStatus().trim().isEmpty()) {
                return error("请指定要更新的状态");
            }
            
            int result = validationRuleService.batchUpdateRuleStatus(request.getRuleIds(), request.getRuleStatus());
            if (result > 0) {
                return success("批量更新规则状态成功，更新数量: " + result);
            } else {
                return error("批量更新规则状态失败，规则不存在");
            }
        } catch (IllegalArgumentException e) {
            return error(e.getMessage());
        } catch (Exception e) {
            logger.error("批量更新规则状态失败", e);
            return error("批量更新规则状态失败: " + e.getMessage());
        }
    }

    /**
     * 重新加载验证规则配置
     */
    @PreAuthorize("@ss.hasPermi('credit:validation-rule:reload')")
    @Log(title = "验证规则配置", businessType = BusinessType.OTHER)
    @PostMapping("/reload")
    public AjaxResult reloadRules()
    {
        try {
            int ruleCount = validationRuleService.reloadValidationRules();
            return success("重新加载验证规则配置成功，当前规则数量: " + ruleCount);
        } catch (Exception e) {
            logger.error("重新加载验证规则配置失败", e);
            return error("重新加载验证规则配置失败: " + e.getMessage());
        }
    }

    /**
     * 验证规则配置有效性
     */
    @PreAuthorize("@ss.hasPermi('credit:validation-rule:validate')")
    @Log(title = "验证规则配置", businessType = BusinessType.OTHER)
    @PostMapping("/validate")
    public AjaxResult validateRule(@RequestBody ValidationRule validationRule)
    {
        try {
            String validationMessage = validationRuleService.validateRuleConfiguration(validationRule);
            if (validationMessage == null) {
                return success("规则配置验证通过");
            } else {
                return error("规则配置验证失败: " + validationMessage);
            }
        } catch (Exception e) {
            logger.error("验证规则配置失败", e);
            return error("验证规则配置失败: " + e.getMessage());
        }
    }

    /**
     * 检查规则名称是否已存在
     */
    @PreAuthorize("@ss.hasPermi('credit:validation-rule:query')")
    @GetMapping("/check-name")
    public AjaxResult checkRuleName(String ruleName, Long excludeRuleId)
    {
        try {
            if (ruleName == null || ruleName.trim().isEmpty()) {
                return error("规则名称不能为空");
            }
            
            boolean exists = validationRuleService.checkRuleNameExists(ruleName.trim(), excludeRuleId);
            return success(java.util.Collections.singletonMap("exists", exists));
        } catch (Exception e) {
            logger.error("检查规则名称失败", e);
            return error("检查规则名称失败: " + e.getMessage());
        }
    }

    /**
     * 获取下一个可用的优先级值
     */
    @PreAuthorize("@ss.hasPermi('credit:validation-rule:query')")
    @GetMapping("/next-priority")
    public AjaxResult getNextPriority()
    {
        try {
            Integer nextPriority = validationRuleService.getNextAvailablePriority();
            return success(java.util.Collections.singletonMap("nextPriority", nextPriority));
        } catch (Exception e) {
            logger.error("获取下一个优先级失败", e);
            return error("获取下一个优先级失败: " + e.getMessage());
        }
    }

    /**
     * 批量状态更新请求对象
     */
    public static class BatchStatusUpdateRequest {
        private Long[] ruleIds;
        private String ruleStatus;

        public Long[] getRuleIds() {
            return ruleIds;
        }

        public void setRuleIds(Long[] ruleIds) {
            this.ruleIds = ruleIds;
        }

        public String getRuleStatus() {
            return ruleStatus;
        }

        public void setRuleStatus(String ruleStatus) {
            this.ruleStatus = ruleStatus;
        }
    }
}