package com.emergency.avenue.admin.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.emergency.avenue.admin.config.MinioTemplate;
import com.emergency.avenue.common.core.constant.CommonConstants;
import com.emergency.avenue.common.core.util.R;
import io.minio.MinioClient;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lengleng
 * @date 2018-12-30
 * <p>
 * 文件管理
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/sysFile")
public class FileController {

	private  String getNowTimestr1() {
		Date d = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyyMM");
		String date = dateFormat.format(d);
		return date.toString();
	}

//	/**
//	 * 上传文件
//	 * 文件名采用uuid,避免原始文件名中带"-"符号导致下载的时候解析出现异常
//	 *
//	 * @param file 资源
//	 * @return R(bucketName, filename)
//	 */
//	@PostMapping("/upload")
//	public R upload(@RequestParam("file") MultipartFile file) {
//		String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
//		Map<String, String> resultMap = new HashMap<>(4);
//		resultMap.put("bucketName", CommonConstants.BUCKET_NAME);
//		resultMap.put("fileName", fileName);
//		resultMap.put("uploadFileName", file.getOriginalFilename());
//		try {
//			minioTemplate.putObject(CommonConstants.BUCKET_NAME, fileName, file.getInputStream());
//		} catch (Exception e) {
//			log.error("上传失败", e);
//			return R.builder().code(CommonConstants.FAIL)
//					.msg(e.getLocalizedMessage()).build();
//		}
//		return R.builder().data(resultMap).build();
//	}


//	@PostMapping("/uploadVoucher")
//	public R uploadVoucher(@RequestParam("file") MultipartFile file,@RequestParam(defaultValue=CommonConstants.BUCKET_NAME,name = "bucket")String bucket) {
//		String fileName =  getNowTimestr()+IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
//		Map<String, String> resultMap = new HashMap<>(4);
//		resultMap.put("bucketName",  bucket);
//		String concat = bucket .concat("-").concat(fileName);
//		resultMap.put("fileName", concat);
//		resultMap.put("fileCustomizeName", file.getOriginalFilename());
//		try {
//			MinioTemplate.uploadObject(minioClient,bucket, fileName,file);
//		} catch (Exception e) {
//			log.error("上传失败", e);
//			throw  new RuntimeException("文件上传失败!");
//		}
//		return R.builder().data(resultMap).build();
//	}
	@Resource
	private MinioClient minioClient;

	/**
	 *上传  按月分文件夹存储
	 * @param file
	 * @param bucket
	 * @return
	 */
	@PostMapping("/uploadVoucher")
	public R uploadVoucher(@RequestParam("file") MultipartFile file,@RequestParam(defaultValue=CommonConstants.BUCKET_NAME,name = "bucket")String bucket) {
		String pre=getNowTimestr1();
		String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
		Map<String, String> resultMap = new HashMap<>(4);
		resultMap.put("bucketName",  bucket);
		String concat =   bucket .concat("-").concat(pre+"_"+fileName);
		resultMap.put("fileName", concat);
		resultMap.put("fileCustomizeName", file.getOriginalFilename());
		try {
			MinioTemplate.uploadObject(minioClient,bucket,  pre+"/"+fileName,file);
		} catch (Exception e) {
			log.error("上传失败", e);
//			throw  new RuntimeException("文件上传失败!");
			return R.failed("文件上传失败!");
		}
		return R.builder().data(resultMap).build();
	}




    /**
     * 删除文件--桶名称， 对象名称
     * @return R(bucketName, filename)
     */
    @DeleteMapping("/{bucketName}/{objectName}")
    public R deletFile(@PathVariable("bucketName") String bucketName,@PathVariable("objectName")  String objectName) {
        try {
			MinioTemplate.removeObject( minioClient,bucketName,objectName );
        } catch (Exception e) {
            log.error("删除失败", e);
//            throw  new RuntimeException("删除失败!");
            return R.failed("删除失败!");
        }
        return R.ok(null,"删除成功!");
    }
	/**
     *
	 * 获取文件
	 *
	 * @param fileName 文件空间/名称
	 * @param response
	 * @return
	 */
	@GetMapping("/{fileName}")
	public void file(@PathVariable String fileName, HttpServletResponse response) {
		String[] split = fileName.split(":");
		String[] nameArray =  split[0].split( StrUtil.DASHED);
		try (InputStream inputStream = MinioTemplate.getObject(minioClient,nameArray[0], nameArray[1].replaceFirst("_","/") ) ) {
			response.setContentType("application/octet-stream; charset=UTF-8");
			if(split.length==2){
				response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(split[1],"UTF-8"));
			}
			IoUtil.copy(inputStream, response.getOutputStream());
		} catch (Exception e) {
			log.error("文件读取异常", e);
		}
	}

}
