package com.nbclass.szxgl.controller.mobile;

import com.nbclass.exception.ParameterException;
import com.nbclass.system.controller.BaseController;
import com.nbclass.szxgl.model.ProjectFiles;
import com.nbclass.util.ResultUtil;
import com.nbclass.util.Utility;
import com.nbclass.vo.base.ResponseVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 公共文件上传接口
 * @Author leiyun
 * @Date 2021/3/11 17:10
 **/
@RestController
@RequestMapping("/mobile/api/file")
public class FileUploadController extends BaseController {

	// CDN保存目录
	private static final String upload_dir = "/mnt/cdn/worktile";

	// CDN域名
	private static final String cdn_domain = "https://cdn.szxgl.cn";


	/**
	 * 上传文件接口，支持批量上传
	 * @param files
	 * @param category
	 * @return
	 */
	@PostMapping("/upload")
	public ResponseVo fileUploadTest(@RequestParam(required=false, value="files") MultipartFile[] files, String category){
		if (null == files || files.length < 1) {
			throw new ParameterException("请选择文件");
		}
		if(StringUtils.isBlank(category)){
			throw new ParameterException("文件类别不能为空");
		}
    	category = category.toLowerCase().trim();
		// 后台限制根目录名，防止前端随意提交
    	if(!Arrays.asList("project_files,attachment".split(",")).contains(category)) {
			throw new ParameterException("文件类别参数有误");
		}

		List<ProjectFiles> list = new ArrayList<>();
		try {
			for (MultipartFile file : files) {
				if(file==null || file.isEmpty())continue;
				String suffix = "", original_name = file.getOriginalFilename();
				if(StringUtils.isNotBlank(original_name)){
					suffix = original_name.substring(original_name.lastIndexOf(".")+1);
					suffix = suffix.toLowerCase();
				}

				String filePath = upload_dir+"/"+category+"/"+ Utility.getDateFormat(new Date(), "yyyyMM")+"/";
				String fileName = System.currentTimeMillis()+ "_"+Utility.getRandomCode(5).toLowerCase()+"."+suffix;
				File dest = new File(filePath + fileName);
				//if(!dest.getParentFile().exists())dest.getParentFile().mkdirs();
				FileUtils.forceMkdirParent(dest); // 强制创建父目录
				dest.createNewFile();
				file.transferTo(dest);

				filePath = filePath.replace("/mnt/cdn/","");
				String fileUrl = cdn_domain+"/"+filePath+fileName;
				ProjectFiles pf = new ProjectFiles();
				pf.setFileExt(suffix);
				pf.setFileSize(file.getSize());
				pf.setOriginalName(original_name);
				pf.setFilePath(fileUrl);
				list.add(pf);
			}

			return ResultUtil.success("上传成功",list);
		} catch (IOException e) {
			logger.error("上传文件异常", e);
			return ResultUtil.error(e.getMessage()!=null ? e.getMessage() :"上传文件失败");
		}
	}


}
