package com.taais.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.taais.common.core.config.TaaisConfig;
import com.taais.common.core.constant.CacheNames;
import com.taais.common.core.constant.Constants;
import com.taais.common.core.core.domain.UploadRes;
import com.taais.common.core.core.page.PageResult;
import com.taais.common.core.exception.ServiceException;
import com.taais.common.core.service.OssService;
import com.taais.common.core.utils.MapstructUtils;
import com.taais.common.core.utils.SpringUtils;
import com.taais.common.core.utils.StreamUtils;
import com.taais.common.core.utils.StringUtils;
import com.taais.common.core.utils.file.FileUtils;
import com.taais.common.orm.core.page.PageQuery;
import com.taais.common.orm.core.service.impl.BaseServiceImpl;
import com.taais.common.oss.core.OssClient;
import com.taais.common.oss.entity.UploadResult;
import com.taais.common.oss.enumd.AccessPolicyType;
import com.taais.common.oss.factory.OssFactory;
import com.taais.system.domain.SysOss;
import com.taais.system.domain.bo.SysOssBo;
import com.taais.system.domain.vo.SysOssVo;
import com.taais.system.mapper.SysOssMapper;
import com.taais.system.service.ISysOssService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
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 static com.taais.system.domain.table.SysOssTableDef.SYS_OSS;

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

    private final SysOssMapper ossMapper;

    @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.OSS_ID.asc());
    }

    @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 = SpringUtils.getAopProxy(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 UploadRes upload(byte[] file, String name) {
        String suffix = StringUtils.substring(name, name.lastIndexOf("."), name.length());
        OssClient storage = OssFactory.instance();
        UploadResult uploadResult = storage.uploadSuffix(file, suffix);
        SysOssVo ossVo = buildResultEntity(name, suffix, storage.getConfigKey(), uploadResult);
        return UploadRes.builder().name(name).url(uploadResult.getUrl()).ossId(ossVo.getOssId()).build();
    }


    @Cacheable(cacheNames = CacheNames.SYS_OSS, key = "#ossId")
    @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 ServiceException("文件数据不存在!");
        }
        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 ServiceException(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 {
            uploadResult = storage.uploadSuffix(file.getBytes(), suffix);
        } catch (IOException e) {
            throw new ServiceException(e.getMessage());
        }
        // 保存文件信息
        return buildResultEntity(originalFilename, suffix, storage.getConfigKey(), uploadResult);
    }

    @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 = storage.uploadSuffix(file, suffix);
        // 保存文件信息
        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);
        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 = TaaisConfig.getProfile() + StringUtils.substringAfter(sysOss.getFileName(), Constants.RESOURCE_PREFIX);
                boolean deleted = FileUtil.del(filePath);
                if (!deleted) {
                    throw new ServiceException(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;
    }
}
