package com.yeejoin.precontrol.controller.publics;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.precontrol.common.exception.BaseException;
import com.yeejoin.precontrol.common.service.FileService;
import com.yeejoin.precontrol.common.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
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 org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 上传下载管理
 *
 * @author zcx
 */
@RestController
@RequestMapping(value = "/file")
@Api(tags = "附件Api")
@Slf4j
public class FileController {

	@Autowired
	FileService fileService;

	/**
	 * 上传路径
	 */
	@Value("${file.uploadUrl}")
	private String fileUploadDir;

	/**
	 * 文件读取参数
	 */
	@Value("${file.readUrl}")
	private String readUrl;

	/**
	 * 文件上传 只返回路径
	 * 
	 * @param file
	 * @return
	 */
	@ApiOperation(httpMethod = "POST", value = "文件上传", notes = "文件上传")
	@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
	public Object uploadfile(@RequestPart("file") MultipartFile file) {
		try {
			Long fileSize = file.getSize() / 1024 / 1024;
			String fileName = file.getOriginalFilename();
			List<String> fileSuffix = new ArrayList<>();
			fileSuffix.add(".png");
			fileSuffix.add(".jpg");
			fileSuffix.add(".bmp");
			fileSuffix.add(".pdf");
			fileSuffix.add(".doc");
			AtomicReference<Boolean> fileSizeFlag = new AtomicReference<>(false);
			fileSuffix.forEach(fs -> {
				if (fileName.endsWith(fs)) {
					fileSizeFlag.set(true);
				}
			});

			// 如果是图片这一堆的 就直接抛出异常
			if (fileSizeFlag.get()) {
				if (fileSize > 10) {
					throw new BaseException("上传文件过大[单个文件大小不得超过10M]");
				}
			}
			return fileService.uploadfile(file);
		} catch (Exception e) {
			log.error(e.getMessage());
			return CommonResponseUtil.failure(e.getMessage());
		}
	}

	/**
	 * 文件上传 返回路径带名称
	 * 
	 * @param file
	 * @return
	 */
	@ApiOperation(httpMethod = "POST", value = "文件上传", notes = "文件上传")
	@RequestMapping(value = "/uploadFileReturnName", method = RequestMethod.POST)
	public Object uploadFileReturnName(@RequestPart("file") MultipartFile file, String name, String personType) {
		Map<String, String> map = new HashMap<>();
		try {
			Long fileSize = file.getSize() / 1024 / 1024;
			String fileName = file.getOriginalFilename();
			List<String> fileSuffix = new ArrayList<>();
			fileSuffix.add(".png");
			fileSuffix.add(".jpg");
			fileSuffix.add(".bmp");
			fileSuffix.add(".pdf");
			fileSuffix.add(".doc");
			AtomicReference<Boolean> fileSizeFlag = new AtomicReference<>(false);
			fileSuffix.forEach(fs -> {
				if (fileName.endsWith(fs)) {
					fileSizeFlag.set(true);
				}
			});
			// 如果是图片这一堆的 就直接抛出异常
			if (fileSizeFlag.get()) {
				if (fileSize > 10) {
					throw new BaseException("上传文件过大[单个文件大小不得超过10M]");
				}
			}
			String uploadfile = fileService.uploadfile(file);
			map.put("filePath", uploadfile);
			map.put("fileName", name);
			map.put("personType", personType);
			return map;
		} catch (IOException e) {
			throw new BaseException("上传文件失败");
		}
	}

	/**
	 * 多文件上传
	 * 
	 * @param files
	 * @return
	 */
	@ApiOperation(httpMethod = "POST", value = "多文件上传", notes = "多文件上传")
	@RequestMapping(value = "/uploadfiles", method = RequestMethod.POST)
	public Object uploadfile(@RequestPart("files") MultipartFile[] files) {
		ArrayList<String> filePaths = new ArrayList<>();
		try {
			filePaths = fileService.uploadfiles(files);
		} catch (Exception e) {
			return CommonResponseUtil.failure("上传失败");
		}
		return filePaths;
	}

	/**
	 * @return
	 * @author: nihuanshan
	 * @date: 2018年11月30日 下午3:15:38
	 */
	@PostMapping(value = "/lookHtmlText", produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "查看文件内容", notes = "查看文件内容")
	public Object lookHtmlText(@ApiParam(value = "查看文件内容", required = true) @RequestBody String file) throws Exception {
		JSONObject obj = JSONObject.parseObject(file);
		String fileName = fileUploadDir;
		if (obj.containsKey("file")) {
			fileName += obj.getString("file");
		}
		File fi = new File(fileName);
		if (!fi.exists()) {
			return CommonResponseUtil.success("访问的文件不存在!", "查询成功");
		}
		if (fileName.endsWith(".pdf")) {
			String data = obj.getString("file");
			return CommonResponseUtil.success(data, "查询成功");
		} else if (fileName.endsWith(".doc") || fileName.endsWith(".docx")) {
			String htmlFileName = fileName.substring(0, fileName.indexOf(".")) + ".html";
			File htmlFile = new File(htmlFileName);
			WordConverterUtils.wordToHtml(fileName, htmlFileName, readUrl);
			FileInputStream fis = new FileInputStream(htmlFile);
			// "gb2312"
			String data = IOUtils.toString(fis, "utf-8");
			fis.close();
			return CommonResponseUtil.success(data, "查询成功");
		} else {
			return CommonResponseUtil.success("访问的文件不存在!", "查询成功");
		}

	}

	/**
	 * 查看文档（加导航栏）
	 *
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/lookHtmlTextNav", produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "查看文件内容（加导航栏）", notes = "查看文件内容（加导航栏）")
	public ResponseModel lookHtmlTextNav(@ApiParam(value = "查看文件内容（加导航栏）", required = true) @RequestBody String file) {
		JSONObject obj = JSONObject.parseObject(file);
		String fileName = fileUploadDir;
		if (obj.containsKey("file")) {
			fileName += obj.getString("file");
		}
		File fi = new File(fileName);
		if (!fi.exists()) {
			return CommonResponseUtil.success("访问的文件不存在!", "查询成功");
		}
		if (fileName.endsWith(".doc") || fileName.endsWith(".docx")) {
			String htmlFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".html";
			File htmlFile = new File(htmlFileName);
			String data = WordConverterUtils.wordToHtmlString(fileName, readUrl);
			Map<String, Object> processData = null;
			if (fileName.endsWith(".doc")) {
				processData = DocUtil.processDoc(data);
			} else {
				processData = DocUtil.processDocx(data);
			}

			String htmlContent = (String) processData.get("html");
			try {
				Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFileName), "UTF-8"));

				writer.write(htmlContent);
				writer.flush();
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			String filePath = obj.getString("file");
			processData.put("html", "/" + filePath.substring(0, filePath.lastIndexOf(".")) + ".html");

			return CommonResponseUtil.success(processData, "查询成功");
		}
		if (fileName.endsWith(".pdf")) {
			Map<String, Object> processData = new HashMap<String, Object>();
			MyNode node = PdfUtil.getPdfNavs(fileName);
			processData.put("nodes", node.getChildren());
			String filePath = obj.getString("file");
			processData.put("html", "/" + filePath.substring(0, filePath.lastIndexOf(".")) + ".pdf");
			return CommonResponseUtil.success(processData, "查询成功");
		} else {
			return CommonResponseUtil.success("文件类型不为doc/docx", "查询成功");
		}
	}

	/**
	 * 获取文件服务器地址
	 * 
	 * @param files
	 * @return
	 */
	@ApiOperation(httpMethod = "GET", value = "获取文件服务器地址", notes = "获取文件服务器地址")
	@RequestMapping(value = "/domain", method = RequestMethod.GET)
	public Object uploadfile() {
		return fileService.getDomain();
	}

}
