package com.example.demo.service;

import java.time.LocalDateTime;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.example.demo.model.WorkflowVideo;
import com.example.demo.repository.WorkflowVideoRepository;

@Service
public class WorkflowVideoService {

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

    @Autowired
    private WorkflowVideoRepository repository;

    @Autowired
    private CosService cosService;

    /** 获取所有已启用的视频（公开接口用） */
    public List<WorkflowVideo> getActiveVideos() {
        return repository.findByIsActiveTrueOrderBySortOrderAscCreatedAtDesc();
    }

    /** 管理后台分页列表 */
    public Page<WorkflowVideo> getAllVideos(int page, int size) {
        return repository.findAllByOrderBySortOrderAscCreatedAtDesc(PageRequest.of(page, size));
    }

    /** 获取单个视频详情 */
    public WorkflowVideo getById(Long id) {
        return repository.findById(id)
                .orElseThrow(() -> new RuntimeException("工作流视频不存在: " + id));
    }

    /** 创建视频记录 */
    public WorkflowVideo create(WorkflowVideo video) {
        video.setCreatedAt(LocalDateTime.now());
        video.setUpdatedAt(LocalDateTime.now());
        return repository.save(video);
    }

    /** 更新视频记录 */
    public WorkflowVideo update(Long id, WorkflowVideo data) {
        WorkflowVideo existing = getById(id);
        if (data.getTitle() != null) existing.setTitle(data.getTitle());
        if (data.getDescription() != null) existing.setDescription(data.getDescription());
        if (data.getVideoUrl() != null) existing.setVideoUrl(data.getVideoUrl());
        if (data.getThumbnailUrl() != null) existing.setThumbnailUrl(data.getThumbnailUrl());
        if (data.getTags() != null) existing.setTags(data.getTags());
        if (data.getSortOrder() != null) existing.setSortOrder(data.getSortOrder());
        if (data.getIsActive() != null) existing.setIsActive(data.getIsActive());
        existing.setUpdatedAt(LocalDateTime.now());
        return repository.save(existing);
    }

    /** 删除视频 */
    public void delete(Long id) {
        if (!repository.existsById(id)) {
            throw new RuntimeException("工作流视频不存在: " + id);
        }
        repository.deleteById(id);
        logger.info("已删除工作流视频: {}", id);
    }

    /** 上传视频文件到 COS，返回访问 URL */
    public String uploadVideo(MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            String extension = ".mp4";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf('.'));
            }
            String filename = "workflow_" + System.currentTimeMillis() + extension;
            String url = cosService.uploadBytes(file.getBytes(), filename, file.getContentType());
            if (url == null) {
                throw new RuntimeException("COS 上传失败");
            }
            logger.info("工作流视频上传成功: {}", url);
            return url;
        } catch (Exception e) {
            logger.error("工作流视频上传失败", e);
            throw new RuntimeException("视频上传失败: " + e.getMessage());
        }
    }

    /** 上传缩略图到 COS，返回访问 URL */
    public String uploadThumbnail(MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            String extension = ".jpg";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf('.'));
            }
            String filename = "workflow_thumb_" + System.currentTimeMillis() + extension;
            String url = cosService.uploadBytes(file.getBytes(), filename, file.getContentType());
            if (url == null) {
                throw new RuntimeException("COS 上传失败");
            }
            return url;
        } catch (Exception e) {
            logger.error("工作流缩略图上传失败", e);
            throw new RuntimeException("缩略图上传失败: " + e.getMessage());
        }
    }
}
