package com.ruoyi.project.controller;

import java.util.*;

import com.ruoyi.common.core.domain.entity.SysUser;
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.project.domain.TrsSensitiveWords;
import com.ruoyi.project.service.ITrsSensitiveWordsService;
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
 *
 * @author ruoyi
 * @date 2025-03-17
 */
@Controller
@RequestMapping("/project/check")
public class TrsSensitiveWordsController extends BaseController
{
    private String prefix = "project/check";

    private String validApiKey = "TRSword123!@#";

    @Autowired
    private ITrsSensitiveWordsService trsSensitiveWordsService;

    @RequiresPermissions("project:check:view")
    @GetMapping()
    public String check()
    {
        return prefix + "/check";
    }

    /**
     * 查询常见错误列表
     */
    @RequiresPermissions("project:check:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TrsSensitiveWords trsSensitiveWords)
    {
        startPage();
        List<TrsSensitiveWords> list = trsSensitiveWordsService.selectTrsSensitiveWordsList(trsSensitiveWords);
        return getDataTable(list);
    }

    /**
     * 导出常见错误列表
     */
    @RequiresPermissions("project:check:export")
    @Log(title = "常见错误", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TrsSensitiveWords trsSensitiveWords)
    {
        List<TrsSensitiveWords> list = trsSensitiveWordsService.selectTrsSensitiveWordsList(trsSensitiveWords);
        ExcelUtil<TrsSensitiveWords> util = new ExcelUtil<TrsSensitiveWords>(TrsSensitiveWords.class);
        return util.exportExcel(list, "常见错误数据");
    }

    /**
     * 新增常见错误
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存常见错误
     */
    @RequiresPermissions("project:check:add")
    @Log(title = "常见错误", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TrsSensitiveWords trsSensitiveWords)
    {
        trsSensitiveWords.setStatus("待审核");
        trsSensitiveWords.setTime(new Date());

        Long deptId = getSysUser().getDeptId();
        if(deptId == 1){
            deptId = 0L;
        }
        trsSensitiveWords.setDeptId(deptId);
        int status = trsSensitiveWordsService.insertTrsSensitiveWords(trsSensitiveWords);
        if(401 == status){
            return AjaxResult.warn("数据已存在");
        }else{
            return toAjax(status);
        }

    }

    /**
     * 修改常见错误
     */
    @RequiresPermissions("project:check:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        TrsSensitiveWords trsSensitiveWords = trsSensitiveWordsService.selectTrsSensitiveWordsById(id);
        mmap.put("trsSensitiveWords", trsSensitiveWords);
        return prefix + "/edit";
    }

    /**
     * 修改保存常见错误
     */
    @RequiresPermissions("project:check:edit")
    @Log(title = "常见错误", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TrsSensitiveWords trsSensitiveWords)
    {
        trsSensitiveWords.setTime(new Date());
        trsSensitiveWords.setStatus("待审核");
        return toAjax(trsSensitiveWordsService.updateTrsSensitiveWords(trsSensitiveWords));
    }

    @RequiresPermissions("project:check:edit")
    @Log(title = "常见错误", businessType = BusinessType.UPDATE)
    @PostMapping("/editstatus")
    @ResponseBody
    public AjaxResult editStatusSave(String ids, String status)
    {
        for (String id : ids.split(",")) {
            TrsSensitiveWords trsSensitiveWords = trsSensitiveWordsService.selectTrsSensitiveWordsById(Long.parseLong(id));
            trsSensitiveWords.setStatus(status);
            trsSensitiveWords.setTime(new Date());
            trsSensitiveWordsService.updateTrsSensitiveWords(trsSensitiveWords);
        }
        return toAjax(1);
    }

    /**
     * 删除常见错误
     */
    @RequiresPermissions("project:check:remove")
    @Log(title = "常见错误", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(trsSensitiveWordsService.deleteTrsSensitiveWordsByIds(ids));
    }

    @RequiresPermissions("system:check:import")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<TrsSensitiveWords> util = new ExcelUtil<TrsSensitiveWords>(TrsSensitiveWords.class);
        return util.importTemplateExcel("常见错误数据");
    }

    @Log(title = "常见错误管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:check:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<TrsSensitiveWords> util = new ExcelUtil<TrsSensitiveWords>(TrsSensitiveWords.class);
        List<TrsSensitiveWords> wordList = util.importExcel(file.getInputStream());
        Long deptId = getSysUser().getDeptId();
        if(deptId == 1){
            deptId = 0L;
        }
        String message = trsSensitiveWordsService.importWords(wordList, updateSupport,deptId);
//
        if(("导入成功"+System.lineSeparator()).equals(message)){
            return AjaxResult.success(message);
        }else{
            return AjaxResult.warn2(message);
        }
    }



    // 从配置文件中读取API密钥


    /**
     * 词库同步接口（API密钥验证）
     * 只返回审核通过的词库数据
     *
     * @param apiKey API密钥（通过Header传递）
     * @param lastSyncTime 最后同步时间戳（毫秒），可选
     * @return 同步结果
     */
/*    @GetMapping("/sync")
    public AjaxResult syncApprovedWords(
            @RequestHeader(value = "X-API-KEY", required = false) String apiKey,
            @RequestParam(value = "lastSyncTime", required = false) Long lastSyncTime) {

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

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

        try {
            // 构建查询条件
            TrsSensitiveWords query = new TrsSensitiveWords();
            query.setStatus("审核通过");  // 只查询审核通过的数据

            // 如果有最后同步时间，进行增量查询
            Date syncTime = null;
            if (lastSyncTime != null && lastSyncTime > 0) {
                syncTime = new Date(lastSyncTime);
            }

            // 调用Service方法获取数据
            List<TrsSensitiveWords> wordList = null;
            if (syncTime != null) {
                // 增量同步：获取指定时间后更新的数据
                wordList = trsSensitiveWordsService.selectApprovedWordsByUpdateTime(syncTime);
            }else {
                // 全量同步：获取所有审核通过的数据
                wordList = new ArrayList<>();
            }
            // 获取当前服务器时间作为同步时间点
            long currentTime = System.currentTimeMillis();

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("syncTime", currentTime);  // 本次同步的时间点
            result.put("wordCount", wordList.size());
            result.put("words", wordList);
            result.put("message", "同步成功");

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

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

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

        // 这里可以扩展为从数据库或Redis中验证多个密钥
        // 目前先使用配置文件中的单一密钥
        return apiKey.equals(validApiKey);
    }*/


}
