package com.ruoyi.web.controller.publicapi;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.jarvis.domain.dto.CommentCallHistory;
import com.ruoyi.jarvis.service.ICommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 评论生成 公共接口（免登录）
 */
@Anonymous
@RestController
@RequestMapping("/public/comment")
public class CommentPublicController extends BaseController {

    private static final String SKEY = "2192057370ef8140c201079969c956a3";

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

    @Value("${jarvis.server.jarvis-java.jd-api-path:/jd}")
    private String jdApiPath;

    @Autowired(required = false)
    private ICommentService commentService;

    /**
     * 获取JD接口基础URL
     */
    private String getJdBase() {
        return jarvisJavaBaseUrl + jdApiPath;
    }

    /**
     * 获取可选型号/类型（示例）
     */
    @GetMapping("/types")
    public AjaxResult types() {
        boolean success = false;
        try {
            String url = getJdBase() + "/comment/types?skey=" + SKEY;
            String result = HttpUtils.sendGet(url);
            Object parsed = JSON.parse(result);
            success = true;
            return AjaxResult.success(parsed);
        } catch (Exception e) {
            return AjaxResult.error("types failed: " + e.getMessage());
        } finally {
            // 记录接口调用统计
            if (commentService != null) {
                commentService.recordApiCall("jd", "types", success);
            }
        }
    }

    /**
     * 生成评论（示例实现：返回两条通用好评与空图片列表）
     * 入参：productType（型号/类型）
     */
    @PostMapping("/generate")
    public AjaxResult generate(@RequestBody Map<String, String> body, HttpServletRequest request) {
        boolean success = false;
        String productType = null;
        String clientIp = getClientIp(request);
        try {
            String url = getJdBase() + "/comment/generate";
            JSONObject param = new JSONObject();
            param.put("skey", SKEY);
            if (body != null && body.get("productType") != null) {
                productType = body.get("productType");
                param.put("productType", productType);
            }
            String result = HttpUtils.sendJsonPost(url, param.toJSONString());
            Object parsed = JSON.parse(result);
            success = true;
            return AjaxResult.success(parsed);
        } catch (Exception e) {
            return AjaxResult.error("generate failed: " + e.getMessage());
        } finally {
            // 记录接口调用统计和历史
            if (commentService != null && productType != null) {
                commentService.recordApiCall("jd", productType, success);
                commentService.recordApiCallHistory(productType, clientIp);
            }
        }
    }

    /**
     * 获取当前IP地址
     */
    @GetMapping("/ip")
    public AjaxResult getIp(HttpServletRequest request) {
        try {
            String ip = getClientIp(request);
            Map<String, String> result = new HashMap<>();
            result.put("ip", ip);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("获取IP失败: " + e.getMessage());
        }
    }

    /**
     * 获取使用统计（今天/7天/30天/累计）
     */
    @GetMapping("/usage-statistics")
    public AjaxResult getUsageStatistics() {
        try {
            if (commentService != null) {
                Map<String, Long> statistics = commentService.getUsageStatistics();
                return AjaxResult.success(statistics);
            } else {
                Map<String, Long> statistics = new HashMap<>();
                statistics.put("today", 0L);
                statistics.put("last7Days", 0L);
                statistics.put("last30Days", 0L);
                statistics.put("total", 0L);
                return AjaxResult.success(statistics);
            }
        } catch (Exception e) {
            return AjaxResult.error("获取使用统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取历史记录
     */
    @GetMapping("/history")
    public TableDataInfo getHistory(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                     @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
        try {
            if (commentService != null) {
                List<CommentCallHistory> historyList = commentService.getApiCallHistory(pageNum, pageSize);
                TableDataInfo dataTable = new TableDataInfo();
                dataTable.setCode(200);
                dataTable.setMsg("查询成功");
                dataTable.setRows(historyList);
                dataTable.setTotal(historyList.size()); // 注意：这里返回的是当前页的数量，实际总数可能需要单独查询
                return dataTable;
            } else {
                TableDataInfo dataTable = new TableDataInfo();
                dataTable.setCode(200);
                dataTable.setMsg("查询成功");
                dataTable.setRows(new ArrayList<>());
                dataTable.setTotal(0);
                return dataTable;
            }
        } catch (Exception e) {
            TableDataInfo dataTable = new TableDataInfo();
            dataTable.setCode(500);
            dataTable.setMsg("获取历史记录失败: " + e.getMessage());
            return dataTable;
        }
    }

    /**
     * 获取客户端真实IP地址
     * 考虑代理和负载均衡的情况
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP
        if (ip != null && ip.contains(",")) {
            ip = ip.substring(0, ip.indexOf(",")).trim();
        }
        return ip;
    }

}


