package org.eco.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eco.common.core.config.EcoConfig;
import org.eco.common.core.constant.CacheNames;
import org.eco.common.core.constant.Constants;
import org.eco.common.core.core.domain.UploadRes;
import org.eco.common.core.core.page.PageResult;
import org.eco.common.core.exception.BusinessException;
import org.eco.common.core.service.OssService;
import org.eco.common.core.utils.MapstructUtils;
import org.eco.common.core.utils.SpringUtils;
import org.eco.common.core.utils.StreamUtils;
import org.eco.common.core.utils.StringUtils;
import org.eco.common.core.utils.file.FileUtils;
import org.eco.common.orm.core.page.PageQuery;
import org.eco.common.orm.core.service.impl.BaseServiceImpl;
import org.eco.common.oss.core.OssClient;
import org.eco.common.oss.entity.UploadResult;
import org.eco.common.oss.enumd.AccessPolicyType;
import org.eco.common.oss.factory.OssFactory;
import org.eco.system.domain.SysOss;
import org.eco.system.domain.bo.SysOssBo;
import org.eco.system.domain.vo.SysOssVo;
import org.eco.system.mapper.SysDeptMapper;
import org.eco.system.mapper.SysOssMapper;
import org.eco.system.service.ICommonService;
import org.eco.system.service.ISysOssService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import static org.eco.common.core.utils.file.FileUtils.percentEncode;
import static org.eco.system.domain.table.SysOssTableDef.SYS_OSS;

/**
 * 文件上传 服务层实现
 *
 * @author wgk
 * @date 2023-11-30
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class SysOssServiceImpl extends BaseServiceImpl<SysOssMapper, SysOss> implements ISysOssService, OssService {

    private final SysOssMapper ossMapper;

    @Resource
    private ICommonService commonService;


    @Override
    public QueryWrapper query() {
        return super.query().from(SYS_OSS);
    }

    private QueryWrapper buildQueryWrapper(SysOssBo bo) {
        return super.buildBaseQueryWrapper()
            .where(SYS_OSS.FILE_NAME.like(bo.getFileName()))
            .and(SYS_OSS.ORIGINAL_NAME.like(bo.getOriginalName()))
            .and(SYS_OSS.FILE_SUFFIX.eq(bo.getFileSuffix()))
            .and(SYS_OSS.URL.eq(bo.getUrl()))
            .and(SYS_OSS.CREATE_TIME.between(bo.getParams().get("beginCreateTime"), bo.getParams().get("endCreateTime")))
            .and(SYS_OSS.SERVICE.eq(bo.getService()))
            .orderBy(SYS_OSS.UPDATE_TIME.desc());
    }

    @Override
    public PageResult<SysOssVo> queryPageList(SysOssBo bo) {
        QueryWrapper queryWrapper = buildQueryWrapper(bo);
        Page<SysOssVo> result = ossMapper.paginateWithRelationsAs(PageQuery.build(), queryWrapper, SysOssVo.class);
        List<SysOssVo> filterResult = StreamUtils.toList(result.getRecords(), this::matchingUrl);
        result.setRecords(filterResult);
        return PageResult.build(result);
    }

    @Override
    public List<SysOssVo> listSysOssByIds(Collection<Long> ossIds) {
        List<SysOssVo> list = new ArrayList<>();
        for (Long id : ossIds) {
            SysOssVo vo = this.getById(id);
            if (ObjectUtil.isNotNull(vo)) {
                try {
                    list.add(this.matchingUrl(vo));
                } catch (Exception ignored) {
                    // 如果oss异常无法连接则将数据直接返回
                    list.add(vo);
                }
            }
        }
        return list;
    }

    @Override
    public String selectUrlByIds(String ossIds) {
        List<String> list = new ArrayList<>();
        for (Long id : StringUtils.splitTo(ossIds, Convert::toLong)) {
            SysOssVo vo = SpringUtils.getAopProxy(this).getById(id);
            if (ObjectUtil.isNotNull(vo)) {
                try {
                    list.add(this.matchingUrl(vo).getUrl());
                } catch (Exception ignored) {
                    // 如果oss异常无法连接则将数据直接返回
                    list.add(vo.getUrl());
                }
            }
        }
        return String.join(StringUtils.SEPARATOR, list);
    }

    @Override
    public SysOssVo getById(Long ossId) {
        QueryWrapper queryWrapper = query().where(SYS_OSS.OSS_ID.eq(ossId));
        return ossMapper.selectOneWithRelationsByQueryAs(queryWrapper, SysOssVo.class);
    }

    @Override
    public void download(Long ossId, HttpServletResponse response) throws IOException {
        SysOssVo sysOss = SpringUtils.getAopProxy(this).getById(ossId);
        if (ObjectUtil.isNull(sysOss)) {
            throw new BusinessException("文件数据不存在!");
        }
        FileUtils.setAttachmentResponseHeader(response, sysOss.getOriginalName());
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE + "; charset=UTF-8");
        OssClient storage = OssFactory.instance(sysOss.getService());
        try (InputStream inputStream = storage.getObjectContent(sysOss.getUrl())) {
            int available = inputStream.available();
            IoUtil.copy(inputStream, response.getOutputStream(), available);
            response.setContentLength(available);
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }

    @Override
    public InputStream getFileStream(Long ossId) {
        SysOssVo sysOss = SpringUtils.getAopProxy(this).getById(ossId);
        if (ObjectUtil.isNull(sysOss)) {
            throw new BusinessException("文件数据不存在!");
        }
        OssClient storage = OssFactory.instance(sysOss.getService());
        try {
            String percentEncodedFileName = percentEncode(sysOss.getOriginalName());
            return storage.getObjectContent(sysOss.getUrl());
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }

    @Override
    public SysOssVo upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String suffix = StringUtils.substring(originalFilename, originalFilename.lastIndexOf("."), originalFilename.length());
        OssClient storage = OssFactory.instance();
        UploadResult uploadResult;
        try {
            if (StrUtil.equals(storage.getConfigKey(), "local")) {
                Map<String, String> map = commonService.uploadFile(file);
                uploadResult = UploadResult.builder().url(map.get("url")).filename(map.get("fileName")).build();
            } else {
                uploadResult = storage.uploadSuffix(file.getBytes(), suffix);
            }
        } catch (IOException e) {
            throw new BusinessException(e.getMessage());
        }
        // 保存文件信息
        return buildResultEntity(originalFilename, suffix, storage.getConfigKey(), uploadResult);
    }

    @Override
    public UploadRes upload(byte[] file, String name) {
        String suffix = StringUtils.substring(name, name.lastIndexOf("."), name.length());
        OssClient storage = OssFactory.instance();
        UploadResult uploadResult;
        File tempFile = null;
        try {
            tempFile = File.createTempFile(name, suffix);
            if (StrUtil.equals(storage.getConfigKey(), "local")) {
                Map<String, String> map = commonService.uploadFile(FileUtils.fileToMultipartFile(tempFile));
                uploadResult = UploadResult.builder().url(map.get("url")).filename(map.get("fileName")).build();
            } else {
                uploadResult = storage.uploadSuffix(file, suffix);
            }
        } catch (IOException e) {
            throw new BusinessException(e.getMessage());
        } finally {
            // 删除临时文件（可选）
            if (tempFile != null) {
                FileUtil.del(tempFile);
            }
        }


        SysOssVo ossVo = buildResultEntity(name, suffix, storage.getConfigKey(), uploadResult);
        return UploadRes.builder().name(name).url(uploadResult.getUrl()).ossId(ossVo.getOssId()).build();
    }

    @Override
    public SysOssVo upload(File file) {
        String originalFileName = file.getName();
        String suffix = StringUtils.substring(originalFileName, originalFileName.lastIndexOf("."), originalFileName.length());
        OssClient storage = OssFactory.instance();

        UploadResult uploadResult;
        try {
            if (StrUtil.equals(storage.getConfigKey(), "local")) {
                Map<String, String> map = commonService.uploadFile(FileUtils.fileToMultipartFile(file));
                uploadResult = UploadResult.builder().url(map.get("url")).filename(map.get("fileName")).build();
            } else {
                uploadResult = storage.uploadSuffix(file, suffix);
            }
        } catch (IOException e) {
            throw new BusinessException(e.getMessage());
        }
        // 保存文件信息
        return buildResultEntity(originalFileName, suffix, storage.getConfigKey(), uploadResult);
    }

    private SysOssVo buildResultEntity(String originalFileName, String suffix, String configKey, UploadResult uploadResult) {
        SysOss oss = new SysOss();
        oss.setUrl(uploadResult.getUrl());
        oss.setFileSuffix(suffix);
        oss.setFileName(uploadResult.getFilename());
        oss.setOriginalName(originalFileName);
        oss.setService(configKey);
        this.save(oss);
        SysOssVo sysOssVo = MapstructUtils.convert(oss, SysOssVo.class);
        assert sysOssVo != null;
        return this.matchingUrl(sysOssVo);
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
        }

        List<SysOss> list = this.listByIds(ids);
        for (SysOss sysOss : list) {
            if (StrUtil.equals("local", sysOss.getService())) {
                // 删除本地文件
                String filePath = EcoConfig.getProfile() + StringUtils.substringAfter(sysOss.getFileName(), Constants.RESOURCE_PREFIX);
                boolean deleted = FileUtil.del(filePath);
                if (!deleted) {
                    throw new BusinessException(sysOss.getFileName() + "文件删除失败，可能是因为文件不存在或无权限删除。");
                }
            } else {
                OssClient storage = OssFactory.instance(sysOss.getService());
                storage.delete(sysOss.getUrl());
            }
        }
        return this.removeByIds(ids);
    }

    /**
     * 匹配Url
     *
     * @param oss OSS对象
     * @return oss 匹配Url的OSS对象
     */
    private SysOssVo matchingUrl(SysOssVo oss) {
        if (StrUtil.equals("local", oss.getService())) {
            return oss;
        }
        OssClient storage = OssFactory.instance(oss.getService());
        // 仅修改桶类型为 private 的URL，临时URL时长为120s
        if (AccessPolicyType.PRIVATE == storage.getAccessPolicy()) {
            oss.setUrl(storage.getPrivateUrl(oss.getFileName(), 120));
        }
        return oss;
    }

    @Override
    public SysOssVo saveResultEntity(String originalFileName, String suffix, String url, String fileName) {
        SysOss oss = new SysOss();
        oss.setUrl(url);
        oss.setFileSuffix(suffix);
        oss.setFileName(fileName);
        oss.setOriginalName(originalFileName);
        oss.setService("local");
        this.save(oss);
        SysOssVo sysOssVo = MapstructUtils.convert(oss, SysOssVo.class);
        assert sysOssVo != null;
        return sysOssVo;
    }
}
