package com.ruoyi.project.controller;

import java.util.*;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.project.domain.*;
import com.ruoyi.project.service.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 常见错误Controller
 */
@Controller
@RequestMapping("/project/check")
public class TrsWordSyncController extends BaseController
{
    private String prefix = "project/check";
    private String validApiKey = "TRSword123!@#";

    @Autowired
    private ITrsSensitiveWordsService trsSensitiveWordsService;

    @Autowired
    private ITrsDomainWordsService trsDomainWordsService;

    @Autowired
    private ITrsNameWordsService trsNameWordsService;

    @Autowired
    private ITrsPolicyWordsService trsPolicyWordsService;

    @Autowired
    private ITrsTechnicalWordsService trsTechnicalWordsService;

    @Autowired
    private ITrsNamenmgWordsService trsNamenmgWordsService;

    @Autowired
    private ITrsRegionWordsService trsRegionWordsService;

    // ... 原有方法保持不变 ...

    /**
     * 词库同步接口（API密钥验证）
     * 支持7种词库类型
     *
     * @param apiKey API密钥（通过Header传递）
     * @param wordType 词库类型（sensitive, domain, name, policy, technical, namenmg, region, all）
     * @param lastSyncTime 最后同步时间戳（毫秒），可选
     * @return 同步结果
     */
    @GetMapping("/sync")
    @ResponseBody
    public AjaxResult syncApprovedWords(
            @RequestHeader(value = "X-API-KEY", required = false) String apiKey,
            @RequestParam(value = "wordType", required = false, defaultValue = "all") String wordType,
            @RequestParam(value = "lastSyncTime", required = false) Long lastSyncTime) {

        logger.info("收到词库同步请求，词库类型: {}, lastSyncTime: {}", wordType, lastSyncTime);

        // 验证API密钥
        if (!isValidApiKey(apiKey)) {
            logger.warn("无效的API密钥访问: {}", apiKey);
            return AjaxResult.error("无效的API密钥", null);
        }

        try {
            // 解析词库类型
            WordLibType type = WordLibType.fromCode(wordType);

            // 解析同步时间
            Date syncTime = null;
            if (lastSyncTime != null && lastSyncTime > 0) {
                syncTime = new Date(lastSyncTime);
                logger.info("执行增量同步，时间: {}", syncTime);
            } else {
                logger.info("执行全量同步");
            }

            // 同步结果
            Map<String, Object> syncResult = new HashMap<>();
            long totalCount = 0;

            // 根据词库类型同步数据
            switch (type) {
                case SENSITIVE:
                    syncResult.put("sensitive", syncSensitiveWords(syncTime));
                    totalCount += ((List<?>) syncResult.get("sensitive")).size();
                    break;

                case DOMAIN:
                    syncResult.put("domain", syncDomainWords(syncTime));
                    totalCount += ((List<?>) syncResult.get("domain")).size();
                    break;

                case NAME:
                    syncResult.put("name", syncNameWords(syncTime));
                    totalCount += ((List<?>) syncResult.get("name")).size();
                    break;

                case POLICY:
                    syncResult.put("policy", syncPolicyWords(syncTime));
                    totalCount += ((List<?>) syncResult.get("policy")).size();
                    break;

                case TECHNICAL:
                    syncResult.put("technical", syncTechnicalWords(syncTime));
                    totalCount += ((List<?>) syncResult.get("technical")).size();
                    break;

                case NAMENMG:
                    syncResult.put("namenmg", syncNamenmgWords(syncTime));
                    totalCount += ((List<?>) syncResult.get("namenmg")).size();
                    break;

                case REGION:
                    syncResult.put("region", syncRegionWords(syncTime));
                    totalCount += ((List<?>) syncResult.get("region")).size();
                    break;

                case ALL:
                default:
                    syncResult.put("sensitive", syncSensitiveWords(syncTime));
                    syncResult.put("domain", syncDomainWords(syncTime));
                    syncResult.put("name", syncNameWords(syncTime));
                    syncResult.put("policy", syncPolicyWords(syncTime));
                    syncResult.put("technical", syncTechnicalWords(syncTime));
                    syncResult.put("namenmg", syncNamenmgWords(syncTime));
                    syncResult.put("region", syncRegionWords(syncTime));

                    totalCount += ((List<?>) syncResult.get("sensitive")).size();
                    totalCount += ((List<?>) syncResult.get("domain")).size();
                    totalCount += ((List<?>) syncResult.get("name")).size();
                    totalCount += ((List<?>) syncResult.get("policy")).size();
                    totalCount += ((List<?>) syncResult.get("technical")).size();
                    totalCount += ((List<?>) syncResult.get("namenmg")).size();
                    totalCount += ((List<?>) syncResult.get("region")).size();
                    break;
            }

            // 获取当前服务器时间作为同步时间点
            long currentTime = System.currentTimeMillis();

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("syncTime", currentTime);
            result.put("wordType", type.getCode());
            result.put("wordTypeName", type.getName());
            result.put("totalCount", totalCount);
            result.put("data", syncResult);
            result.put("message", "同步成功");

            logger.info("{} 同步成功，返回 {} 条数据", type.getName(), totalCount);
            return AjaxResult.success(result);

        } catch (Exception e) {
            logger.error("词库同步失败", e);
            return AjaxResult.error("同步失败: " + e.getMessage());
        }
    }

    // 词库类型枚举
    public enum WordLibType {
        SENSITIVE("sensitive", "常见错误"),
        DOMAIN("domain", "领域常识"),
        NAME("name", "人名职务"),
        POLICY("policy", "政治常识"),
        TECHNICAL("technical", "专业术语"),
        NAMENMG("namenmg", "内蒙古自治区领导人"),
        REGION("region", "内蒙古自治区地区"),
        ALL("all", "所有词库");

        private final String code;
        private final String name;

        WordLibType(String code, String name) {
            this.code = code;
            this.name = name;
        }

        public String getCode() {
            return code;
        }

        public String getName() {
            return name;
        }

        public static WordLibType fromCode(String code) {
            for (WordLibType type : WordLibType.values()) {
                if (type.getCode().equalsIgnoreCase(code)) {
                    return type;
                }
            }
            return ALL; // 默认返回所有词库
        }
    }

    /**
     * 同步常见错误词库
     */
    private List<TrsSensitiveWords> syncSensitiveWords(Date syncTime) {
        try {
            List<TrsSensitiveWords> wordList;
            if (syncTime != null) {
                wordList = trsSensitiveWordsService.selectApprovedWordsByUpdateTime(syncTime);
            } else {
                // 全量同步，创建查询条件
                TrsSensitiveWords query = new TrsSensitiveWords();
                query.setStatus("审核通过");
                wordList = trsSensitiveWordsService.selectTrsSensitiveWordsList(query);
            }
            return wordList != null ? wordList : new ArrayList<>();
        } catch (Exception e) {
            logger.error("同步常见错误词库失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 同步领域常识词库
     */
    private List<TrsDomainWords> syncDomainWords(Date syncTime) {
        try {
            List<TrsDomainWords> wordList;
            if (syncTime != null) {
                wordList = trsDomainWordsService.selectApprovedWordsByUpdateTime(syncTime);
            } else {
                TrsDomainWords query = new TrsDomainWords();
                query.setStatus("审核通过");
                wordList = trsDomainWordsService.selectTrsDomainWordsList(query);
            }
            return wordList != null ? wordList : new ArrayList<>();
        } catch (Exception e) {
            logger.error("同步领域常识词库失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 同步人名职务词库
     */
    private List<TrsNameWords> syncNameWords(Date syncTime) {
        try {
            List<TrsNameWords> wordList;
            if (syncTime != null) {
                wordList = trsNameWordsService.selectApprovedWordsByUpdateTime(syncTime);
            } else {
                TrsNameWords query = new TrsNameWords();
                query.setStatus("审核通过");
                wordList = trsNameWordsService.selectTrsNameWordsList(query);
            }
            return wordList != null ? wordList : new ArrayList<>();
        } catch (Exception e) {
            logger.error("同步人名职务词库失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 同步政治常识词库
     */
    private List<TrsPolicyWords> syncPolicyWords(Date syncTime) {
        try {
            List<TrsPolicyWords> wordList;
            if (syncTime != null) {
                wordList = trsPolicyWordsService.selectApprovedWordsByUpdateTime(syncTime);
            } else {
                TrsPolicyWords query = new TrsPolicyWords();
                query.setStatus("审核通过");
                wordList = trsPolicyWordsService.selectTrsPolicyWordsList(query);
            }
            return wordList != null ? wordList : new ArrayList<>();
        } catch (Exception e) {
            logger.error("同步政治常识词库失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 同步专业术语词库
     */
    private List<TrsTechnicalWords> syncTechnicalWords(Date syncTime) {
        try {
            List<TrsTechnicalWords> wordList;
            if (syncTime != null) {
                wordList = trsTechnicalWordsService.selectApprovedWordsByUpdateTime(syncTime);
            } else {
                TrsTechnicalWords query = new TrsTechnicalWords();
                query.setStatus("审核通过");
                wordList = trsTechnicalWordsService.selectTrsTechnicalWordsList(query);
            }
            return wordList != null ? wordList : new ArrayList<>();
        } catch (Exception e) {
            logger.error("同步专业术语词库失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 同步内蒙古自治区领导人词库
     */
    private List<TrsNamenmgWords> syncNamenmgWords(Date syncTime) {
        try {
            List<TrsNamenmgWords> wordList;
            if (syncTime != null) {
                wordList = trsNamenmgWordsService.selectApprovedWordsByUpdateTime(syncTime);
            } else {
                TrsNamenmgWords query = new TrsNamenmgWords();
                query.setStatus("审核通过");
                wordList = trsNamenmgWordsService.selectTrsNamenmgWordsList(query);
            }
            return wordList != null ? wordList : new ArrayList<>();
        } catch (Exception e) {
            logger.error("同步内蒙古领导人词库失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 同步内蒙古自治区地区词库
     */
    private List<TrsRegionWords> syncRegionWords(Date syncTime) {
        try {
            List<TrsRegionWords> wordList;
            if (syncTime != null) {
                wordList = trsRegionWordsService.selectApprovedWordsByUpdateTime(syncTime);
            } else {
                TrsRegionWords query = new TrsRegionWords();
                query.setStatus("审核通过");
                wordList = trsRegionWordsService.selectTrsRegionWordsList(query);
            }
            return wordList != null ? wordList : new ArrayList<>();
        } catch (Exception e) {
            logger.error("同步内蒙古地区词库失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 验证API密钥
     */
    private boolean isValidApiKey(String apiKey) {
        if (apiKey == null || apiKey.trim().isEmpty()) {
            return false;
        }
        return apiKey.equals(validApiKey);
    }
}