package com.ibiz.web.rt.controller;

import com.ibiz.web.rt.domain.SRFFILE;
import com.ibiz.web.rt.domain.SRFFILEItem;
import com.ibiz.web.rt.service.SRFFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.UUID;

/**
 * 文件上传下载
 */
@RestController
@RequestMapping("/")
public class SRFFileController
{
	@Autowired
	private SRFFileService srfFileService;
	//文件存在目录
	@Value("${ibiz.filepath:/app/file/}")
	private String FILEPATH;
	//文件上传URL
	private final String defaultuploadpath="ibizutil/upload";
	//文件下载URL
	private final String defaultdownloadpath="ibizutil/download/{id}";

	/**
     * 文件上传
	 * @param multipartFile
     * @return
     * @throws Exception
	 */
	@PostMapping(value = "${ibiz.file.uploadpath:"+defaultuploadpath+"}")
	public ResponseEntity<SRFFILEItem> upload(@RequestParam("file") MultipartFile multipartFile) throws Exception {

		// 获取文件名
		String fileName = multipartFile.getOriginalFilename();
		// 获取文件后缀
		String extname="."+getExtensionName(fileName);
		// 用uuid作为文件名，防止生成的临时文件重复
		String fileid= UUID.randomUUID().toString();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String filepath=dateFormat.format(new java.util.Date())+ File.separator+fileid+ File.separator;

		SRFFILE ibzfile=new SRFFILE();
		ibzfile.setSRFFILEId(fileid);
		ibzfile.setSRFFILEName(fileName);
		ibzfile.setFileext(extname);
		ibzfile.setFilesize((int)multipartFile.getSize());
		ibzfile.setFilepath(filepath+fileName);
		boolean flag = srfFileService.save(fileid,ibzfile);
		if(!flag){
			throw new Exception("文件上传发生异常，存储文件记录失败!");
		}

		String dirPath=FILEPATH+filepath;
		File dir=new File(dirPath);
		if(!dir.exists()){
			dir.mkdirs();
		}
		File file = new File(dir,fileName);
		FileCopyUtils.copy(multipartFile.getInputStream(), Files.newOutputStream(file.toPath()));
		SRFFILEItem fileItem=new SRFFILEItem(fileid,fileName,file.length(),extname);

		return ResponseEntity.ok().body(fileItem);
	}

	/**
     * 文件下载
	 * @param id
     * @param response
     * @throws Exception
	 */
    @GetMapping(value = "${ibiz.file.downloadpath:"+defaultdownloadpath+"}")
	@ResponseStatus(HttpStatus.OK)
	public void download(@PathVariable String id, HttpServletResponse response) throws Exception {
        File file= getFile(id);
		String fileName=file.getName();
		try {
			fileName=new String(fileName.getBytes("utf-8"),"iso8859-1");//防止中文乱码
		}
		catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		response.setHeader("Content-Disposition", "attachment;filename="+fileName);
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(file));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		}
		catch (Exception e) {
			//throw e;
		}
		finally {
			if (bis != null) {
				try {
					bis.close();
				}
				catch (IOException e) {

				}
			}
			if (bos != null) {
				try {
					bos.close();
				}
				catch (IOException e) {

				}
			}
		}
	}

	/**
	 * 获取file
	 * @param id
	 * @return
	 * @throws Exception
	 */
	private File getFile(String id) throws Exception {
		SRFFILE ibzfile=srfFileService.get(id);
		if(ibzfile==null)
			throw new Exception("获取文件失败");
		String filepath=ibzfile.getFilepath();
		filepath=filepath.replace("\\",File.separator);
		filepath=filepath.replace("/",File.separator);
		File file=new File(FILEPATH+filepath);
		if(!file.exists())
			throw new Exception("获取文件失败");
		return file;
	}

	/**
	 * 获取文件扩展名
	 * @param filename
	 * @return
	 */
	private String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot >-1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}

}