package org.dromara.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.oss.core.OssClient;
import org.dromara.common.oss.entity.UploadResult;
import org.dromara.common.oss.factory.OssFactory;
import org.dromara.member.domain.AppFile;
import org.dromara.member.domain.bo.AppFileBo;
import org.dromara.member.domain.vo.AppFileVo;
import org.dromara.member.exception.FileException;
import org.dromara.member.mapper.AppFileMapper;
import org.dromara.member.service.AppFileService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * App端文件信息Service业务层处理
 *
 * @author pengles
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AppFileServiceImpl implements AppFileService {

    private final AppFileMapper baseMapper;

    /**
     * 查询App端文件信息
     */
    @Override
    public AppFileVo queryById(Long fileId) {
        return baseMapper.selectVoById(fileId);
    }

    /**
     * 查询App端文件信息列表
     */
    @Override
    public TableDataInfo<AppFileVo> queryPageList(AppFileBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppFile> lqw = buildQueryWrapper(bo);
        Page<AppFileVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询App端文件信息列表
     */
    @Override
    public List<AppFileVo> queryList(AppFileBo bo) {
        LambdaQueryWrapper<AppFile> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppFile> buildQueryWrapper(AppFileBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppFile> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, AppFile::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getFileName()), AppFile::getFileName, bo.getFileName());
        lqw.like(StringUtils.isNotBlank(bo.getOriginalName()), AppFile::getOriginalName, bo.getOriginalName());
        lqw.eq(StringUtils.isNotBlank(bo.getFileType()), AppFile::getFileType, bo.getFileType());
        lqw.eq(StringUtils.isNotBlank(bo.getFileSuffix()), AppFile::getFileSuffix, bo.getFileSuffix());
        lqw.eq(bo.getFileCategory() != null, AppFile::getFileCategory, bo.getFileCategory());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), AppFile::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getIsPublic()), AppFile::getIsPublic, bo.getIsPublic());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
                AppFile::getCreateTime, params.get("beginTime"), params.get("endTime"));
        lqw.orderByDesc(AppFile::getCreateTime);
        return lqw;
    }

    /**
     * 新增App端文件信息
     */
    @Override
    public Boolean insertByBo(AppFileBo bo) {
        AppFile add = BeanUtil.toBean(bo, AppFile.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setFileId(add.getFileId());
        }
        return flag;
    }

    /**
     * 修改App端文件信息
     */
    @Override
    public Boolean updateByBo(AppFileBo bo) {
        AppFile update = BeanUtil.toBean(bo, AppFile.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppFile entity) {
        // 可以添加一些业务校验逻辑
    }

    /**
     * 批量删除App端文件信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 可以添加删除前的校验逻辑
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 上传文件
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppFileVo uploadFile(MultipartFile file, Long userId, Integer fileCategory) {
        if (file.isEmpty()) {
            throw FileException.fileEmpty();
        }

        // 检查文件大小（限制为100MB）
        if (file.getSize() > 100 * 1024 * 1024) {
            throw FileException.fileSizeExceeded(100);
        }

        try {
            // 计算文件MD5
            String fileMd5 = DigestUtil.md5Hex(file.getInputStream());

            // 检查文件是否已存在
            AppFileVo existFile = checkFileExists(fileMd5, userId);
            if (existFile != null) {
                return existFile;
            }

            // 上传到OSS
            OssClient ossClient = OssFactory.instance();
            UploadResult uploadResult = ossClient.uploadSuffix(file.getBytes(), getFileSuffix(file.getOriginalFilename()), file.getContentType());

            // 保存文件信息
            AppFile appFile = new AppFile();
            appFile.setUserId(userId);
            appFile.setFileName(uploadResult.getFilename());
            appFile.setOriginalName(file.getOriginalFilename());
            appFile.setFilePath(uploadResult.getFilename());
            appFile.setFileUrl(uploadResult.getUrl());
            appFile.setFileSize(file.getSize());
            appFile.setFileType(file.getContentType());
            appFile.setFileSuffix(getFileSuffix(file.getOriginalFilename()));
            appFile.setFileCategory(fileCategory != null ? fileCategory : 6); // 默认为其他
            appFile.setStorageService(ossClient.getConfigKey());
            appFile.setStatus("0"); // 正常
            appFile.setDownloadCount(0L);
            appFile.setIsPublic("0"); // 默认私有
            appFile.setFileMd5(fileMd5);

            baseMapper.insert(appFile);
            return MapstructUtils.convert(appFile, AppFileVo.class);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw FileException.uploadFailed(e.getMessage());
        }
    }

    /**
     * 上传头像
     */
    @Override
    public AppFileVo uploadAvatar(MultipartFile file, Long userId) {
        // 检查文件类型
        String contentType = file.getContentType();
        if (!isImageFile(contentType)) {
            throw FileException.unsupportedFileType(contentType);
        }

        // 检查文件大小（限制为5MB）
        if (file.getSize() > 5 * 1024 * 1024) {
            throw FileException.fileSizeExceeded(5);
        }

        return uploadFile(file, userId, 1); // 头像分类
    }

    /**
     * 批量上传文件
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<AppFileVo> batchUploadFiles(MultipartFile[] files, Long userId, Integer fileCategory) {
        List<AppFileVo> result = new ArrayList<>();
        for (MultipartFile file : files) {
            try {
                AppFileVo fileVo = uploadFile(file, userId, fileCategory);
                result.add(fileVo);
            } catch (Exception e) {
                log.error("批量上传文件失败: {}", file.getOriginalFilename(), e);
                // 继续处理其他文件
            }
        }
        return result;
    }

    /**
     * 根据用户ID查询文件列表
     */
    @Override
    public List<AppFileVo> queryByUserId(Long userId, Integer fileCategory) {
        LambdaQueryWrapper<AppFile> lqw = Wrappers.lambdaQuery();
        lqw.eq(AppFile::getUserId, userId);
        lqw.eq(fileCategory != null, AppFile::getFileCategory, fileCategory);
        lqw.eq(AppFile::getStatus, "0"); // 正常状态
        lqw.orderByDesc(AppFile::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据文件分类查询文件列表
     */
    @Override
    public List<AppFileVo> queryByCategory(Integer fileCategory) {
        LambdaQueryWrapper<AppFile> lqw = Wrappers.lambdaQuery();
        lqw.eq(AppFile::getFileCategory, fileCategory);
        lqw.eq(AppFile::getStatus, "0"); // 正常状态
        lqw.eq(AppFile::getIsPublic, "1"); // 公开文件
        lqw.orderByDesc(AppFile::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 下载文件
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppFileVo downloadFile(Long fileId, Long userId) {
        AppFile appFile = baseMapper.selectById(fileId);
        if (appFile == null) {
            throw FileException.fileNotFound(fileId);
        }

        // 检查权限
        if (!appFile.getUserId().equals(userId) && !"1".equals(appFile.getIsPublic())) {
            throw FileException.accessDenied(fileId);
        }

        // 更新下载次数
        appFile.setDownloadCount(appFile.getDownloadCount() + 1);
        baseMapper.updateById(appFile);

        return MapstructUtils.convert(appFile, AppFileVo.class);
    }

    /**
     * 删除用户文件
     */
    @Override
    public Boolean deleteUserFile(Long fileId, Long userId) {
        AppFile appFile = baseMapper.selectById(fileId);
        if (appFile == null) {
            throw FileException.fileNotFound(fileId);
        }

        if (!appFile.getUserId().equals(userId)) {
            throw FileException.accessDenied(fileId);
        }

        return baseMapper.deleteById(fileId) > 0;
    }

    /**
     * 批量删除用户文件
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchDeleteUserFiles(Collection<Long> fileIds, Long userId) {
        for (Long fileId : fileIds) {
            deleteUserFile(fileId, userId);
        }
        return true;
    }

    /**
     * 更新文件状态
     */
    @Override
    public Boolean updateFileStatus(Long fileId, String status, Long userId) {
        AppFile appFile = baseMapper.selectById(fileId);
        if (appFile == null) {
            throw new ServiceException("文件不存在");
        }

        if (!appFile.getUserId().equals(userId)) {
            throw new ServiceException("无权限修改该文件");
        }

        appFile.setStatus(status);
        return baseMapper.updateById(appFile) > 0;
    }

    /**
     * 获取用户文件统计信息
     */
    @Override
    public AppFileVo getUserFileStatistics(Long userId) {
        LambdaQueryWrapper<AppFile> lqw = Wrappers.lambdaQuery();
        lqw.eq(AppFile::getUserId, userId);
        lqw.eq(AppFile::getStatus, "0");

        List<AppFile> files = baseMapper.selectList(lqw);

        AppFileVo statistics = new AppFileVo();
        statistics.setUserId(userId);

        if (!files.isEmpty()) {
            long totalSize = files.stream().mapToLong(AppFile::getFileSize).sum();
            long totalDownloads = files.stream().mapToLong(AppFile::getDownloadCount).sum();

            statistics.setFileSize(totalSize);
            statistics.setDownloadCount(totalDownloads);
        }

        return statistics;
    }

    /**
     * 清理过期文件
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer cleanExpiredFiles(Integer days) {
        LocalDateTime expiredTime = LocalDateTime.now().minusDays(days);
        LambdaQueryWrapper<AppFile> lqw = Wrappers.lambdaQuery();
        lqw.lt(AppFile::getCreateTime, expiredTime);
        lqw.eq(AppFile::getStatus, "1"); // 已删除状态

        List<AppFile> expiredFiles = baseMapper.selectList(lqw);
        if (!expiredFiles.isEmpty()) {
            List<Long> fileIds = expiredFiles.stream().map(AppFile::getFileId).collect(Collectors.toList());
            baseMapper.deleteBatchIds(fileIds);
        }

        return expiredFiles.size();
    }

    /**
     * 检查文件是否存在
     */
    @Override
    public AppFileVo checkFileExists(String fileMd5, Long userId) {
        LambdaQueryWrapper<AppFile> lqw = Wrappers.lambdaQuery();
        lqw.eq(AppFile::getFileMd5, fileMd5);
        lqw.eq(AppFile::getUserId, userId);
        lqw.eq(AppFile::getStatus, "0");

        AppFile existFile = baseMapper.selectOne(lqw);
        return existFile != null ? MapstructUtils.convert(existFile, AppFileVo.class) : null;
    }

    /**
     * 更新文件公开状态
     */
    @Override
    public Boolean updateFilePublicStatus(Long fileId, String isPublic, Long userId) {
        AppFile appFile = baseMapper.selectById(fileId);
        if (appFile == null) {
            throw new ServiceException("文件不存在");
        }

        if (!appFile.getUserId().equals(userId)) {
            throw new ServiceException("无权限修改该文件");
        }

        appFile.setIsPublic(isPublic);
        return baseMapper.updateById(appFile) > 0;
    }

    /**
     * 获取文件后缀
     */
    private String getFileSuffix(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return "";
        }
        int lastDotIndex = fileName.lastIndexOf(".");
        return lastDotIndex > 0 ? fileName.substring(lastDotIndex) : "";
    }

    /**
     * 检查是否为图片文件
     */
    private boolean isImageFile(String contentType) {
        return StringUtils.isNotBlank(contentType) &&
                (contentType.startsWith("image/") ||
                        contentType.equals("application/octet-stream"));
    }

}