package com.boyue.hasfj.controller;

import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.boyue.common.core.controller.BaseController;
import com.boyue.common.core.domain.AjaxResult;
import com.boyue.hasfj.domain.HtmlPages;
import com.boyue.hasfj.service.IHtmlPagesService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 页面API控制器
 * 
 * @author boyue
 */
@RestController
@RequestMapping("/api/hasfj")
@Tag(name = "页面API接口")
public class HtmlPageApiController extends BaseController {
    
    @Autowired
    private IHtmlPagesService htmlPagesService;
    
    /**
     * 获取页面详情
     */
    @GetMapping("/page")
    @Operation(summary = "获取页面详情")
    public AjaxResult getPageDetail(@RequestParam(value = "type", required = true) String pageType,
                                   @RequestParam(value = "formatId", required = true) String formatId) {
        HtmlPages htmlPages = new HtmlPages();
        htmlPages.setPageType(pageType);
        htmlPages.setFormatId(formatId);
        htmlPages.setStatus(Integer.valueOf(1)); // 只查询启用状态的
        
        List<HtmlPages> list = htmlPagesService.selectHtmlPagesList(htmlPages);
        if (list != null && !list.isEmpty()) {
            HtmlPages page = list.get(0);
            // 使用专门的方法更新浏览次数
            htmlPagesService.updateHtmlPagesViewCount(page.getId());
            // 重新查询最新数据
            page = htmlPagesService.selectHtmlPagesById(page.getId());
            
            return AjaxResult.success(page);
        }
        
        return AjaxResult.error("未找到相关页面");
    }
    
    /**
     * 根据ID获取页面 - 增加类型检查防止非数字字符串作为ID传入
     */
    @GetMapping("/page/{id}")
    @Operation(summary = "根据ID获取页面")
    public AjaxResult getPageById(@PathVariable(value = "id", required = true) String idStr) {
        // 添加参数验证，确保ID是有效的数字
        try {
            // 尝试将ID转换为Long类型
            Long id = Long.valueOf(idStr);
            HtmlPages htmlPages = htmlPagesService.selectHtmlPagesById(id);
            if (htmlPages != null) {
                // 使用专门的方法更新浏览次数
                htmlPagesService.updateHtmlPagesViewCount(htmlPages.getId());
                // 重新查询最新数据
                htmlPages = htmlPagesService.selectHtmlPagesById(htmlPages.getId());
                
                return AjaxResult.success(htmlPages);
            }
            return AjaxResult.error("未找到ID为" + id + "的页面");
        } catch (NumberFormatException e) {
            // 如果ID不是有效的数字，返回错误信息
            return AjaxResult.error("无效的页面ID: " + idStr + "，请提供有效的数字ID");
        }
    }
    
    /**
     * 获取页面列表
     */
    @GetMapping("/pages")
    @Operation(summary = "获取页面列表")
    public AjaxResult getPages(@RequestParam(value = "type", required = false) String pageType) {
        HtmlPages htmlPages = new HtmlPages();
        if (pageType != null && !pageType.isEmpty()) {
            htmlPages.setPageType(pageType);
        }
        htmlPages.setStatus(Integer.valueOf(1)); // 只查询启用状态的
        
        List<HtmlPages> list = htmlPagesService.selectHtmlPagesList(htmlPages);
        return AjaxResult.success(list);
    }
    
    /**
     * 根据类型获取页面列表
     */
    @GetMapping("/hasfjpages/listByType/{pageType}")
    @Operation(summary = "根据类型获取页面列表")
    public AjaxResult getPagesByType(@PathVariable("pageType") String pageType) {
        HtmlPages htmlPages = new HtmlPages();
        htmlPages.setPageType(pageType);
        htmlPages.setStatus(Integer.valueOf(1)); // 只查询启用状态的
        
        startPage(); // 使用不带参数的分页方法，会自动从请求参数中获取分页信息
        List<HtmlPages> list = htmlPagesService.selectHtmlPagesList(htmlPages);
        return AjaxResult.success(getDataTable(list));
    }
    
    /**
     * 获取法律规定列表
     */
    @GetMapping("/laws")
    @Operation(summary = "获取法律规定列表")
    public AjaxResult getLaws() {
        HtmlPages htmlPages = new HtmlPages();
        htmlPages.setPageType("law");
        htmlPages.setStatus(Integer.valueOf(1));
        
        List<HtmlPages> list = htmlPagesService.selectHtmlPagesList(htmlPages);
        return AjaxResult.success(list);
    }
    
    /**
     * 获取典型案例列表
     */
    @GetMapping("/cases")
    @Operation(summary = "获取典型案例列表")
    public AjaxResult getCases() {
        HtmlPages htmlPages = new HtmlPages();
        htmlPages.setPageType("case");
        htmlPages.setStatus(Integer.valueOf(1));
        
        List<HtmlPages> list = htmlPagesService.selectHtmlPagesList(htmlPages);
        return AjaxResult.success(list);
    }
    
    /**
     * 获取表单下载列表
     */
    @GetMapping("/forms")
    @Operation(summary = "获取表单下载列表")
    public AjaxResult getForms() {
        HtmlPages htmlPages = new HtmlPages();
        htmlPages.setPageType("form");
        htmlPages.setStatus(Integer.valueOf(1));
        
        List<HtmlPages> list = htmlPagesService.selectHtmlPagesList(htmlPages);
        return AjaxResult.success(list);
    }
    
    /**
     * 搜索API
     */
    @GetMapping("/search")
    @Operation(summary = "搜索内容")
    public AjaxResult search(
        @RequestParam(value = "keyword", required = false) String keyword,
        @RequestParam(value = "q", required = false) String q,
        @RequestParam(value = "content", required = false) String content,
        @RequestParam(value = "type", required = false) String pageType) {
        
        // 按优先级选择搜索关键词
        String searchText = keyword;
        if (searchText == null || searchText.trim().isEmpty()) {
            searchText = q;
        }
        if (searchText == null || searchText.trim().isEmpty()) {
            searchText = content;
        }
        
        if (searchText == null || searchText.trim().isEmpty()) {
            return AjaxResult.error("搜索关键词不能为空");
        }
        
        HtmlPages searchCondition = new HtmlPages();
        searchCondition.setStatus(Integer.valueOf(1)); // 只搜索启用状态的内容
        if (pageType != null && !pageType.trim().isEmpty()) {
            searchCondition.setPageType(pageType);
        }
        
        List<HtmlPages> allPages = htmlPagesService.selectHtmlPagesList(searchCondition);
        List<HtmlPages> searchResults = new ArrayList<>();
        
        if (allPages != null && !allPages.isEmpty()) {
            // 在标题和内容中搜索关键词
            String keywordLower = searchText.toLowerCase();
            searchResults = allPages.stream()
                .filter(page -> {
                    String title = page.getTitle() != null ? page.getTitle().toLowerCase() : "";
                    String pageContent = page.getContent() != null ? page.getContent().toLowerCase() : "";
                    String desc = page.getDescription() != null ? page.getDescription().toLowerCase() : "";
                    String keys = page.getKeywords() != null ? page.getKeywords().toLowerCase() : "";
                    
                    return title.contains(keywordLower) || 
                           pageContent.contains(keywordLower) || 
                           desc.contains(keywordLower) || 
                           keys.contains(keywordLower);
                })
                .collect(Collectors.toList());
        }
        
        return AjaxResult.success(searchResults);
    }
    
    /**
     * 搜索API - 前端路径兼容版本
     */
    @GetMapping({"/hasfjpages/search", "/search"})
    @Operation(summary = "搜索内容(前端兼容版)")
    public AjaxResult searchFrontend(
        @RequestParam(value = "keyword", required = false) String keyword,
        @RequestParam(value = "q", required = false) String q,
        @RequestParam(value = "content", required = false) String content,
        @RequestParam(value = "type", required = false) String pageType,
        @RequestParam(value = "pageType", required = false) String pageTypeAlt,
        @RequestParam(value = "stringQuery", required = false) String stringQuery) {
        
        try {
            // 获取可能的ID参数，但不使用@RequestParam注解
            // 因为@RequestParam对于特定类型的参数会尝试自动类型转换，可能导致错误
            String idStr = null;
            try {
                // 手动从请求参数中获取id，避免Spring自动类型转换导致的错误
                idStr = this.getRequest().getParameter("id");
                System.out.println("手动获取id参数: " + idStr);
            } catch (Exception e) {
                System.out.println("获取id参数时出错: " + e.getMessage());
            }
            
            System.out.println("搜索请求参数: keyword=" + keyword + ", q=" + q + ", content=" + content + 
                            ", type=" + pageType + ", pageType=" + pageTypeAlt + 
                            ", id=" + idStr + ", stringQuery=" + stringQuery);
            
            // 检测参数值是否含有前缀，如果有则移除前缀
            if (keyword != null && keyword.startsWith("keyword:")) {
                keyword = keyword.substring("keyword:".length());
            }
            if (q != null && q.startsWith("keyword:")) {
                q = q.substring("keyword:".length());
            }
            if (content != null && content.startsWith("keyword:")) {
                content = content.substring("keyword:".length());
            }
            
            // 特殊关键词处理，如果搜索关键词为"search"、"如何"等特殊词，强制使用字符串搜索模式
            boolean forceStringSearch = "true".equalsIgnoreCase(stringQuery);
            
            // 扩展特殊关键词列表，包括"如何"、"search"等
            String[] specialKeywords = {"search", "如何", "怎么", "怎样", "什么", "哪些", "为什么"};
            
            // 检查所有可能的参数是否包含特殊关键词
            if (containsSpecialKeyword(keyword, specialKeywords) ||
                containsSpecialKeyword(q, specialKeywords) ||
                containsSpecialKeyword(content, specialKeywords) ||
                containsSpecialKeyword(idStr, specialKeywords)) {
                forceStringSearch = true;
                System.out.println("检测到特殊关键词，启用强制字符串搜索模式");
            }
            
            // 按优先级选择搜索关键词
            String searchText = keyword;
            if (searchText == null || searchText.trim().isEmpty()) {
                searchText = q;
            }
            if (searchText == null || searchText.trim().isEmpty()) {
                searchText = content;
            }
            if (searchText == null || searchText.trim().isEmpty() && !forceStringSearch && idStr != null && !isSpecialKeyword(idStr)) {
                searchText = idStr; // 如果ID不是数字且不是特殊关键词，当作关键词使用
            }
            
            if (searchText == null || searchText.trim().isEmpty()) {
                return AjaxResult.error("搜索关键词不能为空");
            }
            
            System.out.println("最终使用的搜索文本: " + searchText + ", 强制字符串搜索模式: " + forceStringSearch);
            
            // 确定页面类型
            String finalPageType = pageType;
            if (finalPageType == null || finalPageType.trim().isEmpty()) {
                finalPageType = pageTypeAlt;
            }
            
            // 直接调用专用搜索API
            return searchContent(searchText, finalPageType);
        } catch (Exception ex) {
            System.out.println("搜索接口全局异常: " + ex.getMessage());
            ex.printStackTrace();
            return AjaxResult.error("搜索服务异常，请稍后重试");
        }
    }

    /**
     * 判断字符串是否包含特殊关键词
     */
    private boolean containsSpecialKeyword(String text, String[] specialKeywords) {
        if (text == null || text.trim().isEmpty()) {
            return false;
        }
        
        String lowerText = text.toLowerCase();
        for (String keyword : specialKeywords) {
            if (lowerText.contains(keyword.toLowerCase())) {
                System.out.println("检测到特殊关键词: " + keyword + " 在文本: " + text);
                return true;
            }
        }
        
        return false;
    }

    /**
     * 判断字符串是否为特殊关键词
     */
    private boolean isSpecialKeyword(String text) {
        if (text == null || text.trim().isEmpty()) {
            return false;
        }
        
        String[] specialKeywords = {"search", "如何", "怎么", "怎样", "什么", "哪些", "为什么"};
        String lowerText = text.toLowerCase();
        
        for (String keyword : specialKeywords) {
            if (lowerText.equals(keyword.toLowerCase())) {
                return true;
            }
        }
        
        // 检查是否为纯数字
        try {
            Long.parseLong(text);
            return false; // 是纯数字，不是特殊关键词
        } catch (NumberFormatException e) {
            return true; // 不是纯数字，视为特殊关键词
        }
    }

    /**
     * 搜索API - 纯文本搜索端点，无ID参数干扰
     */
    @GetMapping("/search-text")
    @Operation(summary = "全文搜索(无ID冲突)")
    public AjaxResult searchText(
        @RequestParam(value = "keyword", required = false) String keyword,
        @RequestParam(value = "type", required = false) String pageType) {
        
        System.out.println("全文搜索请求: keyword=" + keyword + ", type=" + pageType);
        
        if (keyword == null || keyword.trim().isEmpty()) {
            return AjaxResult.error("搜索关键词不能为空");
        }
        
        HtmlPages searchCondition = new HtmlPages();
        searchCondition.setStatus(Integer.valueOf(1)); // 只搜索启用状态的内容
        if (pageType != null && !pageType.trim().isEmpty()) {
            searchCondition.setPageType(pageType);
        }
        
        try {
            // 获取所有启用状态的页面
            List<HtmlPages> allPages = htmlPagesService.selectHtmlPagesList(searchCondition);
            List<HtmlPages> searchResults = new ArrayList<>();
            
            if (allPages != null && !allPages.isEmpty()) {
                // 在标题和内容中搜索关键词
                String keywordLower = keyword.toLowerCase();
                searchResults = allPages.stream()
                    .filter(page -> {
                        String title = page.getTitle() != null ? page.getTitle().toLowerCase() : "";
                        String pageContent = page.getContent() != null ? page.getContent().toLowerCase() : "";
                        String desc = page.getDescription() != null ? page.getDescription().toLowerCase() : "";
                        String keys = page.getKeywords() != null ? page.getKeywords().toLowerCase() : "";
                        
                        return title.contains(keywordLower) || 
                               pageContent.contains(keywordLower) || 
                               desc.contains(keywordLower) || 
                               keys.contains(keywordLower);
                    })
                    .collect(Collectors.toList());
            }
            
            System.out.println("全文搜索结果数量: " + searchResults.size());
            return AjaxResult.success(searchResults);
        } catch (Exception e) {
            System.out.println("全文搜索出错: " + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("搜索服务异常，请稍后重试");
        }
    }

    /**
     * 专用搜索API - 全新路径，避免与任何现有API冲突
     */
    @GetMapping("/search-content")
    @Operation(summary = "专用内容搜索API")
    public AjaxResult searchContent(@RequestParam(value = "keyword", required = false) String keyword,
                                  @RequestParam(value = "type", required = false) String pageType) {
        System.out.println("专用搜索API调用: keyword=" + keyword + ", type=" + pageType);
        
        try {
            // 参数验证和处理
            if (keyword == null || keyword.trim().isEmpty()) {
                System.out.println("搜索关键词为空，返回错误");
                return AjaxResult.error("搜索关键词不能为空");
            }
            
            // 记录关键词信息
            System.out.println("处理搜索关键词: " + keyword);
            
            // 检查是否为特殊关键词
            String[] specialKeywords = {"search", "如何", "怎么", "怎样", "什么", "哪些", "为什么"};
            boolean isSpecial = false;
            for (String special : specialKeywords) {
                if (keyword.toLowerCase().contains(special.toLowerCase())) {
                    isSpecial = true;
                    System.out.println("检测到特殊关键词: " + special + " 在搜索文本中");
                    break;
                }
            }
            
            // 构建搜索条件
            HtmlPages searchCondition = new HtmlPages();
            searchCondition.setStatus(Integer.valueOf(1)); // 只搜索启用状态的内容
            
            if (pageType != null && !pageType.trim().isEmpty()) {
                searchCondition.setPageType(pageType);
                System.out.println("按类型搜索: " + pageType);
            } else {
                System.out.println("搜索所有类型");
            }
            
            try {
                // 获取所有启用状态的页面
                System.out.println("开始查询数据库...");
                List<HtmlPages> allPages = htmlPagesService.selectHtmlPagesList(searchCondition);
                System.out.println("数据库查询完成，总记录数: " + (allPages != null ? allPages.size() : 0));
                
                List<HtmlPages> searchResults = new ArrayList<>();
                
                if (allPages != null && !allPages.isEmpty()) {
                    // 在标题和内容中搜索关键词
                    String keywordLower = keyword.toLowerCase();
                    searchResults = allPages.stream()
                        .filter(page -> {
                            // 获取页面各字段，防止空值
                            String title = page.getTitle() != null ? page.getTitle().toLowerCase() : "";
                            String pageContent = page.getContent() != null ? page.getContent().toLowerCase() : "";
                            String desc = page.getDescription() != null ? page.getDescription().toLowerCase() : "";
                            String keys = page.getKeywords() != null ? page.getKeywords().toLowerCase() : "";
                            String formatId = page.getFormatId() != null ? page.getFormatId().toLowerCase() : "";
                            String author = page.getAuthor() != null ? page.getAuthor().toLowerCase() : "";
                            
                            // 对所有字段进行关键词匹配，实现全局搜索
                            boolean matches = title.contains(keywordLower) || 
                                   pageContent.contains(keywordLower) || 
                                   desc.contains(keywordLower) || 
                                   keys.contains(keywordLower) ||
                                   formatId.contains(keywordLower) ||
                                   author.contains(keywordLower);
                            
                            if (matches) {
                                System.out.println("找到匹配: ID=" + page.getId() + ", 标题=" + page.getTitle() + ", 类型=" + page.getPageType());
                            }
                            
                            return matches;
                        })
                        .collect(Collectors.toList());
                    
                    // 将匹配度最高的结果排在前面（标题匹配优先于内容匹配）
                    searchResults.sort((a, b) -> {
                        String aTitle = a.getTitle() != null ? a.getTitle().toLowerCase() : "";
                        String bTitle = b.getTitle() != null ? b.getTitle().toLowerCase() : "";
                        
                        boolean aTitleMatch = aTitle.contains(keywordLower);
                        boolean bTitleMatch = bTitle.contains(keywordLower);
                        
                        if (aTitleMatch && !bTitleMatch) {
                            return -1;
                        } else if (!aTitleMatch && bTitleMatch) {
                            return 1;
                        } else {
                            return 0;
                        }
                    });
                }
                
                System.out.println("专用搜索API搜索结果数量: " + searchResults.size());
                
                // 返回成功结果
                AjaxResult result = AjaxResult.success(searchResults);
                result.put("total", searchResults.size());
                return result;
            } catch (Exception e) {
                System.out.println("专用搜索API出错: " + e.getMessage());
                e.printStackTrace();
                return AjaxResult.error("搜索服务异常，请稍后重试: " + e.getMessage());
            }
        } catch (Exception ex) {
            System.out.println("专用搜索API全局异常: " + ex.getMessage());
            ex.printStackTrace();
            return AjaxResult.error("搜索服务异常，请稍后重试");
        }
    }

    /**
     * 为确保向后兼容，添加一个额外的搜索端点，与前端路径匹配
     */
    @GetMapping("/hasfjpages/search-content")
    @Operation(summary = "专用内容搜索API(前端兼容版)")
    public AjaxResult searchContentFrontend(@RequestParam(value = "keyword", required = true) String keyword,
                                          @RequestParam(value = "type", required = false) String pageType) {
        // 调用主要的搜索方法
        return searchContent(keyword, pageType);
    }

    /**
     * 新增：前端搜索API - 无需前缀路径，直接支持/hasfj/search-content
     */
    @GetMapping("/hasfj/search-content")
    @Operation(summary = "前端直接搜索API")
    public AjaxResult directSearchContent(@RequestParam(value = "keyword", required = true) String keyword,
                                        @RequestParam(value = "type", required = false) String pageType) {
        // 调用主要的搜索方法
        return searchContent(keyword, pageType);
    }
    
    /**
     * 新增：搜索API - 处理所有搜索请求的通用端点
     * 此端点不会与ID路径冲突，专门用于处理搜索请求
     */
    @GetMapping("/search-api")
    @Operation(summary = "通用搜索API")
    public AjaxResult searchApi(@RequestParam(value = "keyword", required = true) String keyword,
                              @RequestParam(value = "type", required = false) String pageType) {
        // 调用主要的搜索方法
        return searchContent(keyword, pageType);
    }
    
    /**
     * 新增：前端搜索API - 前端兼容版本
     */
    @GetMapping("/hasfjpages/search-api")
    @Operation(summary = "通用搜索API(前端兼容版)")
    public AjaxResult searchApiFrontend(@RequestParam(value = "keyword", required = true) String keyword,
                                      @RequestParam(value = "type", required = false) String pageType) {
        // 调用主要的搜索方法
        return searchContent(keyword, pageType);
    }

    /**
     * 获取当前请求对象
     */
    private HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
} 