package org.dromara.system.service.impl;

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 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 org.springframework.stereotype.Service;
import org.dromara.system.domain.FileInfo;
import org.dromara.system.domain.bo.FileInfoBo;
import org.dromara.system.domain.vo.FileInfoVo;
import org.dromara.system.mapper.FileInfoMapper;
import org.dromara.system.service.IFileInfoService;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 文件信息Service业务层处理
 *
 * @author Lion Li
 * @date 2024-01-01
 */
@RequiredArgsConstructor
@Service
public class FileInfoServiceImpl implements IFileInfoService {

    private final FileInfoMapper baseMapper;

    /**
     * 查询文件信息
     */
    @Override
    public FileInfoVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询文件信息列表
     */
    @Override
    public TableDataInfo<FileInfoVo> queryPageList(FileInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<FileInfo> lqw = buildQueryWrapper(bo);
        // 指定租户ID为000000，以便查询所有数据
        lqw.apply("tenant_id = '000000'");
        Page<FileInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询文件信息列表
     */
    @Override
    public List<FileInfoVo> queryList(FileInfoBo bo) {
        LambdaQueryWrapper<FileInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<FileInfo> buildQueryWrapper(FileInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<FileInfo> lqw = Wrappers.lambdaQuery();

        // 添加调试日志
        System.out.println("buildQueryWrapper - bo.getCategoryType(): " + bo.getCategoryType());
        System.out.println("buildQueryWrapper - bo.getCategoryId(): " + bo.getCategoryId());

        lqw.like(StringUtils.isNotBlank(bo.getName()), FileInfo::getName, bo.getName());
        lqw.like(StringUtils.isNotBlank(bo.getOriginalName()), FileInfo::getOriginalName, bo.getOriginalName());
        lqw.like(StringUtils.isNotBlank(bo.getPath()), FileInfo::getPath, bo.getPath());
        lqw.eq(bo.getCategoryId() != null, FileInfo::getCategoryId, bo.getCategoryId());
        lqw.eq(bo.getCategoryType() != null, FileInfo::getCategoryType, bo.getCategoryType());
        // 支持类型前缀匹配
        if (StringUtils.isNotBlank(bo.getType())) {
            if (bo.getType().endsWith("/")) {
                // 如果是前缀匹配（如 "image/" 或 "video/"）
                lqw.like(FileInfo::getType, bo.getType());
            } else {
                // 如果是精确匹配
                lqw.eq(FileInfo::getType, bo.getType());
            }
        }
        lqw.eq(bo.getUploadStatus() != null, FileInfo::getUploadStatus, bo.getUploadStatus());
        lqw.eq(bo.getIsPublic() != null, FileInfo::getIsPublic, bo.getIsPublic());
        lqw.eq(bo.getStatus() != null, FileInfo::getStatus, bo.getStatus());
        // 确保只查询未删除的记录
        lqw.eq(FileInfo::getDelFlag, 0);
        lqw.orderByDesc(FileInfo::getId);
        return lqw;
    }

    /**
     * 新增文件信息
     */
    @Override
    public Boolean insertByBo(FileInfoBo bo) {
        FileInfo add = MapstructUtils.convert(bo, FileInfo.class);
        validEntityBeforeSave(add);

        // 设置租户ID - 使用字段直接赋值
        try {
            java.lang.reflect.Field tenantIdField = add.getClass().getSuperclass().getDeclaredField("tenantId");
            tenantIdField.setAccessible(true);
            tenantIdField.set(add, "000000");
        } catch (Exception e) {
            // 忽略设置租户ID的错误
        }

        // 设置默认值
        if (add.getDownloadCount() == null) {
            add.setDownloadCount(0);
        }
        if (add.getViewCount() == null) {
            add.setViewCount(0);
        }
        if (add.getUploadStatus() == null) {
            add.setUploadStatus(1);
        }
        if (add.getIsPublic() == null) {
            add.setIsPublic(1);
        }
        if (add.getStatus() == null) {
            add.setStatus(0);
        }
        if (add.getDelFlag() == null) {
            add.setDelFlag(0L);
        }

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改文件信息
     */
    @Override
    public Boolean updateByBo(FileInfoBo bo) {
        FileInfo update = MapstructUtils.convert(bo, FileInfo.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(FileInfo entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除文件信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 根据分类ID查询文件列表
     */
    @Override
    public List<FileInfoVo> queryByCategoryId(Long categoryId) {
        LambdaQueryWrapper<FileInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(FileInfo::getCategoryId, categoryId);
        lqw.eq(FileInfo::getStatus, 0);
        lqw.orderByDesc(FileInfo::getId);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据文件类型查询文件列表
     */
    @Override
    public List<FileInfoVo> queryByType(String type) {
        LambdaQueryWrapper<FileInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(FileInfo::getType, type);
        lqw.eq(FileInfo::getStatus, 0);
        lqw.orderByDesc(FileInfo::getId);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 更新文件下载次数
     */
    @Override
    public Boolean updateDownloadCount(Long id) {
        FileInfo fileInfo = baseMapper.selectById(id);
        if (fileInfo != null) {
            fileInfo.setDownloadCount(fileInfo.getDownloadCount() + 1);
            return baseMapper.updateById(fileInfo) > 0;
        }
        return false;
    }

    /**
     * 更新文件查看次数
     */
    @Override
    public Boolean updateViewCount(Long id) {
        FileInfo fileInfo = baseMapper.selectById(id);
        if (fileInfo != null) {
            fileInfo.setViewCount(fileInfo.getViewCount() + 1);
            return baseMapper.updateById(fileInfo) > 0;
        }
        return false;
    }

    /**
     * 下载文件
     */
    @Override
    public void downloadFile(Long id, jakarta.servlet.http.HttpServletResponse response) throws java.io.IOException {
        try {
            FileInfo fileInfo = baseMapper.selectById(id);
            if (fileInfo == null) {
                throw new RuntimeException("文件不存在，ID: " + id);
            }

            System.out.println("开始下载文件，ID: " + id + ", 名称: " + fileInfo.getName() + ", URL: " + fileInfo.getUrl());

            // 如果文件有URL，直接返回文件内容
            if (fileInfo.getUrl() != null && !fileInfo.getUrl().isEmpty()) {
                System.out.println("文件有URL，准备下载: " + fileInfo.getUrl());

                // 设置下载响应头
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileInfo.getName() + "\"");
                response.setContentType(fileInfo.getType() + "; charset=UTF-8");
                response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Expires", "0");

                // 简化方案：直接重定向到OSS文件
                System.out.println("准备重定向到OSS文件: " + fileInfo.getUrl());
                response.sendRedirect(fileInfo.getUrl());
                System.out.println("重定向成功");
                return;
            }

            // 如果没有URL，尝试从OSS下载
            if (fileInfo.getOssId() != null && !fileInfo.getOssId().isEmpty()) {
                System.out.println("文件没有URL，但有ossId: " + fileInfo.getOssId());
                try {
                    // 调用系统OSS服务下载
                    org.dromara.common.core.service.OssService ossService =
                        org.dromara.common.core.utils.SpringUtils.getBean(org.dromara.common.core.service.OssService.class);
                    if (ossService != null) {
                        // 这里需要根据实际情况调整，可能需要先查询sys_oss表获取文件信息
                        throw new RuntimeException("暂不支持通过ossId下载，请使用文件URL");
                    }
                } catch (Exception e) {
                    throw new RuntimeException("OSS服务不可用: " + e.getMessage());
                }
            }

            throw new RuntimeException("无法下载文件，文件URL和OSS信息都不存在");
        } catch (Exception e) {
            System.err.println("下载文件时发生错误: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
}
