package com.op.file.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.op.common.core.domain.R;
import com.op.common.core.utils.file.FileUtils;
import com.op.file.service.ISysFileService;
import com.op.system.api.domain.SysFile;

/**
 * 文件请求处理
 *
 * @author OP
 */
@RestController
public class SysFileController {
	private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

	@Autowired
	private ISysFileService sysFileService;

	/**
	 * 文件上传请求（用的是这个）
	 */
	@PostMapping("upload")
	public R<SysFile> upload(MultipartFile file) {
		try {
			// 上传并返回访问地址
			String url = sysFileService.uploadFile(file);
			SysFile sysFile = new SysFile();
			sysFile.setName(file.getOriginalFilename());//sysFile.setName(FileUtils.getName(url));
			sysFile.setUrl(url);
			return R.ok(sysFile);
		} catch (Exception e) {
			log.error("上传文件失败", e);
			return R.fail(e.getMessage());
		}
	}

	@PostMapping("/file/upload")
	public R<SysFile> fileUpload(MultipartFile file) {
		try {
			// 上传并返回访问地址
			String url = sysFileService.uploadFile(file);
			SysFile sysFile = new SysFile();
			sysFile.setName(file.getOriginalFilename());//sysFile.setName(FileUtils.getName(url));
			sysFile.setUrl(url);
			return R.ok(sysFile);
		} catch (Exception e) {
			log.error("上传文件失败", e);
			return R.fail(e.getMessage());
		}
	}

	// 在线显示
	@GetMapping("/online")
	public void previewPng(HttpServletRequest request, HttpServletResponse response) {
		OutputStream out = null;
		response.setHeader("Content-Disposition", "inline;fileName=1.png");
		byte[] io = sysFileService.imageOnline(request.getParameter("id"));
		response.setContentLength(io.length);
		try {
			out = response.getOutputStream();
			out.write(io);
		} catch (IOException e) {
			log.error("Online error", e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					log.error("Close error", e);
				}
			}
		}
	}

	// 下载
	@GetMapping("/downLoadFile")
	public void downLoadFile(HttpServletRequest request, HttpServletResponse response) {
		OutputStream out = null;
		try {
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(request.getParameter("fileName"), "UTF-8"));
			byte[] io = sysFileService.imageOnline(request.getParameter("id"));
			response.setContentLength(io.length);
			out = response.getOutputStream();
			out.write(io);
		} catch (IOException e) {
			log.error("Online error", e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					log.error("Close error", e);
				}
			}
		}
	}

	// 转byte[]
	public static byte[] toByteArray(InputStream input) throws IOException {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[4096];
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
		}
		return output.toByteArray();
	}
}
