package com.ycwl.basic.controller;

import com.github.pagehelper.PageInfo;
import com.ycwl.basic.model.pc.videoreview.dto.AdminVideoReviewLogReqDTO;
import com.ycwl.basic.model.pc.videoreview.dto.AdminVideoReviewLogRespDTO;
import com.ycwl.basic.model.pc.videoreview.dto.VideoPurchaseCheckReqDTO;
import com.ycwl.basic.model.pc.videoreview.dto.VideoPurchaseCheckRespDTO;
import com.ycwl.basic.model.pc.videoreview.dto.VideoReviewAddReqDTO;
import com.ycwl.basic.model.pc.videoreview.dto.VideoReviewListReqDTO;
import com.ycwl.basic.model.pc.videoreview.dto.VideoReviewRespDTO;
import com.ycwl.basic.model.pc.videoreview.dto.VideoReviewStatisticsRespDTO;
import com.ycwl.basic.service.VideoReviewService;
import com.ycwl.basic.utils.ApiResponse;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;

/**
 * 视频评价Controller
 * 管理端使用,通过token角色控制权限
 */
@Slf4j
@RestController
@RequestMapping("/api/video-review/v1")
public class VideoReviewController {

    @Autowired
    private VideoReviewService videoReviewService;

    /**
     * 新增视频评价
     *
     * @param reqDTO 评价信息
     * @return 评价ID
     */
    @PostMapping("/add")
    public ApiResponse<Long> addReview(@RequestBody VideoReviewAddReqDTO reqDTO) {
        log.info("新增视频评价,videoId: {}", reqDTO.getVideoId());
        Long reviewId = videoReviewService.addReview(reqDTO);
        return ApiResponse.success(reviewId);
    }

    /**
     * 分页查询评价列表
     *
     * @param reqDTO 查询条件
     * @return 分页结果
     */
    @GetMapping("/list")
    public ApiResponse<PageInfo<VideoReviewRespDTO>> getReviewList(VideoReviewListReqDTO reqDTO) {
        log.info("查询视频评价列表,pageNum: {}, pageSize: {}", reqDTO.getPageNum(), reqDTO.getPageSize());
        PageInfo<VideoReviewRespDTO> pageInfo = videoReviewService.getReviewList(reqDTO);
        return ApiResponse.success(pageInfo);
    }

    /**
     * 管理后台分页查询评价日志
     * 提供更详细的管理信息,包括评价人账号、机位评价统计等
     *
     * @param reqDTO 查询条件
     * @return 分页结果
     */
    @GetMapping("/admin/logs")
    public ApiResponse<PageInfo<AdminVideoReviewLogRespDTO>> getAdminReviewLogList(AdminVideoReviewLogReqDTO reqDTO) {
        log.info("管理后台查询评价日志,pageNum: {}, pageSize: {}", reqDTO.getPageNum(), reqDTO.getPageSize());
        PageInfo<AdminVideoReviewLogRespDTO> pageInfo = videoReviewService.getAdminReviewLogList(reqDTO);
        return ApiResponse.success(pageInfo);
    }

    /**
     * 获取评价统计数据
     *
     * @return 统计结果
     */
    @GetMapping("/statistics")
    public ApiResponse<VideoReviewStatisticsRespDTO> getStatistics() {
        log.info("获取视频评价统计数据");
        VideoReviewStatisticsRespDTO statistics = videoReviewService.getStatistics();
        return ApiResponse.success(statistics);
    }

    /**
     * 导出评价数据到Excel
     *
     * @param reqDTO 查询条件
     * @param response HTTP响应
     */
    @GetMapping("/export")
    public void exportReviews(VideoReviewListReqDTO reqDTO, HttpServletResponse response) {
        log.info("导出视频评价数据");

        try {
            // 设置响应头
            String fileName = "video_reviews_" + System.currentTimeMillis() + ".xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 导出数据
            videoReviewService.exportReviews(reqDTO, response.getOutputStream());

            response.getOutputStream().flush();
        } catch (IOException e) {
            log.error("导出视频评价数据失败", e);
            throw new RuntimeException("导出失败: " + e.getMessage());
        }
    }

    /**
     * 检查视频是否已被购买
     * 购买条件：
     * 1. 直接购买视频（order_item中goods_type=0且goods_id=视频id）
     * 2. 购买整个模板（order的face_id与video关联的task的face_id相同，goods_type=-1，goods_id为video的templateId）
     *
     * @param reqDTO 查询条件
     * @return 购买状态及订单ID列表
     */
    @PostMapping("/check-purchase")
    public ApiResponse<VideoPurchaseCheckRespDTO> checkVideoPurchase(@RequestBody VideoPurchaseCheckReqDTO reqDTO) {
        log.info("检查视频购买状态,videoId: {}", reqDTO.getVideoId());
        VideoPurchaseCheckRespDTO respDTO = videoReviewService.checkVideoPurchase(reqDTO);
        return ApiResponse.success(respDTO);
    }
}
