package com.zjty.tynotes.fs.subject.service.impl;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.zjty.tynotes.fs.subject.service.FsUtil;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author LJJ cnljj1995@gmail.com
 * on 2019-04-28
 */
@Slf4j
@Service
public class FsUtilImpl implements FsUtil {

    @Autowired
    private MongoDbFactory mongoDbFactory;
    @Autowired
    private GridFsTemplate gridFsTemplate;

    @Override
    public String save(String path) {

        try {
            InputStream inputStream = new FileInputStream(path);
            String fileName = new Date().toString();
            ObjectId id = gridFsTemplate.store(inputStream, fileName);
            return id.toString();
        } catch (FileNotFoundException e) {
            log.error("[fs] the err msg is : {}", e.getMessage());
            return "";
        }
    }

    @Override
    public String save(HttpServletRequest httpServletRequest) {
        try {
            Part part = httpServletRequest.getPart("file");
            InputStream inputStream = part.getInputStream();
            String fileName = new Date().toString();
            ObjectId id = gridFsTemplate.store(inputStream, fileName);
            return id.toString();
        } catch (IOException | ServletException e) {
            log.error("[fs] the err msg is: {}", e.getMessage());
            return "";
        }

    }

    @Override
    public void download(String id, HttpServletRequest request, HttpServletResponse response) {

        GridFSBucket bucket = GridFSBuckets.create(mongoDbFactory.getDb());

        // 重置响应对象
        response.reset();
        // 当前日期，用于导出文件名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = "filename" + sdf.format(new Date()) + ".zip";
        // 指定下载的文件名--设置响应头
        response.addHeader("Content-Disposition", "attachment;filename=" + dateStr);
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        // 写出数据输出流到页面

        try {
            OutputStream output = response.getOutputStream();
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);

            bucket.downloadToStream(new ObjectId(id), bufferedOutPut);

            bufferedOutPut.flush();
            bufferedOutPut.close();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void delete(String id) {
        gridFsTemplate.delete(new Query(Criteria.where("_id").is(id)));
    }
}
