package com.ruoyi.web.controller.jarvis;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.jarvis.service.ISocialMediaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 小红书/抖音内容生成Controller
 * 
 * @author ruoyi
 * @date 2025-01-XX
 */
@RestController
@RequestMapping("/jarvis/social-media")
public class SocialMediaController extends BaseController
{
    @Autowired
    private ISocialMediaService socialMediaService;

    /**
     * 提取关键词
     */
    @PostMapping("/extract-keywords")
    public AjaxResult extractKeywords(@RequestBody Map<String, Object> request)
    {
        try {
            String productName = (String) request.get("productName");
            if (productName == null || productName.trim().isEmpty()) {
                return AjaxResult.error("商品名称不能为空");
            }
            
            Map<String, Object> result = socialMediaService.extractKeywords(productName);
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("提取关键词失败", e);
            return AjaxResult.error("提取关键词失败: " + e.getMessage());
        }
    }

    /**
     * 生成文案
     */
    @PostMapping("/generate-content")
    public AjaxResult generateContent(@RequestBody Map<String, Object> request)
    {
        try {
            String productName = (String) request.get("productName");
            if (productName == null || productName.trim().isEmpty()) {
                return AjaxResult.error("商品名称不能为空");
            }
            
            Object originalPriceObj = request.get("originalPrice");
            Object finalPriceObj = request.get("finalPrice");
            String keywords = (String) request.get("keywords");
            String style = (String) request.getOrDefault("style", "both");
            
            Map<String, Object> result = socialMediaService.generateContent(
                productName, originalPriceObj, finalPriceObj, keywords, style
            );
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("生成文案失败", e);
            return AjaxResult.error("生成文案失败: " + e.getMessage());
        }
    }

    /**
     * 一键生成完整内容（关键词 + 文案 + 图片）
     */
    @Log(title = "小红书/抖音内容生成", businessType = BusinessType.OTHER)
    @PostMapping("/generate-complete")
    public AjaxResult generateComplete(@RequestBody Map<String, Object> request)
    {
        try {
            String productImageUrl = (String) request.get("productImageUrl");
            String productName = (String) request.get("productName");
            if (productName == null || productName.trim().isEmpty()) {
                return AjaxResult.error("商品名称不能为空");
            }
            
            Object originalPriceObj = request.get("originalPrice");
            Object finalPriceObj = request.get("finalPrice");
            String style = (String) request.getOrDefault("style", "both");
            
            Map<String, Object> result = socialMediaService.generateCompleteContent(
                productImageUrl, productName, originalPriceObj, finalPriceObj, style
            );
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("生成完整内容失败", e);
            return AjaxResult.error("生成完整内容失败: " + e.getMessage());
        }
    }

    /**
     * 获取提示词模板列表
     */
    @GetMapping("/prompt/list")
    public AjaxResult listPromptTemplates()
    {
        try {
            return socialMediaService.listPromptTemplates();
        } catch (Exception e) {
            logger.error("获取提示词模板列表失败", e);
            return AjaxResult.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取单个提示词模板
     */
    @GetMapping("/prompt/{key}")
    public AjaxResult getPromptTemplate(@PathVariable String key)
    {
        try {
            return socialMediaService.getPromptTemplate(key);
        } catch (Exception e) {
            logger.error("获取提示词模板失败", e);
            return AjaxResult.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 保存提示词模板
     */
    @Log(title = "保存提示词模板", businessType = BusinessType.UPDATE)
    @PostMapping("/prompt/save")
    public AjaxResult savePromptTemplate(@RequestBody Map<String, Object> request)
    {
        try {
            return socialMediaService.savePromptTemplate(request);
        } catch (Exception e) {
            logger.error("保存提示词模板失败", e);
            return AjaxResult.error("保存失败: " + e.getMessage());
        }
    }

    /**
     * 删除提示词模板（恢复默认）
     */
    @Log(title = "删除提示词模板", businessType = BusinessType.DELETE)
    @DeleteMapping("/prompt/{key}")
    public AjaxResult deletePromptTemplate(@PathVariable String key)
    {
        try {
            return socialMediaService.deletePromptTemplate(key);
        } catch (Exception e) {
            logger.error("删除提示词模板失败", e);
            return AjaxResult.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 列出多套大模型接入配置及当前激活 id
     */
    @GetMapping("/llm-config")
    public AjaxResult listLlmProfiles()
    {
        try {
            return socialMediaService.listLlmProfiles();
        } catch (Exception e) {
            logger.error("列出大模型接入配置失败", e);
            return AjaxResult.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取单套配置（编辑）
     */
    @GetMapping("/llm-config/profiles/{id}")
    public AjaxResult getLlmProfile(@PathVariable("id") String id)
    {
        try {
            return socialMediaService.getLlmProfile(id);
        } catch (Exception e) {
            logger.error("获取大模型接入配置失败", e);
            return AjaxResult.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 新增一套配置
     */
    @Log(title = "新增大模型接入配置", businessType = BusinessType.INSERT)
    @PostMapping("/llm-config/profiles")
    public AjaxResult createLlmProfile(@RequestBody Map<String, Object> request)
    {
        try {
            return socialMediaService.createLlmProfile(request);
        } catch (Exception e) {
            logger.error("新增大模型接入配置失败", e);
            return AjaxResult.error("保存失败: " + e.getMessage());
        }
    }

    /**
     * 更新一套配置
     */
    @Log(title = "更新大模型接入配置", businessType = BusinessType.UPDATE)
    @PutMapping("/llm-config/profiles/{id}")
    public AjaxResult updateLlmProfile(@PathVariable("id") String id, @RequestBody Map<String, Object> request)
    {
        try {
            return socialMediaService.updateLlmProfile(id, request);
        } catch (Exception e) {
            logger.error("更新大模型接入配置失败", e);
            return AjaxResult.error("保存失败: " + e.getMessage());
        }
    }

    /**
     * 删除一套配置
     */
    @Log(title = "删除大模型接入配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/llm-config/profiles/{id}")
    public AjaxResult deleteLlmProfile(@PathVariable("id") String id)
    {
        try {
            return socialMediaService.deleteLlmProfile(id);
        } catch (Exception e) {
            logger.error("删除大模型接入配置失败", e);
            return AjaxResult.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 激活指定配置为当前使用
     */
    @Log(title = "激活大模型接入配置", businessType = BusinessType.UPDATE)
    @PutMapping("/llm-config/active/{id}")
    public AjaxResult setActiveLlmProfile(@PathVariable("id") String id)
    {
        try {
            return socialMediaService.setActiveLlmProfile(id);
        } catch (Exception e) {
            logger.error("激活大模型接入配置失败", e);
            return AjaxResult.error("操作失败: " + e.getMessage());
        }
    }

    /**
     * 取消激活（Jarvis 使用 yml 默认 Ollama）
     */
    @Log(title = "取消激活大模型接入配置", businessType = BusinessType.UPDATE)
    @DeleteMapping("/llm-config/active")
    public AjaxResult clearActiveLlmProfile()
    {
        try {
            return socialMediaService.clearActiveLlmProfile();
        } catch (Exception e) {
            logger.error("取消激活大模型接入配置失败", e);
            return AjaxResult.error("操作失败: " + e.getMessage());
        }
    }

    /**
     * 清空所有套及旧版单键
     */
    @Log(title = "清空大模型接入配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/llm-config")
    public AjaxResult resetAllLlmConfig()
    {
        try {
            return socialMediaService.resetAllLlmConfig();
        } catch (Exception e) {
            logger.error("清空大模型接入配置失败", e);
            return AjaxResult.error("清除失败: " + e.getMessage());
        }
    }

    /**
     * 大模型连通测试（转发 Jarvis，默认问题 1+1）
     */
    @Log(title = "大模型连通测试", businessType = BusinessType.OTHER)
    @PostMapping("/llm-config/test")
    public AjaxResult testLlmProfile(@RequestBody(required = false) Map<String, Object> request)
    {
        try {
            return socialMediaService.testLlmProfile(request);
        } catch (Exception e) {
            logger.error("大模型连通测试失败", e);
            return AjaxResult.error("测试失败: " + e.getMessage());
        }
    }

    /**
     * 闲鱼文案(手动)：根据标题+可选型号生成代下单、教你下单文案，不依赖JD接口
     */
    @Log(title = "闲鱼文案(手动)生成", businessType = BusinessType.OTHER)
    @PostMapping("/xianyu-wenan/generate")
    public AjaxResult generateXianyuWenan(@RequestBody Map<String, Object> request)
    {
        try {
            Map<String, Object> result = socialMediaService.generateXianyuWenan(request);
            if (Boolean.TRUE.equals(result.get("success"))) {
                return AjaxResult.success(result);
            }
            return AjaxResult.error((String) result.get("error"));
        } catch (Exception e) {
            logger.error("闲鱼文案生成失败", e);
            return AjaxResult.error("生成失败: " + e.getMessage());
        }
    }
}

