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.ImageTools;
import com.wisedu.coeus.util.Strings;
import com.wisedu.mooc.app.thirdparty.service.ThirdpartyInstance;
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 com.wisedu.mooc.app.user.UserConstant;

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

/**
 * 用户头像上传处理类
 * @author 01115035
 *
 */
public class UserUploadServiceImpl extends UploadService  {

    String pathJoin = RsConstant.PATH_JOIN;
    
    /**
     * 校验文件后缀是否符合
     * @param fileExt 文件后缀名
     * return boolean true:符合，false:不符合
     */
    @Override
    public boolean isFileExtValid(String fileExt) {
        if(!"".equals(fileExt)&&RsConstant.USER_IMAGE_SUFFIX.contains(fileExt)){
            return true;
        }
        return false;
    }

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

    	/**系统本地绝对路径 **/
        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.USR_PIC_PATH);
        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);
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-", "");
        relativePath.append(uuid);
        relativePath.append(pathJoin);
        /**生成文件的绝对路径目录**/
        String direct = rsRootPath+relativePath.toString();
        File fileDir = new File(direct);
        if(fileDir.exists()){
            fileDir.mkdirs();
        }

        relativePath.append(RsConstant.UPLOAD_FILE_ORIGINAL+"."+super.fileExt);

        File tempFileDir = new File(tempFilePath);
        if(!tempFileDir.exists()){
            tempFileDir.mkdirs();
        }
        String tempFileName =uuid+"."+super.fileExt;
        /**初始化工具类的相应属性**/
        uploadVo.setFileRelativePath(Strings.replaceFileSep(relativePath.toString())) ;
        //uploadVo.setFileAbsolutePath(rsRootPath+relativePath);
        uploadVo.setFileTempPath(tempFilePath+pathJoin+tempFileName);
        uploadVo.setFileTempUrl(Strings.replaceUrlSep(ConstantStatic.getResourceDomain() + tempFilePath+pathJoin+tempFileName));
    }


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

        //文件的真实名称
        if("".equals(super.uploadVo.getFileAbsolutePath())||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;
    }

    /**
     * 文件提交处理操作
     * @param uploadVo 文件上传工具类
     */
    @Override
    public void uploadEndOperate(UploadVo uploadVo)  throws UploadException {
        if(Strings.isEmpty(uploadVo)){
            throw new UploadException("","");
        }
        /**获取文件的真实与临时目录的绝对路径 **/
        uploadVo.setFileTempPath(ConstantStatic.RESOURCE_PATH+uploadVo.getFileTempPath());
        uploadVo.setFileAbsolutePath(ConstantStatic.RESOURCE_PATH+uploadVo.getFileRelativePath());
        //要切割清晰的图片我们需要这个值转换为图片的原始尺寸图下的x,y,w,h
        Integer[] whxy =  new Integer[]{0,0,0,0};
        if (uploadVo.getWidth() != null && uploadVo.getWidth() > 0 && uploadVo.getHeight() != null && uploadVo.getHeight() > 0 ) {
            try {
                whxy = ImageTools.getImageNewWHXY(uploadVo.getFileTempPath(), 180, uploadVo.getAxisX(), uploadVo.getAxisY(), uploadVo.getWidth(), uploadVo.getHeight());
            } catch (IOException e2) {
                throw new UploadException("IMG_W_H_FAILED","操作图片失败!");
            }
        }

        //真实路径
        String absolutePath = uploadVo.getFileAbsolutePath();
        String relativePath = uploadVo.getFileRelativePath();
        //临时文件的存放路径，也就是提供前台预览的路径
        String previewFilePath = uploadVo.getFileTempPath();

        //把前台预览的路径图拷贝到真实路径下
        try {
            FileUtils.copyFile(new File(previewFilePath), new File(absolutePath));
        } catch (IOException e1) {
            throw new UploadException(UploadException.UPLOAD_SAVE_FILE_ERROR,null,"upload.save.file_error");
        }
        //读取文件，拿出上级节点，构造新的图片文件
        File file = new File(absolutePath);
        String fileName = file.getName();
        String parentPath = file.getParent();

        //按照转换后的图片尺寸切割一张IMG
        String cutFilePath = parentPath+pathJoin+fileName.replace(RsConstant.UPLOAD_FILE_ORIGINAL,ConstantStatic.TEMP_FILE_PATH);
        if (whxy[2] >0 && whxy[3] > 0) {
            try {
                ImageTools.cutImage(absolutePath, cutFilePath, whxy[0],whxy[1], whxy[2], whxy[3]);
            } catch (IOException e) {
                throw new UploadException("IMG_ZOOM_FAILED","操作图片失败!");
            }
        } else {
            try {
                FileUtils.copyFile(new File(absolutePath), new File(cutFilePath));
            } catch (IOException e1) {
                throw new UploadException(UploadException.UPLOAD_SAVE_FILE_ERROR,null,"upload.save.file_error");
            }
        }

        Map<String, String> map = new HashMap<String, String>();
        /**如果使用阿里云的OSS处理头像 **/
        if(ConstantStatic.UPLOAD_RESOURCE_TYPE.equals(ConstantStatic.UPLOAD_RESOURCE_TYPE_ALIYUN)){ 
        	cutFilePath = Strings.replaceUrlSep(Strings.replaceUrlSep(cutFilePath).replace(Strings.replaceUrlSep(ConstantStatic.RESOURCE_PATH), ""));
        	String targetPath = cutFilePath;
        	try {
	        	ThirdpartyInstance.getThirdpartyService().doUpload(cutFilePath,targetPath.substring(1));
        	}  catch (Exception e) {
                throw new UploadException("IMG_UPLOAD_FAILED","图片上传失败!");
            }
        	map.put("parentPath",cutFilePath);
    	}else{   //本地处理头像
    		//按照系统要求把切割后的图片做也所处理
            String [] pxs = UserConstant.USER_HEAD_PX.split(";");
            String ext = UserConstant.USER_HEAD_TYPE;//fileName.replace(RsConstant.UPLOAD_FILE_ORIGINAL,"");
            String userHeadImg = "";
            /**根据配置文件中配置的头像大小生成对应的头像图片 **/
            for(String px : pxs){
                String pxFileName = parentPath+pathJoin+px+ext; //fileName.replace(RsConstant.UPLOAD_FILE_ORIGINAL, px);
                try {
                    userHeadImg = userHeadImg.length()==0?userHeadImg+px+ext:userHeadImg+","+px+ext;
                    ImageTools.zoomImage(1, cutFilePath, pxFileName,Integer.valueOf(px),Integer.valueOf(px));
                }  catch (IOException e) {
                    throw new UploadException("IMG_ZOOM_FAILED","操作图片失败!");
                }
            }
            parentPath = relativePath.replace(fileName, "");
            map.put("userHeadImg", userHeadImg);
            /**把生成头像图片的路径写入到map返回 **/
            map.put("parentPath",Strings.replaceUrlSep(parentPath));
            //删除原来的预览图
            File previewFile = new File(previewFilePath);
            if(previewFile.exists()){
                //previewFile.delete();
            }

            //删除刚创建的切割后的临时图片
            File cutFile = new File(cutFilePath);
            if(cutFile.exists()){
                //cutFile.delete();
            }
    	}
        uploadVo.setUploadMap(map);
    }


}
