package ink.wgink.module.file.service.filedownload.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import ink.wgink.common.base.DefaultBaseService;
import ink.wgink.exceptions.FileException;
import ink.wgink.module.file.dao.filedownload.IFileDownloadDao;
import ink.wgink.module.file.manager.FilesManager;
import ink.wgink.module.file.pojo.dtos.filedownload.FileDownloadDTO;
import ink.wgink.module.file.pojo.vos.filedownload.FileDownloadVO;
import ink.wgink.module.file.service.filedownload.IFileDownloadService;
import ink.wgink.pojo.ListPage;
import ink.wgink.pojo.pos.FilePO;
import ink.wgink.pojo.result.SuccessResultList;
import ink.wgink.util.UUIDUtil;
import ink.wgink.util.date.DateUtil;
import ink.wgink.util.map.HashMapUtil;
import ink.wgink.util.request.RequestUtil;
import ink.wgink.util.request.StaticResourceRequestUtil;
import ink.wgink.util.thread.CachedThreadPoolUtil;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.URLEncoder;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: FileDownloadServiceImpl
 * @Description: 文件下载
 * @Author: wanggeng
 * @Date: 2022/8/2 09:58
 * @Version: 1.0
 */
@Service
public class FileDownloadServiceImpl extends DefaultBaseService implements IFileDownloadService {

    @Autowired
    private IFileDownloadDao fileDownloadDao;

    @Override
    public void save(FileDownloadVO fileDownloadVO) {
        Map<String, Object> params = HashMapUtil.beanToMap(fileDownloadVO);
        params.put("fileDownloadId", UUIDUtil.getUUID());
        params.put("gmtCreate", DateUtil.getTime());
        fileDownloadDao.save(params);
    }

    @Override
    public List<FileDownloadDTO> list(Map<String, Object> params) {
        params = params == null ? getHashMap(0) : params;
        return fileDownloadDao.list(params);
    }

    @Override
    public List<FileDownloadDTO> listByFileId(String fileId) {
        Map<String, Object> params = getHashMap(2);
        params.put("fileId", fileId);
        return list(params);
    }

    @Override
    public SuccessResultList<List<FileDownloadDTO>> listPage(ListPage page) {
        PageHelper.startPage(page.getPage(), page.getRows());
        List<FileDownloadDTO> fileDownloadDTOS = list(page.getParams());
        PageInfo<FileDownloadDTO> pageInfo = new PageInfo<>(fileDownloadDTOS);
        return new SuccessResultList<>(fileDownloadDTOS, pageInfo.getPageNum(), pageInfo.getTotal());
    }

    @Override
    public SuccessResultList<List<FileDownloadDTO>> listPageByFileId(String fileId, ListPage page) {
        page.getParams().put("fileId", fileId);
        return listPage(page);
    }

    @Override
    public Integer countByFileId(String fileId) {
        Map<String, Object> params = getHashMap(2);
        params.put("fileId", fileId);
        return fileDownloadDao.count(params);
    }


    @Override
    public void download(HttpServletRequest request, HttpServletResponse response, FilePO filePO) {
        String fileId = filePO.getFileId();
        try (
                RandomAccessFile randomAccessFile = new RandomAccessFile(filePO.getFilePath(), "r");
                FileChannel fileChannel = randomAccessFile.getChannel();
                OutputStream outputStream = response.getOutputStream();
                WritableByteChannel writableByteChannel = Channels.newChannel(outputStream);
        ) {
            response.setHeader("Content-Length", filePO.getFileSize().toString());
            response.setContentType(StaticResourceRequestUtil.getContentType(filePO.getFileType()));
            response.setHeader("Content-Disposition", "inline;fileName=" + URLEncoder.encode(filePO.getFileName(), "UTF-8"));
            String rangeString = request.getHeader("Range");
            long contentLength = filePO.getFileSize();
            long startRange = 0;
            long endRange = contentLength - 1;
            if (!StringUtils.isBlank(rangeString)) {
                response.setContentType("multipart/byteranges");
                String[] rangeArray = rangeString.substring(rangeString.indexOf("=") + 1).split("-");
                startRange = Long.parseLong(rangeArray[0]);
                if (rangeArray.length > 1) {
                    endRange = Long.parseLong(rangeArray[1]);
                }
                response.setHeader("Content-Length", String.valueOf(endRange - startRange + 1));
                response.setHeader("Content-Range", String.format("bytes %d-%d/%d", startRange, endRange, contentLength));
                response.setHeader("Accept-Ranges", "bytes");
                response.setHeader("Etag", fileId);
                response.setStatus(206);
                randomAccessFile.seek(startRange);
            }
            LOG.debug("startRange: {}, endRange: {}", startRange, endRange);
            long totalOutputLength = endRange - startRange + 1;
            fileChannel.transferTo(startRange, totalOutputLength, writableByteChannel);
            outputStream.flush();
            if (endRange >= contentLength - 1) {
                handle(request, false, fileId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof ClientAbortException) {
                LOG.debug("客户端断开连接");
            } else {
                throw new FileException("文件输出异常", e);
            }
        }
    }

    @Override
    public void downloadRedirect(HttpServletRequest request, HttpServletResponse response, boolean isOpen, FilePO filePO) {
        if (filePO == null) {
            throw new FileException("查询失败");
        }
        File file = new File(filePO.getFilePath());
        if (!file.exists()) {
            throw new FileException("文件不存在");
        }
        String fileId = filePO.getFileId();
        try {
            String code = FilesManager.getInstance().generateCode(fileId, filePO.getFileName());
            response.sendRedirect(String.format("%s/%s?file=%s&code=%s&open=%d", request.getContextPath(), filePO.getFileUrl(), fileId, code, isOpen ? 1 : 0));
            handle(request, isOpen, fileId);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void handle(HttpServletRequest httpServletRequest, boolean isOpen, String fileId) {
        String requestIp = RequestUtil.getRequestIp(httpServletRequest);
        if (!isOpen && !StringUtils.isBlank(requestIp)) {
            // 记录下载历史
            CachedThreadPoolUtil.execute(() -> {
                save(new FileDownloadVO(fileId, requestIp));
            });
        }
    }

}
