package com.op.file.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
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 com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;

/**
 * /**
 *
 * @program:
 * @description: MongoService
 */
@Service
public class MongoService {

	@Autowired
	private GridFsTemplate gridFsTemplate;
	@Autowired
	private MongoTemplate mongoTemplate;

	/**
	 * 文件上传到mongo服务器上
	 *
	 * @param multipartFile 文件
	 * @param fileName      存入mongo中的名字
	 * @return
	 * @throws Exception
	 */
	public String uploadFile(MultipartFile multipartFile, String fileName) throws Exception {

		// 查看mongo中是否已经保存图片
		Query filename = Query.query(Criteria.where("filename").is(fileName));
		// 获得文件输入流
		InputStream fileIn = multipartFile.getInputStream();

		// 将文件存储到mongodb中,mongodb 将会返回这个文件的具体信息
		ObjectId objectId = gridFsTemplate.store(fileIn, fileName);

		return objectId.toString();
	}

	/**
	 * 图片预览
	 *
	 * @param fileId
	 * @param
	 * @return
	 */
	public byte[] downloadImageByte(String fileId) {
		byte[] fileBytes = null;
		try {
			// 查询单个文件
			Query query = Query.query(Criteria.where("_id").is(fileId));
			GridFSFile gfsFile = gridFsTemplate.findOne(query);
			InputStream inputStream = null;
			if (gfsFile != null) {
				GridFSBucket gridFSBucket = defaultGridFsBucket();
				GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gfsFile.getObjectId());
				// 创建GridFsResource对象，获取流
				GridFsResource gridFsResource = new GridFsResource(gfsFile, gridFSDownloadStream);

				inputStream = gridFsResource.getInputStream();
			}
			fileBytes = is2ByeteArray(inputStream);
			inputStream.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileBytes;

	}

	private GridFSBucket defaultGridFsBucket() {
		// 通过mongoTemplate来获取默认的数据库连接
		MongoDatabaseFactory mongoDatabaseFactory = mongoTemplate.getMongoDatabaseFactory();
		MongoDatabase db = mongoDatabaseFactory.getMongoDatabase("op_cloud");
		// 创建GridFSBucket 并指定文件系统使用的bucket
		return GridFSBuckets.create(db);
	}

	// 转化inputStream 为byte[]
	public byte[] is2ByeteArray(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buff = new byte[100];
		int rc = 0;
		while ((rc = is.read(buff, 0, 100)) > 0) {
			baos.write(buff, 0, rc);
		}

		return baos.toByteArray();
	}

}
