package com.ruoyi.web.controller.jarvis;

import com.alibaba.fastjson2.JSONObject;
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.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.jarvis.config.TencentDocConfig;
import com.ruoyi.jarvis.service.ITencentDocService;
import com.ruoyi.jarvis.service.ITencentDocTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * 腾讯文档配置管理Controller
 * 用于动态配置H-TF订单自动写入腾讯文档的相关参数
 * 
 * @author system
 */
@RestController
@RequestMapping("/jarvis/tencentDoc/config")
public class TencentDocConfigController extends BaseController {
    
    private static final Logger log = LoggerFactory.getLogger(TencentDocConfigController.class);
    
    @Autowired
    private TencentDocConfig tencentDocConfig;
    
    @Autowired
    private ITencentDocService tencentDocService;
    
    @Autowired
    private ITencentDocTokenService tencentDocTokenService;
    
    @Autowired
    private RedisCache redisCache;
    
    // Redis key前缀（用于存储文档配置）
    private static final String REDIS_KEY_PREFIX = "tencent:doc:auto:config:";

    
    /**
     * 获取当前配置
     * 注意：accessToken 由系统自动管理（通过授权登录），此接口只返回状态
     */
    @GetMapping
    public AjaxResult getConfig() {
        try {
            JSONObject config = new JSONObject();
            
            // 1. 检查 accessToken 状态（从Token服务）
            boolean hasAccessToken = false;
            String accessTokenStatus = "未授权";
            try {
                String accessToken = tencentDocTokenService.getValidAccessToken();
                if (accessToken != null && !accessToken.isEmpty()) {
                    hasAccessToken = true;
                    accessTokenStatus = "已授权";
                }
            } catch (Exception e) {
                // Token不存在或已过期
                accessTokenStatus = "未授权：" + e.getMessage();
            }
            
            // 2. 从Redis获取文档配置
            String fileId = redisCache.getCacheObject(REDIS_KEY_PREFIX + "fileId");
            String sheetId = redisCache.getCacheObject(REDIS_KEY_PREFIX + "sheetId");
            Integer headerRow = redisCache.getCacheObject(REDIS_KEY_PREFIX + "headerRow");
            Integer startRow = redisCache.getCacheObject(REDIS_KEY_PREFIX + "startRow");
            
            // 如果Redis中没有，则使用配置文件中的默认值
            if (fileId == null || fileId.isEmpty()) {
                fileId = tencentDocConfig.getFileId();
            }
            if (sheetId == null || sheetId.isEmpty()) {
                sheetId = tencentDocConfig.getSheetId();
            }
            if (headerRow == null) {
                headerRow = tencentDocConfig.getHeaderRow();
            }
            if (startRow == null) {
                startRow = tencentDocConfig.getStartRow();
            }
            
            config.put("hasAccessToken", hasAccessToken);
            config.put("accessTokenStatus", accessTokenStatus);
            config.put("fileId", fileId);
            config.put("sheetId", sheetId);
            config.put("headerRow", headerRow);
            config.put("startRow", startRow);
            config.put("appId", tencentDocConfig.getAppId());
            config.put("apiBaseUrl", tencentDocConfig.getApiBaseUrl());
            
            // 仅从接口获取 rowCount 用于展示，无任何进度缓存；与填充逻辑一致：每次取最后200行
            if (fileId != null && !fileId.isEmpty() && sheetId != null && !sheetId.isEmpty()) {
                try {
                    String accessToken = tencentDocTokenService.getValidAccessToken();
                    if (accessToken != null && !accessToken.isEmpty()) {
                        int rowCount = tencentDocService.getSheetRowTotal(accessToken, fileId, sheetId);
                        if (rowCount > 0) {
                            config.put("currentProgress", rowCount);
                            int nextStartRow = Math.max(3, rowCount - 199);  // 与填充逻辑一致：取最后200行
                            config.put("nextStartRow", nextStartRow);
                            config.put("progressHint", String.format("表格当前 %d 行（接口获取），每次同步取最后200行：第 %d ~ %d 行", rowCount, nextStartRow, rowCount));
                        } else {
                            config.put("currentProgress", null);
                            config.put("nextStartRow", startRow);
                            config.put("progressHint", "未获取到行数");
                        }
                    } else {
                        config.put("currentProgress", null);
                        config.put("nextStartRow", startRow);
                        config.put("progressHint", "未授权，无法获取表格行数");
                    }
                } catch (Exception e) {
                    log.warn("获取 rowCount 失败: {}", e.getMessage());
                    config.put("currentProgress", null);
                    config.put("nextStartRow", startRow);
                    config.put("progressHint", "获取表格行数失败: " + e.getMessage());
                }
            }
            
            // 检查配置是否完整
            boolean isConfigured = hasAccessToken &&
                                   fileId != null && !fileId.isEmpty() &&
                                   sheetId != null && !sheetId.isEmpty();
            config.put("isConfigured", isConfigured);
            
            // 提供配置建议
            if (!hasAccessToken) {
                config.put("hint", "请先访问 /jarvis/tendoc/authUrl 完成授权登录");
            } else if (fileId == null || fileId.isEmpty() || sheetId == null || sheetId.isEmpty()) {
                config.put("hint", "请配置目标文档的 fileId 和 sheetId");
            } else {
                config.put("hint", "配置完整，H-TF订单将自动写入腾讯文档");
            }
            
            return AjaxResult.success("获取配置成功", config);
        } catch (Exception e) {
            log.error("获取腾讯文档配置失败", e);
            return AjaxResult.error("获取配置失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新配置（保存到Redis，180天有效期）
     * 注意：accessToken 由系统自动管理，无需手动配置
     * 
     * @param params 包含 fileId, sheetId, startRow
     */
    @Log(title = "腾讯文档配置", businessType = BusinessType.UPDATE)
    @PostMapping
    public AjaxResult updateConfig(@RequestBody JSONObject params) {
        try {
            String fileId = params.getString("fileId");
            String sheetId = params.getString("sheetId");
            Integer headerRow = params.getInteger("headerRow");
            Integer startRow = params.getInteger("startRow");
            
            // 验证必填字段
            if (fileId == null || fileId.trim().isEmpty()) {
                return AjaxResult.error("文件ID不能为空");
            }
            if (sheetId == null || sheetId.trim().isEmpty()) {
                return AjaxResult.error("工作表ID不能为空");
            }
            
            // headerRow默认值为2
            if (headerRow == null || headerRow < 1) {
                headerRow = 2;
            }
            
            // startRow默认值为3
            if (startRow == null || startRow < 1) {
                startRow = 3;
            }
            
            // 检查是否已授权
            boolean hasAccessToken = false;
            try {
                String accessToken = tencentDocTokenService.getValidAccessToken();
                hasAccessToken = (accessToken != null && !accessToken.isEmpty());
            } catch (Exception e) {
                log.warn("检查授权状态时出错: {}", e.getMessage());
            }
            
            if (!hasAccessToken) {
                return AjaxResult.error("尚未完成腾讯文档授权，请先访问 /jarvis/tendoc/authUrl 完成授权");
            }
            
            // 保存到Redis（180天有效期）
            redisCache.setCacheObject(REDIS_KEY_PREFIX + "fileId", fileId.trim(), 180, TimeUnit.DAYS);
            redisCache.setCacheObject(REDIS_KEY_PREFIX + "sheetId", sheetId.trim(), 180, TimeUnit.DAYS);
            redisCache.setCacheObject(REDIS_KEY_PREFIX + "headerRow", headerRow, 180, TimeUnit.DAYS);
            redisCache.setCacheObject(REDIS_KEY_PREFIX + "startRow", startRow, 180, TimeUnit.DAYS);
            
            // 不再使用 Redis 存储进度，配置更新后下次从接口获取 rowCount 决定范围
            log.info("配置已更新，将从第 {} 行开始（下次从接口获取 rowCount）", startRow);
            
            // 同时更新TencentDocConfig对象（内存中）
            tencentDocConfig.setFileId(fileId.trim());
            tencentDocConfig.setSheetId(sheetId.trim());
            tencentDocConfig.setHeaderRow(headerRow);
            tencentDocConfig.setStartRow(startRow);
            
            log.info("H-TF订单自动写入配置已更新 - fileId: {}, sheetId: {}, headerRow: {}, startRow: {}", 
                fileId.trim(), sheetId.trim(), headerRow, startRow);
            
            JSONObject result = new JSONObject();
            result.put("message", "配置更新成功，已保存到Redis（180天有效期）");
            result.put("fileId", fileId.trim());
            result.put("sheetId", sheetId.trim());
            result.put("headerRow", headerRow);
            result.put("startRow", startRow);
            result.put("hint", "现在录入分销标识为 H-TF 的订单时，将自动追加到此腾讯文档（从第" + startRow + "行开始匹配）");
            
            return AjaxResult.success("配置更新成功", result);
        } catch (Exception e) {
            log.error("更新腾讯文档配置失败", e);
            return AjaxResult.error("配置更新失败: " + e.getMessage());
        }
    }
    
    /**
     * 测试配置是否有效
     * 尝试读取指定表格的工作表列表
     */
    @GetMapping("/test")
    public AjaxResult testConfig() {
        try {
            // 1. 获取访问令牌（从Token服务）
            String accessToken;
            try {
                accessToken = tencentDocTokenService.getValidAccessToken();
            } catch (Exception e) {
                return AjaxResult.error("获取访问令牌失败：" + e.getMessage() + 
                    "。请先访问 /jarvis/tendoc/authUrl 完成授权");
            }
            
            if (accessToken == null || accessToken.isEmpty()) {
                return AjaxResult.error("访问令牌未配置，请先完成腾讯文档授权");
            }
            
            // 2. 获取文档配置
            String fileId = redisCache.getCacheObject(REDIS_KEY_PREFIX + "fileId");
            if (fileId == null || fileId.isEmpty()) {
                fileId = tencentDocConfig.getFileId();
            }
            
            if (fileId == null || fileId.isEmpty()) {
                return AjaxResult.error("文件ID未配置，请先配置目标文档");
            }
            
            // 3. 测试API调用：获取工作表列表
            log.info("测试腾讯文档配置 - fileId: {}", fileId);
            JSONObject result = tencentDocService.getSheetList(accessToken, fileId);
            
            if (result != null) {
                JSONObject testResult = new JSONObject();
                testResult.put("status", "success");
                testResult.put("message", "配置有效，API调用成功");
                testResult.put("fileId", fileId);
                testResult.put("apiResponse", result);
                
                return AjaxResult.success("配置测试成功", testResult);
            } else {
                return AjaxResult.error("配置测试失败：API返回null");
            }
        } catch (Exception e) {
            log.error("测试腾讯文档配置失败", e);
            return AjaxResult.error("配置测试失败: " + e.getMessage());
        }
    }
    
    /**
     * 清除配置（从Redis中删除文档配置）
     * 注意：这不会清除授权令牌，如需清除令牌请访问 /jarvis/tendoc/clearToken
     */
    @Log(title = "腾讯文档配置", businessType = BusinessType.DELETE)
    @DeleteMapping
    public AjaxResult clearConfig() {
        try {
            redisCache.deleteObject(REDIS_KEY_PREFIX + "fileId");
            redisCache.deleteObject(REDIS_KEY_PREFIX + "sheetId");
            redisCache.deleteObject(REDIS_KEY_PREFIX + "startRow");
            
            log.info("H-TF订单自动写入配置已清除");
            
            JSONObject result = new JSONObject();
            result.put("message", "文档配置已清除");
            result.put("hint", "授权令牌未清除。如需清除授权，请访问 /jarvis/tendoc/clearToken");
            
            return AjaxResult.success("配置已清除", result);
        } catch (Exception e) {
            log.error("清除腾讯文档配置失败", e);
            return AjaxResult.error("清除配置失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取文档的工作表列表（用于选择工作表ID）
     * 
     * @param fileId 文件ID
     */
    @GetMapping("/sheets")
    public AjaxResult getSheetList(@RequestParam String fileId) {
        try {
            // 获取访问令牌（从Token服务）
            String accessToken;
            try {
                accessToken = tencentDocTokenService.getValidAccessToken();
            } catch (Exception e) {
                return AjaxResult.error("获取访问令牌失败：" + e.getMessage() + 
                    "。请先访问 /jarvis/tendoc/authUrl 完成授权");
            }
            
            if (accessToken == null || accessToken.isEmpty()) {
                return AjaxResult.error("访问令牌未配置，请先完成腾讯文档授权");
            }
            
            if (fileId == null || fileId.isEmpty()) {
                return AjaxResult.error("文件ID不能为空");
            }
            
            // 调用API获取工作表列表
            log.info("获取腾讯文档工作表列表 - fileId: {}", fileId);
            JSONObject result = tencentDocService.getSheetList(accessToken, fileId);
            
            if (result != null) {
                return AjaxResult.success("获取工作表列表成功", result);
            } else {
                return AjaxResult.error("获取工作表列表失败：API返回null");
            }
        } catch (Exception e) {
            log.error("获取工作表列表失败 - fileId: {}", fileId, e);
            return AjaxResult.error("获取工作表列表失败: " + e.getMessage());
        }
    }
}

