package cn.superdesk.uniorder.controller._common;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.UUID;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.rest.response.ResponseResultOuterUtils;
import cn.superdesk.uniorder.dto.param._common.CommonStaticResourceDeleteTargetInfoForm;
import cn.superdesk.uniorder.dto.param._common.UploadFilesParam;
import cn.superdesk.uniorder.dubbo.consumer._common.UploadFilesDubboConsumerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 统一订单 公共的文件上传 目前逻辑 只能图片
 * @Author: linjinyu
 * @CreateDate: 9/17/20 4:12 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 9/17/20 4:12 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "公共接口-文件下载-特定 图片类", tags = {"公共接口-文件下载-特定 图片类"})
@Slf4j
@RestController
@RequestMapping("/common/static/resource")
public class CommonStaticResourceController {

	@Value("${common.static.resource.uploadOne}")
	private String uploadPath;
	@Value("${common.static.resource.uploadPathBySupplierAccountingAppeal}")
	private String uploadPathBySupplierAccountingAppeal;


	/**
	 * /common/static/resource/uploadOne
	 * <p>
	 * desc: 单文件上传
	 * param:
	 * return:
	 */
	@ApiOperation(value = "单文件上传")
	@RequestMapping(value = "/uploadOne", method = RequestMethod.POST)
	public Object uploadOne(@RequestParam(value = "file") MultipartFile multipartFile) throws IOException {

		String currentDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
		String yyyyMMdd    = uploadPath + currentDate + File.separator;

		if (!FileUtil.exist(yyyyMMdd)) {
			FileUtil.mkdir(yyyyMMdd);
		}

		String fileName = UUID.randomUUID().toString() + "@" + multipartFile.getOriginalFilename();
		String suffix   = Objects.requireNonNull(multipartFile.getOriginalFilename()).substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
		File   file1    = FileUtil.writeBytes(multipartFile.getBytes(), yyyyMMdd + fileName);

		List<Map<String, String>> pathList = new ArrayList<>();

		if (file1.length() > 0) {
			Map<String, String> map = new HashMap<>();
			map.put("fileName", fileName);
			map.put("suffix", suffix);
			map.put("path", currentDate);
			pathList.add(map);
		}
		return pathList;
	}

	@ApiOperation(value = "上传图片-供应商结算-申诉")
	@RequestMapping(value = "/uploadOneBySupplierAccountingAppeal", method = RequestMethod.POST)
	public Object uploadOneBySupplierAccountingAppeal(@RequestParam(value = "file") MultipartFile multipartFile) throws IOException {

		String currentDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
		String yyyyMMdd    = uploadPath + currentDate + File.separator;

		if (!FileUtil.exist(yyyyMMdd)) {
			FileUtil.mkdir(yyyyMMdd);
		}

		String fileName = UUID.randomUUID().toString() + "@" + multipartFile.getOriginalFilename();
		String suffix   = Objects.requireNonNull(multipartFile.getOriginalFilename()).substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
		File   file1    = FileUtil.writeBytes(multipartFile.getBytes(), yyyyMMdd + fileName);

		List<Map<String, String>> pathList = new ArrayList<>();

		if (file1.length() > 0) {
			Map<String, String> map = new HashMap<>();
			map.put("fileName", fileName);
			map.put("suffix", suffix);
			map.put("path", currentDate);
			pathList.add(map);
		}
		return pathList;
	}

	@ApiOperation(value = "查看图片-供应商结算-申诉")
	@GetMapping("showBySupplierAccountingAppeal")
	public Object showBySupplierAccountingAppeal(HttpServletResponse response, @RequestParam Map<String, Object> map) {

		log.info("\n\n\n\nCommonStaticResourceController.show params : {}\n\n\n\n", AnJsonUtils.toJson(map));

		view(response, map, uploadPathBySupplierAccountingAppeal);
		return null;
	}


	/**
	 * desc: 多文件上传
	 * param:
	 * return:
	 */
	@ApiOperation(value = "多文件上传")
	@RequestMapping(value = "/uploadMany", method = RequestMethod.POST)
	public Object uploadMany(@RequestParam(value = "file") MultipartFile[] file) throws IOException {

		String currentDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
		String yyyyMMdd    = uploadPath + currentDate + File.separator;
		if (!FileUtil.exist(yyyyMMdd)) {
			FileUtil.mkdir(yyyyMMdd);
		}

		List<Map<String, String>> pathList = new ArrayList<>();
		if (file.length > 0) {
			for (MultipartFile multipartFile : file) {
				String fileName = UUID.randomUUID().toString() + "@" + multipartFile.getOriginalFilename();

				String suffix = Objects.requireNonNull(multipartFile.getOriginalFilename()).substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
				File   file1  = FileUtil.writeBytes(multipartFile.getBytes(), yyyyMMdd + fileName);
				if (file1.length() > 0) {
					Map<String, String> map = new HashMap<>();
					map.put("fileName", fileName);
					map.put("suffix", suffix);
					map.put("path", currentDate);
					pathList.add(map);
				}
			}
		}

		return pathList;
	}



	/**
	 * 192.168.1.223:8089/web/common/static/resource/showImg?path=20200917&fileName=d24b2f68-4864-4290-a187-ebb85f3b3305@mrrobot.png&suffix=.png
	 * desc: 图片显示
	 * param:
	 * return:
	 */
	@RequestMapping(value = "showImg", method = RequestMethod.POST)
	public Object showImg(HttpServletResponse response, @RequestBody Map<String, Object> map) {

		view(response, map, uploadPath);
		return null;
	}

	/**
	 * 192.168.1.223:8089/web/common/static/resource/show?path=20200917&fileName=d24b2f68-4864-4290-a187-ebb85f3b3305@mrrobot.png&suffix=.png
	 *
	 * @param response
	 * @param map
	 * @return
	 */
	@GetMapping("show")
	public Object show(HttpServletResponse response, @RequestParam Map<String, Object> map) {

		log.info("\n\n\n\nCommonStaticResourceController.show params : {}\n\n\n\n", AnJsonUtils.toJson(map));

		view(response, map, uploadPath);
		return null;
	}

	private void view(HttpServletResponse response, Map<String, Object> map, String path) {

		if (map.isEmpty()) {

			log.info("文件不能为空");
			return;
		}

		boolean suffix = checkPic(map.get("suffix").toString());

		if (!suffix) {
			log.info("不是图片");
			return;
		}

		try {
			ServletOutputStream outputStream = response.getOutputStream();

			String fileUrl = path + map.get("path").toString() + File.separator + map.get("fileName").toString();

			outputStream.write(FileUtil.readBytes(fileUrl));

			IoUtil.close(outputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 192.168.1.223:8089/web/common/static/resource/download?path=20200917&fileName=d24b2f68-4864-4290-a187-ebb85f3b3305@mrrobot.png
	 * <p>
	 * desc: 文件下载
	 * param:    http://127.0.0.1:83/download?path=20200709&fileName=63610ee-862c-4b55-9461-4c1ffe18e1c8@%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20200622141419.jpg
	 * return:
	 */
	@ApiOperation(value = "下载文件-根据-相对路径|文件名 eg 192.168.1.223:8089/web/common/static/resource/download?path=20200917&fileName=d24b2f68-4864-4290-a187-ebb85f3b3305@mrrobot.png")
	@GetMapping("download")
	public Object download(HttpServletResponse response, @RequestParam Map<String, Object> map) throws IOException {

		if (map.isEmpty()) {
			return "文件不能为空";
		}

		String fileUrl = uploadPath + map.get("path").toString() + File.separator + map.get("fileName").toString();
//        String suffix = map.get("suffix").toString();
		ServletOutputStream outputStream = response.getOutputStream();
		response.setContentType("application/force-download");
		// 设置编码,避免文件名中文乱码
		response.setHeader("Content-Disposition", "attachment;filename=" + new String(map.get("fileName").toString().getBytes("gb2312"), "ISO8859-1"));
		outputStream.write(FileUtil.readBytes(fileUrl));
		IoUtil.close(outputStream);
		return null;
	}


	/**
	 * 图片格式检验
	 *
	 * @param suffix
	 * @return
	 */
	private static boolean checkPic(String suffix) {
		if (suffix.isEmpty()) {
			return false;
		}
		String  reg     = "(.JPEG|.jpeg|.JPG|.jpg|.PNG|.png|.GIF|.gif|.BMP|.bmp)$";
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher("." + suffix);
		return matcher.find();
	}

	@ApiOperation(value = "删除文件-根据-绝对路径")
	@PostMapping("delete")
	public R<String> delete(@RequestBody CommonStaticResourceDeleteTargetInfoForm form) {

		if (FileUtil.isFile(form.getAbsolutePath())) {
			FileUtil.del(form.getAbsolutePath());
			return ResponseResultOuterUtils.createSuccesResult("200", "删除成功");
		} else {
			return ResponseResultOuterUtils.createErrorResult("500", "文件不存在");
		}
	}


}
