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.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.jarvis.domain.Comment;
import com.ruoyi.jarvis.domain.dto.CommentApiStatistics;
import com.ruoyi.jarvis.domain.dto.CommentStatistics;
import com.ruoyi.jarvis.service.ICommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 评论管理 Controller
 */
@RestController
@RequestMapping("/jarvis/comment")
public class CommentController extends BaseController {

    @Autowired
    private ICommentService commentService;

    /** 获取评论外部服务地址（后端转发，避免前端跨域） */
    @Value("${jarvis.server.fetch-comments.base-url:http://192.168.8.60:5008}")
    private String fetchCommentsBaseUrl;

    /**
     * 查询京东评论列表
     */
    @PreAuthorize("@ss.hasPermi('jarvis:comment:list')")
    @GetMapping("/jd/list")
    public TableDataInfo list(Comment comment) {
        startPage();
        List<Comment> list = commentService.selectCommentList(comment);
        return getDataTable(list);
    }

    /**
     * 导出京东评论列表
     */
    @PreAuthorize("@ss.hasPermi('jarvis:comment:export')")
    @Log(title = "京东评论", businessType = BusinessType.EXPORT)
    @PostMapping("/jd/export")
    public void export(HttpServletResponse response, Comment comment) {
        List<Comment> list = commentService.selectCommentList(comment);
        ExcelUtil<Comment> util = new ExcelUtil<Comment>(Comment.class);
        util.exportExcel(response, list, "京东评论数据");
    }

    /**
     * 获取京东评论详细信息
     */
    @PreAuthorize("@ss.hasPermi('jarvis:comment:query')")
    @GetMapping("/jd/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(commentService.selectCommentById(id));
    }

    /**
     * 修改评论使用状态
     */
    @PreAuthorize("@ss.hasPermi('jarvis:comment:edit')")
    @Log(title = "评论管理", businessType = BusinessType.UPDATE)
    @PutMapping("/jd")
    public AjaxResult edit(@RequestBody Comment comment) {
        return toAjax(commentService.updateCommentIsUse(comment));
    }

    /**
     * 删除评论
     */
    @PreAuthorize("@ss.hasPermi('jarvis:comment:remove')")
    @Log(title = "评论管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/jd/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(commentService.deleteCommentByIds(ids));
    }

    /**
     * 重置评论使用状态（按商品ID）
     */
    @PreAuthorize("@ss.hasPermi('jarvis:comment:edit')")
    @Log(title = "评论管理", businessType = BusinessType.UPDATE)
    @PutMapping("/jd/reset/{productId}")
    public AjaxResult resetByProductId(@PathVariable String productId) {
        return toAjax(commentService.resetCommentIsUseByProductId(productId));
    }

    /**
     * 获取评论统计信息
     */
    @PreAuthorize("@ss.hasPermi('jarvis:comment:list')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics(@RequestParam(required = false) String source) {
        List<CommentStatistics> statistics = commentService.getCommentStatistics(source);
        return success(statistics);
    }

    /**
     * 获取接口调用统计
     */
    @PreAuthorize("@ss.hasPermi('jarvis:comment:list')")
    @GetMapping("/api/statistics")
    public AjaxResult getApiStatistics(
            @RequestParam(required = false) String apiType,
            @RequestParam(required = false) String productType,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        List<CommentApiStatistics> statistics = commentService.getApiStatistics(apiType, productType, startDate, endDate);
        return success(statistics);
    }

    /**
     * 获取Redis产品类型映射（京东）
     */
    @PreAuthorize("@ss.hasPermi('jarvis:comment:list')")
    @GetMapping("/redis/jd/map")
    public AjaxResult getJdProductTypeMap() {
        Map<String, String> map = commentService.getJdProductTypeMap();
        return success(map);
    }

    /**
     * 获取Redis产品类型映射（淘宝）
     */
    @PreAuthorize("@ss.hasPermi('jarvis:comment:list')")
    @GetMapping("/redis/tb/map")
    public AjaxResult getTbProductTypeMap() {
        Map<String, String> map = commentService.getTbProductTypeMap();
        return success(map);
    }

    /**
     * 获取评论（后端转发到外部服务，避免前端跨域）
     * 请求转发至：GET {fetch-comments.base-url}/fetch_comments?product_id=xxx
     */
    @PreAuthorize("@ss.hasPermi('jarvis:comment:list')")
    @Log(title = "评论管理", businessType = BusinessType.OTHER)
    @GetMapping("/fetch-comments")
    public AjaxResult fetchComments(@RequestParam("product_id") String productId) {
        if (StringUtils.isBlank(productId)) {
            return error("商品ID(product_id)不能为空");
        }
        try {
            String url = fetchCommentsBaseUrl + "/fetch_comments";
            String param = "product_id=" + java.net.URLEncoder.encode(productId.trim(), "UTF-8");
            HttpUtils.sendGet(url, param);
            return success();
        } catch (Exception e) {
            return error("调用获取评论接口失败: " + e.getMessage());
        }
    }
}

