package com.moka.gdtauto.service.impl;

import java.time.LocalDateTime;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moka.gdtauto.entity.OssFile;
import com.moka.gdtauto.mapper.OssFileMapper;
import com.moka.gdtauto.service.OssFileService;
import com.moka.gdtauto.service.TencentAssetService;
import com.moka.gdtauto.util.OssUtil;
import com.moka.gdtauto.util.TencentFileMd5Util;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * OSS文件Service实现类
 *
 * @author moka
 * @since 2026-02-26
 */
@Slf4j
@Service
@AllArgsConstructor
public class OssFileServiceImpl extends ServiceImpl<OssFileMapper, OssFile> implements OssFileService {

    private final OssUtil ossUtil;
    private TencentAssetService tencentAssetService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OssFile uploadFile(MultipartFile file, String folder, String fileType, Integer businessType, Long userId, String userName) {
        try {
            // 验证品牌形象只能上传图片
            if (businessType != null && businessType == 2 && !"image".equals(fileType)) {
                throw new RuntimeException("品牌形象只能上传图片文件");
            }
            String md5 = TencentFileMd5Util.calculateMd5(file.getInputStream());
            // 上传到OSS
            String fileUrl = ossUtil.uploadFile(file, folder);
            
            // 提取对象Key
            String objectKey = extractObjectKey(fileUrl);
            
            // 获取文件信息
            String originalFileName = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFileName != null && originalFileName.contains(".")) {
                fileExtension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
            }
            
            // 保存文件记录
            OssFile ossFile = new OssFile();
            ossFile.setFileName(objectKey);
            ossFile.setOriginalFileName(originalFileName);
            ossFile.setFileType(fileType);
            ossFile.setBusinessType(businessType);
            ossFile.setFileSize(file.getSize());
            ossFile.setFileUrl(fileUrl);
            ossFile.setFileMd5(md5);
            ossFile.setObjectKey(objectKey);
            ossFile.setFolder(folder);
            ossFile.setFileExtension(fileExtension);
            ossFile.setCreatedBy(userId);
            ossFile.setCreatedByName(userName);
            ossFile.setCreatedTime(LocalDateTime.now());
            ossFile.setUpdatedTime(LocalDateTime.now());
            
            save(ossFile);
            if (businessType == 1) {
                tencentAssetService.uploadAsset(ossFile);
                updateById(ossFile);
            }
            
            log.info("文件上传成功，ID: {}, URL: {}", ossFile.getId(), fileUrl);
            return ossFile;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteFile(Long fileId) {
        try {
            OssFile ossFile = getById(fileId);
            if (ossFile == null) {
                log.warn("文件不存在，ID: {}", fileId);
                return false;
            }
            
            // 删除OSS文件
            boolean ossDeleted = ossUtil.deleteFile(ossFile.getFileUrl());
            if (!ossDeleted) {
                log.warn("OSS文件删除失败，但继续删除数据库记录，ID: {}", fileId);
            }
            
            // 删除数据库记录
            boolean dbDeleted = removeById(fileId);
            
            log.info("文件删除成功，ID: {}, OSS删除: {}, DB删除: {}", fileId, ossDeleted, dbDeleted);
            return dbDeleted;
        } catch (Exception e) {
            log.error("文件删除失败，ID: {}", fileId, e);
            throw new RuntimeException("文件删除失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteFiles(Long[] fileIds) {
        boolean allSuccess = true;
        for (Long fileId : fileIds) {
            try {
                boolean success = deleteFile(fileId);
                if (!success) {
                    allSuccess = false;
                }
            } catch (Exception e) {
                log.error("批量删除文件失败，ID: {}", fileId, e);
                allSuccess = false;
            }
        }
        return allSuccess;
    }

    @Override
    public Page<OssFile> listFiles(Long page, Long size, String fileType, Integer businessType, String fileName, Long userId, String sortField, String sortOrder) {
        Page<OssFile> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<OssFile> wrapper = new LambdaQueryWrapper<>();
        
        // 文件类型过滤
        if (fileType != null && !fileType.trim().isEmpty()) {
            wrapper.eq(OssFile::getFileType, fileType);
        }
        
        // 业务分类过滤
        if (businessType != null) {
            wrapper.eq(OssFile::getBusinessType, businessType);
        }
        
        // 文件名模糊查询
        if (fileName != null && !fileName.trim().isEmpty()) {
            wrapper.like(OssFile::getOriginalFileName, fileName);
        }
        
        // 创建人过滤
        if (userId != null) {
            wrapper.eq(OssFile::getCreatedBy, userId);
        }
        
        // 排序逻辑
        if (sortField != null && !sortField.trim().isEmpty()) {
            boolean isAsc = "ascending".equalsIgnoreCase(sortOrder);
            switch (sortField) {
                case "normalCnt":
                    if (isAsc) {
                        wrapper.orderByAsc(OssFile::getNormalCnt);
                    } else {
                        wrapper.orderByDesc(OssFile::getNormalCnt);
                    }
                    break;
                case "deniedCnt":
                    if (isAsc) {
                        wrapper.orderByAsc(OssFile::getDeniedCnt);
                    } else {
                        wrapper.orderByDesc(OssFile::getDeniedCnt);
                    }
                    break;
                default:
                    // 默认按创建时间倒序
                    wrapper.orderByDesc(OssFile::getCreatedTime);
            }
        } else {
            // 没有指定排序时，按创建时间倒序
            wrapper.orderByDesc(OssFile::getCreatedTime);
        }
        
        return page(pageParam, wrapper);
    }

    /**
     * 从URL中提取OSS对象Key
     */
    private String extractObjectKey(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            return "";
        }
        
        if (fileUrl.startsWith("http://") || fileUrl.startsWith("https://")) {
            int lastSlashIndex = fileUrl.indexOf("/", 8);
            if (lastSlashIndex != -1 && lastSlashIndex < fileUrl.length() - 1) {
                return fileUrl.substring(lastSlashIndex + 1);
            }
        }
        
        return fileUrl;
    }
}

