package cn.component.file;

import cn.config.SysConfig;
import cn.constant.CharsetKit;
import cn.constant.CommonConst;
import cn.common.page.response.Result;
import cn.util.core.IsKit;
import cn.util.core.LogKit;
import cn.util.core.TypeKit;
import cn.util.file.FileTypeKit;
import cn.util.file.FileKit;
import cn.util.uuid.UUIDKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import cn.facade.abs.IFile;
import cn.cloud.util.file.MinioUtil;
import cn.cloud.util.file.OssBootUtil;

/**文件上传工具类*/
@Component
public class FileUpload extends IFile
{
	@Autowired
	protected SysConfig sysConfigService;
	
	/**
     * 本地：local minio：minio 阿里：alioss
     */
    @Value(value="${sam.file.uploadType}")
    private String uploadType;

    /***app專用*/
    private String appDirName = "app";
    public String uploadFile(HttpServletRequest request,String appDirName)
    {
        this.appDirName = appDirName;
        String bizPath = request.getParameter("biz");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
        if(IsKit.isEmpty(bizPath)){
            if(CommonConst.UPLOAD_TYPE_OSS.equals(uploadType)){
                //未指定目录，则用阿里云默认目录 upload
                bizPath = "upload";
            }else{
                bizPath = "";
            }
        }
        String savePath = "";
        if(CommonConst.UPLOAD_TYPE_LOCAL.equals(uploadType)){
            savePath = this.uploadLocal(file,bizPath);
        }
        else if(CommonConst.UPLOAD_TYPE_MINIO.equals(uploadType)){
            savePath = MinioUtil.upload(file,bizPath);
        }
        else if(CommonConst.UPLOAD_TYPE_OSS.equals(uploadType)) {
            savePath = OssBootUtil.upload(file,bizPath);
        }
      return savePath;
    }

    /**
     * 本地文件上传
     * @param mf 文件
     * @param bizPath  自定义路径
     * 需调试保存的路径是否对
     */
    public String uploadLocal(MultipartFile mf,String bizPath){
        try {
            if(IsKit.isNotNullOrEmpty(bizPath)){
                appDirName = bizPath;
            }
            //保存文件的完整路径 含有URL
            String filePath = fileService.getFileFullPath(appDirName);
            /** 原来的
             * String ctxPath = uploadpath;
             * File file = new File(ctxPath + File.separator + bizPath + File.separator );
             */
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            String fileName = fileService.genFileName(mf);
            String savePath = file.getPath() + File.separator + fileName;
            FileCopyUtils.copy(mf.getBytes(), new File(savePath));
            String dbpath = null;
            if(IsKit.isNotEmpty(bizPath)){
                dbpath = bizPath + File.separator + fileName;
            }else{
                dbpath = fileName;
            }
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            return dbpath;
        } catch (IOException e) {
            LogKit.info(e.getMessage());
        }
        return "";
    }

    /**没有调试*/
    public String uploadOnlineImage(byte[] data,String basePath,String bizPath,String uploadType)
    {
        String dbPath = null;
        String fileName = "image" + Math.round(Math.random() * 100000000000L);
        fileName += "." + fileService.getFileExtendName(data);
	    try {
            if(CommonConst.UPLOAD_TYPE_LOCAL.equals(uploadType)){
                File file = new File(basePath + File.separator + bizPath + File.separator );
                if (!file.exists()) {
                    file.mkdirs();// 创建文件根目录
                }
                String savePath = file.getPath() + File.separator + fileName;
                File savefile = new File(savePath);
                FileCopyUtils.copy(data, savefile);
                dbPath = bizPath + File.separator + fileName;
            }else {
                InputStream in = new ByteArrayInputStream(data);
                String relativePath = bizPath+"/"+fileName;
                if(CommonConst.UPLOAD_TYPE_MINIO.equals(uploadType)){
                    dbPath = MinioUtil.upload(in,relativePath);
                }else if(CommonConst.UPLOAD_TYPE_OSS.equals(uploadType)){
                    dbPath = OssBootUtil.upload(in,relativePath);
                }
            }
        } catch (Exception e) {
            LogKit.info(e.getMessage());
        }
        return dbPath;
    }


	/**保存文件到指定目录下. 返回硬盘上的文件名**/
	public String uploadFile(MultipartFile multipartFile,String fileName,String dirPath) 
	{
		if(CommonConst.UPLOAD_TYPE_MINIO.equals(uploadType)) {
			   
		}
		else if(CommonConst.UPLOAD_TYPE_OSS.equals(uploadType)) {
			   
		}
		return _uploadFileToLocal(multipartFile,fileName,dirPath,null);
	}
	
	
	/**保存文件到指定目录下. 返回硬盘上的文件名**/
	public String uploadFile(MultipartFile multipartFile,Map<String,Object> paramMap) 
	{
		//页面给出：文件保存目录
		String dirPath = TypeKit.objToStr(paramMap.get("DirName"));
		//页面给出：文件名
		String fileName = TypeKit.objToStr(paramMap.get("FileName"));
		//页面给出：文件名前缀
		String filePrefix = TypeKit.objToStr(paramMap.get("FilePrefix"));
		
		if(CommonConst.UPLOAD_TYPE_MINIO.equals(uploadType)) {
			   
		}
		else if(CommonConst.UPLOAD_TYPE_OSS.equals(uploadType)) {
			   
		}
		return _uploadFileToLocal(multipartFile,fileName,dirPath,filePrefix);
	}	
	
	/**保存文件到指定目录下. 返回硬盘上的文件名**/
	private String _uploadFileToLocal(MultipartFile multipartFile,
			String fileName,String dirPath,String filePrefix) 
	{
		if (multipartFile.isEmpty()) {
			//throw new BaseException("文件对象名称({})为空！");
			return null;
		}
		//页面所选文件的文件名
		String originalFilename = multipartFile.getOriginalFilename();
		if (IsKit.isNull(originalFilename)) {
			//throw new BaseException("文件对象名称({})非法!");
			return null;
		}

		//获取文件后缀
		String suffix = FileTypeKit.getFileType(originalFilename);
		//服务器上的文件名.如果页面没有给出，就采用原来的文件名
		if(IsKit.isNotNullOrEmpty(fileName))
		{
		    //由系统自动产生文件名	
			if("*".equals(fileName)) {
				fileName = UUIDKit.getUUID_32();
			}
			if(!fileName.contains("." )) {
				fileName = fileName + "." + suffix;
			}		
			originalFilename = fileName;
		}
		//处理文件名前缀  页面给出
		/**CharsetKit.SYMBOL_HIFEN文件前缀与文件名之间的分隔符**/
		if(IsKit.isNotNullOrEmpty(filePrefix)){
			originalFilename  = filePrefix + CharsetKit.SYMBOL_HIFEN  + originalFilename;
		}
		//文件保存目录
		String dirName = "temp";
		if(IsKit.isNotNullOrEmpty(dirPath)){
			dirName = dirPath;
		}
		//保存文件的完整路径 含有URL
		String filePath = fileService.getFileFullPath(dirName);
		//写文件到指定位置  
		Boolean writeFlag = FileKit.copy(multipartFile,filePath,originalFilename);
		if(writeFlag) {
			return originalFilename;
		}
		else {
			return null;
		}
	}
}
