package com.example.demo.controller;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.example.demo.model.WorkflowVideo;
import com.example.demo.service.WorkflowVideoService;

/**
 * 优质工作流视频 API 控制器
 * 公开接口：/api/workflow-videos
 * 管理员接口：/api/admin/workflow-videos
 */
@RestController
public class WorkflowVideoApiController {

    private static final Logger logger = LoggerFactory.getLogger(WorkflowVideoApiController.class);

    @Autowired
    private WorkflowVideoService workflowVideoService;

    // ==================== 公开接口 ====================

    /**
     * 获取已启用的工作流视频列表（无需认证）
     */
    @GetMapping("/api/workflow-videos")
    public ResponseEntity<Map<String, Object>> getActiveVideos() {
        Map<String, Object> response = new HashMap<>();
        try {
            List<WorkflowVideo> videos = workflowVideoService.getActiveVideos();
            response.put("success", true);
            response.put("data", videos);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取工作流视频列表失败", e);
            response.put("success", false);
            response.put("message", "获取列表失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    // ==================== 管理员接口 ====================

    /**
     * 管理后台 - 获取所有工作流视频（分页）
     */
    @GetMapping("/api/admin/workflow-videos")
    public ResponseEntity<Map<String, Object>> getAllVideos(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        Map<String, Object> response = new HashMap<>();
        try {
            Page<WorkflowVideo> videos = workflowVideoService.getAllVideos(page, size);
            response.put("success", true);
            response.put("data", videos.getContent());
            response.put("totalElements", videos.getTotalElements());
            response.put("totalPages", videos.getTotalPages());
            response.put("currentPage", page);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("管理后台获取工作流视频列表失败", e);
            response.put("success", false);
            response.put("message", "获取列表失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 管理后台 - 创建工作流视频
     */
    @PostMapping("/api/admin/workflow-videos")
    public ResponseEntity<Map<String, Object>> createVideo(@RequestBody WorkflowVideo video) {
        Map<String, Object> response = new HashMap<>();
        try {
            WorkflowVideo created = workflowVideoService.create(video);
            response.put("success", true);
            response.put("data", created);
            response.put("message", "创建成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("创建工作流视频失败", e);
            response.put("success", false);
            response.put("message", "创建失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 管理后台 - 更新工作流视频
     */
    @PutMapping("/api/admin/workflow-videos/{id}")
    public ResponseEntity<Map<String, Object>> updateVideo(
            @PathVariable Long id,
            @RequestBody WorkflowVideo video) {
        Map<String, Object> response = new HashMap<>();
        try {
            WorkflowVideo updated = workflowVideoService.update(id, video);
            response.put("success", true);
            response.put("data", updated);
            response.put("message", "更新成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("更新工作流视频失败", e);
            response.put("success", false);
            response.put("message", "更新失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 管理后台 - 删除工作流视频
     */
    @DeleteMapping("/api/admin/workflow-videos/{id}")
    public ResponseEntity<Map<String, Object>> deleteVideo(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        try {
            workflowVideoService.delete(id);
            response.put("success", true);
            response.put("message", "删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("删除工作流视频失败", e);
            response.put("success", false);
            response.put("message", "删除失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 管理后台 - 上传视频文件
     */
    @PostMapping("/api/admin/workflow-videos/upload-video")
    public ResponseEntity<Map<String, Object>> uploadVideo(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        try {
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            String url = workflowVideoService.uploadVideo(file);
            response.put("success", true);
            response.put("url", url);
            response.put("message", "上传成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("上传视频文件失败", e);
            response.put("success", false);
            response.put("message", "上传失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 管理后台 - 上传缩略图
     */
    @PostMapping("/api/admin/workflow-videos/upload-thumbnail")
    public ResponseEntity<Map<String, Object>> uploadThumbnail(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        try {
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            String url = workflowVideoService.uploadThumbnail(file);
            response.put("success", true);
            response.put("url", url);
            response.put("message", "上传成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("上传缩略图失败", e);
            response.put("success", false);
            response.put("message", "上传失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}
