package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.cweb.config.SysConfig;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.ImageUtils;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.model.ResponseData;
import com.hfkj.obs.HuaWeiYunObs;
import com.hfkj.service.FileUploadService;
import com.obs.services.model.PutObjectResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

@RestController
@RequestMapping(value="/fileUpload")
@Api(value="文件上传")
public class FileUploadController {

	private static Logger log = LoggerFactory.getLogger(FileUploadController.class);

	@Resource
	private SysConfig sysConfig;

	@RequestMapping(value="/uploadfile",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "文件上传")
	public ResponseData uploadFile(@RequestParam(value = "files" , required = false) MultipartFile files,
								   HttpServletRequest request,
								   HttpServletResponse response) throws Exception {
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			List<String> fileNames = new ArrayList<String>();
			if (multipartResolver.isMultipart(request)) {
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				Iterator<String> iterator = multiRequest.getFileNames();

				while (iterator.hasNext()) {
					MultipartFile file = multiRequest.getFile(iterator.next());
					if (file != null) {
						FileOutputStream out = null;
						try {

							String fileType = file.getOriginalFilename()
									.substring(file.getOriginalFilename().lastIndexOf(".") + 1);
							String fileName = System.currentTimeMillis() + "." + fileType;
							String childPath = DateUtil.date2String(new Date(), "yyyyMM");
							String destDirName = sysConfig.getFileUrl() + File.separator + childPath;
							File dir = new File(destDirName);
							if (!dir.exists()) {
								dir.mkdirs();
							}
							out = new FileOutputStream(destDirName + File.separator + fileName);
							out.write(file.getBytes());
							out.flush();

							Thumbnails.of(destDirName + File.separator + fileName).scale(1f)
									.outputQuality(0.5f).toFile(destDirName + File.separator + fileName);

							fileNames.add("/"+ childPath + "/" + fileName);

							File filePath = new File(destDirName + "/" + fileName);
							PutObjectResult putObjectResult = HuaWeiYunObs.putObject(CommonSysConst.getSysConfig().getObs_bucket_name(),
									childPath + "/" + fileName,filePath);

						} catch (Exception e) {
							log.error(e.getMessage(), e);
						} finally {
							if (out != null) {
								out.close();
							}
						}
					}
				}
			}
			return ResponseMsgUtil.success(fileNames);

		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return ResponseMsgUtil.exception(e);
		}
	}

	@RequestMapping(value="/uploadBase64File",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "文件上传")
	public ResponseData uploadBase64File(@RequestParam(value = "base64File" , required = true) String base64File) {
		try {
			String fileName = System.currentTimeMillis()+"";
			String childPath = DateUtil.date2String(new Date(), "yyyyMM");
			String path =  sysConfig.getFileUrl() + File.separator + childPath;
			Map<String, Object> map = ImageUtils.generateImage(base64File, path, fileName);

			File filePath = new File(path +"/"+ map.get("fileName"));
			HuaWeiYunObs.putObject(CommonSysConst.getSysConfig().getObs_bucket_name(), childPath + "/" + map.get("fileName"), filePath);

			List<String> fileNames = new ArrayList<String>();
			fileNames.add("/"+childPath + "/" + map.get("fileName"));
			return ResponseMsgUtil.success(fileNames);

		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return ResponseMsgUtil.exception(e);
		}
	}

	@RequestMapping(value="/getImgSignedUrl",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "文件上传")
	public ResponseData getImgSignedUrl(@RequestBody JSONObject body) throws Exception {
		try {

			if (body == null || StringUtils.isBlank(body.getString("fileUrl"))) {
				throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
			}
			return ResponseMsgUtil.success(HuaWeiYunObs.getImgSignedUrl(CommonSysConst.getSysConfig().getObs_bucket_name(), body.getString("fileUrl")));

		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return ResponseMsgUtil.exception(e);
		}
	}


}
