package com.patzn.lims.res.service.impl;

import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.patzn.lims.res.service.MongoDbService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
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.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Slf4j
@Service
public class MongoDbServiceImpl implements MongoDbService {

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

    public void downloadFile(String fileId, HttpServletRequest request, HttpServletResponse response){
        Query query = Query.query(Criteria.where("_id").is(fileId));
        // 查询单个文件
        GridFSFile gfsFile = gridFsTemplate.findOne(query);
        GridFsResource gridFsResource=new GridFsResource(gfsFile, GridFSBuckets.create(mongoDbFactory.getDb()).openDownloadStream(gfsFile.getObjectId()));
        String fileName = gfsFile.getFilename().replace(",", "");
        try {
            //处理中文文件名乱码
            if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||
                    request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")
                    || request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
                //非IE浏览器的处理：
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }
            // 通知浏览器进行文件下载
            response.setHeader("Content-Disposition", "attachment;filename=\"" + java.net.URLEncoder.encode(fileName, "UTF-8") + "\"");

            IOUtils.copy(gridFsResource.getInputStream(),response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }



    }

    @Override
    public void preview(String fileId, HttpServletRequest request, HttpServletResponse response){
        Query query = Query.query(Criteria.where("_id").is(fileId));
        // 查询单个文件
        GridFSFile gfsFile = gridFsTemplate.findOne(query);

        if (null!=gfsFile){
            GridFsResource gridFsResource=new GridFsResource(gfsFile, GridFSBuckets.create(mongoDbFactory.getDb()).openDownloadStream(gfsFile.getObjectId()));
            try {


                response.setCharacterEncoding("UTF-8");
               if (gridFsResource.getFilename().contains(".xlsx")){
                   response.setHeader("content-type", "application/x-msexcel");
                   response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
               }else if (gridFsResource.getFilename().contains(".jpg")){
                   response.setContentType("text/html; charset=UTF-8");
                   response.setContentType("image/jpeg");
               }



                InputStream fis = gridFsResource.getInputStream();
                OutputStream os = response.getOutputStream();
                try {
                    int count = 0;
                    byte[] buffer = new byte[1024 * 1024];
                    while ((count = fis.read(buffer)) != -1)
                        os.write(buffer, 0, count);
                    os.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (os != null)
                        os.close();
                    if (fis != null)
                        fis.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }

    }


    public String saveFile(String filePath) {
        Resource resource = new FileSystemResource(filePath);
        try {
            ObjectId id = gridFsTemplate.store(resource.getInputStream(), resource.getFilename(), resource.getFilename().split(".")[1]);
            return  id.toString();
        }catch (Exception e){
           log.error("saveFile(String filePath)mongodb保存文件失败"+e.getMessage(),e);
        }
        return  null;

    }




    public String saveFile(File file)  {
        try {
            Resource resource = new FileSystemResource(file);
            ObjectId id = gridFsTemplate.store(resource.getInputStream(), resource.getFilename(),  file.getName().split(".")[1]);
            return  id.toString();
        }catch (Exception e){
            log.error("saveFile(File file) mongodb保存文件失败"+e.getMessage(),e);
        }
        return  null;
    }



    public String saveFile(MultipartFile file)  {
        try {

         String fileName=   file.getOriginalFilename();
            ObjectId id = gridFsTemplate.store(file.getInputStream(), fileName, file.getContentType());
            return  id.toString();
        }catch (Exception e){

            log.error("saveFile(MultipartFile file)mongodb保存文件失败"+e.getMessage(),e);
        }

        return  null;

    }
}
