package com.wisedu.mooc.app.upload.service.impl;

import com.wisedu.coeus.core.ConstantStatic;
import com.wisedu.coeus.util.FileUtils;
import com.wisedu.coeus.util.Strings;
import com.wisedu.mooc.app.upload.RsConstant;
import com.wisedu.mooc.app.upload.exception.UploadException;
import com.wisedu.mooc.app.upload.service.UploadService;
import com.wisedu.mooc.app.upload.vo.UploadVo;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.UUID;

/**
 * 资源上传处理类
 * @author 01115035
 *
 */
public class ResUploadServiceImpl extends UploadService {


	/**
     * 校验文件后缀是否符合
     * @param fileExt 文件后缀名
     * return boolean true:符合，false:不符合
     */
    public boolean isFileExtValid(String fileExt) {
        return true;
    }

    /**
     * 初始化文件上传工具类UploadVo
     * @param fileName
     */
    public void setFilePath(String fileName) throws UploadException {

        String pathJoin = RsConstant.PATH_JOIN;
        /**系统本地绝对路径 **/
        String rsRootPath = ConstantStatic.RESOURCE_PATH;
        /**相对路径*/
        StringBuilder relativePath = new StringBuilder();
        String urlHead = RsConstant.getOssUrlHead();
        if(Strings.isNotEmpty(urlHead)){
            relativePath.append(urlHead);
        }
        relativePath.append(pathJoin);
        relativePath.append("repositry");
        relativePath.append(pathJoin);
        /**临时文件相对路径 **/
        String tempFilePath = relativePath + ConstantStatic.TEMP_FILE_PATH;
        relativePath.append(RsConstant.NODES_PATH);
        relativePath.append(pathJoin);
        String typePath = RsConstant.getRsTypePath(fileExt);
        relativePath.append(typePath);
        relativePath.append(pathJoin);
        //日
        String day = String.valueOf(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
        relativePath.append(getYearAndMonth());
        relativePath.append(pathJoin);
        relativePath.append(day);
        relativePath.append(pathJoin);

        if (typePath.equals(RsConstant.RS_OTHER_PATH)) {
            fileExt = fileExt + RsConstant.SPECIAL_FILE_EXT_APPEND;
        }
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-", "");
        /**生成文件的绝对路径目录**/
        String direct = rsRootPath + relativePath.toString();
        File fileDir = new File(direct);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        String tempFileName = uuid + "." + super.fileExt;
        /**初始化工具类的相应属性**/
        uploadVo.setFileRelativePath(Strings.replaceUrlSep(relativePath.toString() + tempFileName));
        String fileTempPath = Strings.replaceUrlSep(tempFilePath + RsConstant.PATH_JOIN + tempFileName);
        uploadVo.setFileTempPath(fileTempPath);
        uploadVo.setFileTempUrl(ConstantStatic.getResourceDomain() + fileTempPath);
    }


    /**
     * 保存文件
     *
     * @param inputStream
     * @param fileName
     * @return UploadVo
     * @throws UploadException
     */
    public UploadVo saveFile(InputStream inputStream, String fileName) throws UploadException {

        //文件的真实名称
        if (Strings.isEmpty(super.uploadVo.getFileAbsolutePath())) {
            setFilePath(fileName);
        }
        try {
        	/**输入流写入临时目录文件 **/
            FileUtils.copyInputStreamToFile(inputStream, new File(ConstantStatic.RESOURCE_PATH + super.uploadVo.getFileTempPath()));
        } catch (IllegalStateException e) {
            throw new UploadException(UploadException.UPLOAD_SAVE_FILE_ERROR, null, "upload.save.file_error");

        } catch (IOException e) {
            throw new UploadException(UploadException.UPLOAD_SAVE_FILE_ERROR, null, "upload.save.file_error");
        }
        return super.uploadVo;
    }

    public void uploadEndOperate(UploadVo uploadVo) throws UploadException {
    	/**获取文件的真实与临时目录的绝对路径 **/
        String tempFilePath = ConstantStatic.RESOURCE_PATH + uploadVo.getFileTempPath();
        String absoluteFilePath = ConstantStatic.RESOURCE_PATH + uploadVo.getFileRelativePath();
        if (Strings.isNotEmpty(tempFilePath) && Strings.isNotEmpty(absoluteFilePath)) {
            File f = new File(tempFilePath);
            if (f.exists() && f.isFile()) {
                try {
                	/**把当前文件移动到目标文件位置 **/
                    FileUtils.moveFile(f, new File(absoluteFilePath));
                } catch (IOException e) {
                    throw new UploadException(UploadException.MOVE_FILE_ERROR, null);
                }
            } else {
                throw new UploadException(UploadException.MOVE_FILE_NOT_EXIST, null);
            }
        }
    }

}
