package com.ruoyi.jarvis.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.jarvis.service.ISocialMediaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 小红书/抖音内容生成Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-XX
 */
@Service
public class SocialMediaServiceImpl implements ISocialMediaService 
{
    private static final Logger log = LoggerFactory.getLogger(SocialMediaServiceImpl.class);

    @Autowired(required = false)
    private StringRedisTemplate redisTemplate;

    @Value("${jarvis.server.jarvis-java.base-url:http://127.0.0.1:6666}")
    private String jarvisBaseUrl;

    // Redis Key 前缀
    private static final String REDIS_KEY_PREFIX = "social_media:prompt:";

    // 模板键名列表
    private static final String[] TEMPLATE_KEYS = {
        "keywords",
        "content:xhs",
        "content:douyin",
        "content:both"
    };

    // 模板说明
    private static final Map<String, String> TEMPLATE_DESCRIPTIONS = new HashMap<String, String>() {{
        put("keywords", "关键词提取提示词模板\n占位符：%s - 商品名称");
        put("content:xhs", "小红书文案生成提示词模板\n占位符：%s - 商品名称，%s - 价格信息，%s - 关键词信息");
        put("content:douyin", "抖音文案生成提示词模板\n占位符：%s - 商品名称，%s - 价格信息，%s - 关键词信息");
        put("content:both", "通用文案生成提示词模板\n占位符：%s - 商品名称，%s - 价格信息，%s - 关键词信息");
    }};

    /**
     * 提取商品标题关键词
     */
    @Override
    public Map<String, Object> extractKeywords(String productName) {
        Map<String, Object> result = new HashMap<>();
        
        if (StringUtils.isEmpty(productName)) {
            result.put("success", false);
            result.put("error", "商品名称不能为空");
            return result;
        }

        try {
            // 调用 jarvis_java 的接口
            String url = jarvisBaseUrl + "/jarvis/social-media/extract-keywords";
            JSONObject requestBody = new JSONObject();
            requestBody.put("productName", productName);
            
            log.info("调用jarvis_java提取关键词接口，URL: {}, 参数: {}", url, requestBody.toJSONString());
            String response = HttpUtils.sendJsonPost(url, requestBody.toJSONString());
            log.info("jarvis_java响应: {}", response);
            
            if (StringUtils.isEmpty(response)) {
                throw new Exception("jarvis_java返回空结果");
            }
            
            // 解析响应
            Object parsed = JSON.parse(response);
            if (parsed instanceof JSONObject) {
                JSONObject jsonResponse = (JSONObject) parsed;
                if (jsonResponse.getInteger("code") == 200) {
                    Object data = jsonResponse.get("data");
                    if (data instanceof Map) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> dataMap = (Map<String, Object>) data;
                        return dataMap;
                    }
                } else {
                    String msg = jsonResponse.getString("msg");
                    result.put("success", false);
                    result.put("error", msg != null ? msg : "提取关键词失败");
                    return result;
                }
            }
            
            result.put("success", false);
            result.put("error", "响应格式错误");
            return result;
            
        } catch (Exception e) {
            log.error("提取关键词失败", e);
            result.put("success", false);
            result.put("error", "提取关键词失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 生成文案
     */
    @Override
    public Map<String, Object> generateContent(String productName, Object originalPrice, 
                                                Object finalPrice, String keywords, String style) {
        Map<String, Object> result = new HashMap<>();
        
        if (StringUtils.isEmpty(productName)) {
            result.put("success", false);
            result.put("error", "商品名称不能为空");
            return result;
        }

        try {
            // 调用 jarvis_java 的接口
            String url = jarvisBaseUrl + "/jarvis/social-media/generate-content";
            JSONObject requestBody = new JSONObject();
            requestBody.put("productName", productName);
            if (originalPrice != null) {
                requestBody.put("originalPrice", parseDouble(originalPrice));
            }
            if (finalPrice != null) {
                requestBody.put("finalPrice", parseDouble(finalPrice));
            }
            if (StringUtils.isNotEmpty(keywords)) {
                requestBody.put("keywords", keywords);
            }
            if (StringUtils.isNotEmpty(style)) {
                requestBody.put("style", style);
            }
            
            log.info("调用jarvis_java生成文案接口，URL: {}, 参数: {}", url, requestBody.toJSONString());
            String response = HttpUtils.sendJsonPost(url, requestBody.toJSONString());
            log.info("jarvis_java响应: {}", response);
            
            if (StringUtils.isEmpty(response)) {
                throw new Exception("jarvis_java返回空结果");
            }
            
            // 解析响应
            Object parsed = JSON.parse(response);
            if (parsed instanceof JSONObject) {
                JSONObject jsonResponse = (JSONObject) parsed;
                if (jsonResponse.getInteger("code") == 200) {
                    Object data = jsonResponse.get("data");
                    if (data instanceof Map) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> dataMap = (Map<String, Object>) data;
                        return dataMap;
                    }
                } else {
                    String msg = jsonResponse.getString("msg");
                    result.put("success", false);
                    result.put("error", msg != null ? msg : "生成文案失败");
                    return result;
                }
            }
            
            result.put("success", false);
            result.put("error", "响应格式错误");
            return result;
            
        } catch (Exception e) {
            log.error("生成文案失败", e);
            result.put("success", false);
            result.put("error", "生成文案失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 一键生成完整内容（关键词 + 文案 + 图片）
     */
    @Override
    public Map<String, Object> generateCompleteContent(String productImageUrl, String productName,
                                                        Object originalPrice, Object finalPrice, String style) {
        Map<String, Object> result = new HashMap<>();
        
        if (StringUtils.isEmpty(productName)) {
            result.put("success", false);
            result.put("error", "商品名称不能为空");
            return result;
        }

        try {
            // 调用 jarvis_java 的接口
            String url = jarvisBaseUrl + "/jarvis/social-media/generate-complete";
            JSONObject requestBody = new JSONObject();
            if (StringUtils.isNotEmpty(productImageUrl)) {
                requestBody.put("productImageUrl", productImageUrl);
            }
            requestBody.put("productName", productName);
            if (originalPrice != null) {
                requestBody.put("originalPrice", parseDouble(originalPrice));
            }
            if (finalPrice != null) {
                requestBody.put("finalPrice", parseDouble(finalPrice));
            }
            if (StringUtils.isNotEmpty(style)) {
                requestBody.put("style", style);
            }
            
            log.info("调用jarvis_java生成完整内容接口，URL: {}, 参数: {}", url, requestBody.toJSONString());
            String response = HttpUtils.sendJsonPost(url, requestBody.toJSONString());
            log.info("jarvis_java响应: {}", response);
            
            if (StringUtils.isEmpty(response)) {
                throw new Exception("jarvis_java返回空结果");
            }
            
            // 解析响应
            Object parsed = JSON.parse(response);
            if (parsed instanceof JSONObject) {
                JSONObject jsonResponse = (JSONObject) parsed;
                if (jsonResponse.getInteger("code") == 200) {
                    Object data = jsonResponse.get("data");
                    if (data instanceof Map) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> dataMap = (Map<String, Object>) data;
                        return dataMap;
                    }
                } else {
                    String msg = jsonResponse.getString("msg");
                    result.put("success", false);
                    result.put("error", msg != null ? msg : "生成完整内容失败");
                    return result;
                }
            }
            
            result.put("success", false);
            result.put("error", "响应格式错误");
            return result;
            
        } catch (Exception e) {
            log.error("生成完整内容失败", e);
            result.put("success", false);
            result.put("error", "生成完整内容失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 获取提示词模板列表
     */
    @Override
    public AjaxResult listPromptTemplates() {
        try {
            Map<String, Object> templates = new HashMap<>();
            
            for (String key : TEMPLATE_KEYS) {
                Map<String, Object> templateInfo = new HashMap<>();
                templateInfo.put("key", key);
                templateInfo.put("description", TEMPLATE_DESCRIPTIONS.get(key));
                
                String template = getTemplateFromRedis(key);
                templateInfo.put("template", template);
                templateInfo.put("isDefault", template == null);
                
                templates.put(key, templateInfo);
            }
            
            return AjaxResult.success(templates);
        } catch (Exception e) {
            log.error("获取提示词模板列表失败", e);
            return AjaxResult.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取单个提示词模板
     */
    @Override
    public AjaxResult getPromptTemplate(String key) {
        try {
            if (!isValidKey(key)) {
                return AjaxResult.error("无效的模板键名");
            }
            
            String template = getTemplateFromRedis(key);
            Map<String, Object> data = new HashMap<>();
            data.put("key", key);
            data.put("description", TEMPLATE_DESCRIPTIONS.get(key));
            data.put("template", template);
            data.put("isDefault", template == null);
            
            return AjaxResult.success(data);
        } catch (Exception e) {
            log.error("获取提示词模板失败", e);
            return AjaxResult.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 保存提示词模板
     */
    @Override
    public AjaxResult savePromptTemplate(Map<String, Object> request) {
        try {
            String key = (String) request.get("key");
            String template = (String) request.get("template");
            
            if (!isValidKey(key)) {
                return AjaxResult.error("无效的模板键名");
            }
            
            if (StringUtils.isEmpty(template)) {
                return AjaxResult.error("模板内容不能为空");
            }
            
            if (redisTemplate == null) {
                return AjaxResult.error("Redis未配置，无法保存模板");
            }
            
            String redisKey = REDIS_KEY_PREFIX + key;
            String templateValue = template.trim();
            if (StringUtils.isEmpty(templateValue)) {
                return AjaxResult.error("模板内容不能为空");
            }
            redisTemplate.opsForValue().set(redisKey, templateValue);
            
            log.info("保存提示词模板成功: {}", key);
            return AjaxResult.success("保存成功");
            
        } catch (Exception e) {
            log.error("保存提示词模板失败", e);
            return AjaxResult.error("保存失败: " + e.getMessage());
        }
    }

    /**
     * 删除提示词模板（恢复默认）
     */
    @Override
    public AjaxResult deletePromptTemplate(String key) {
        try {
            if (!isValidKey(key)) {
                return AjaxResult.error("无效的模板键名");
            }
            
            if (redisTemplate == null) {
                return AjaxResult.error("Redis未配置，无法删除模板");
            }
            
            String redisKey = REDIS_KEY_PREFIX + key;
            redisTemplate.delete(redisKey);
            
            log.info("删除提示词模板成功: {}", key);
            return AjaxResult.success("删除成功，已恢复默认模板");
            
        } catch (Exception e) {
            log.error("删除提示词模板失败", e);
            return AjaxResult.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 从 Redis 获取模板
     */
    private String getTemplateFromRedis(String key) {
        if (redisTemplate == null) {
            return null;
        }
        
        try {
            String redisKey = REDIS_KEY_PREFIX + key;
            String template = redisTemplate.opsForValue().get(redisKey);
            return StringUtils.isNotEmpty(template) ? template : null;
        } catch (Exception e) {
            log.warn("读取Redis模板失败: {}", key, e);
            return null;
        }
    }

    /**
     * 验证模板键名是否有效
     */
    private boolean isValidKey(String key) {
        if (StringUtils.isEmpty(key)) {
            return false;
        }
        for (String validKey : TEMPLATE_KEYS) {
            if (validKey.equals(key)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 解析Double值
     */
    private Double parseDouble(Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof Double) {
            return (Double) value;
        }
        if (value instanceof Number) {
            return ((Number) value).doubleValue();
        }
        try {
            return Double.parseDouble(value.toString());
        } catch (Exception e) {
            return null;
        }
    }
}

