package com.elephant.framework.galaxy.aroad.module.common.controller;

import com.elephant.framework.galaxy.aroad.constant.CommonConstants;
import com.elephant.framework.galaxy.aroad.exception.UploadFileException;
import com.elephant.framework.galaxy.aroad.module.codegen.response.R;
import com.elephant.framework.galaxy.aroad.response.UpFileResponse;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * 文件上环fastDFS
 *
 * @author wangjian
 * @date 2019-05-05 16:31:46
 */
@RestController
@RequestMapping("/upload")
public class FileUploadController {

    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * 上传图片
     *
     * @return R
     */
    @PostMapping("/images")
    public R uploadImage(HttpServletRequest request) throws IOException {
        Map<String, String> resultMap = new HashMap<>();
        //将当前上下文初始化给  CommonsMultipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            List<String> supportFileTypes = Arrays.asList("JPG", "JPEG", "PNG", "GIF", "BMP", "WBMP");
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                String name = iter.next().toString();
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(name);
                if (file != null) {
                    String extension = FilenameUtils.getExtension(file.getOriginalFilename());
                    if (StringUtils.isBlank(extension)) {
                        throw new UploadFileException("上传文件类型不支持");
                    }
                    if (!supportFileTypes.contains(extension.toUpperCase())) {
                        throw new UploadFileException("上传文件类型不支持");
                    }
                    StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
                            file.getInputStream(), file.getSize(), extension, null);
                    resultMap.put(name, storePath.getFullPath());
                }
            }
            return new R<>(resultMap);
        }
        return new R(CommonConstants.FAIL, "没有上传文件");
    }

    /**
     * 上传文件
     *
     * @return R
     */
    @PostMapping("/files")
    public R uploadFiles(HttpServletRequest request) throws IOException {
        Map<String, String> resultMap = new HashMap<>();
        //将当前上下文初始化给  CommonsMultipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            List<String> supportFileTypes = Arrays.asList("TXT", "XLS", "XLSX", "DOC", "DOCX", "PPT", "PPTX", "RAR", "ZIP");
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                String name = iter.next().toString();
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(name);
                if (file != null) {
                    String extension = FilenameUtils.getExtension(file.getOriginalFilename());
                    if (StringUtils.isBlank(extension)) {
                        throw new UploadFileException("上传文件类型不支持");
                    }
                    if (!supportFileTypes.contains(extension.toUpperCase())) {
                        throw new UploadFileException("上传文件类型不支持");
                    }
                    StorePath storePath = this.storageClient.uploadFile(
                            file.getInputStream(), file.getSize(), extension, null);
                    resultMap.put(name, storePath.getFullPath());
                }
            }
            return new R<>(resultMap);
        }
        System.out.println("没有上传文件");
        return new R(CommonConstants.FAIL, "没有上传文件");
    }

    @PostMapping("/file")
    public UpFileResponse uploadFile(HttpServletRequest request) throws IOException {
        Map<String, String> resultMap = new HashMap<>();
        //将当前上下文初始化给  CommonsMultipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            List<String> supportFileTypes = Arrays.asList("TXT", "XLS", "XLSX", "DOC", "DOCX", "PPT", "PPTX", "RAR", "ZIP");
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                String name = iter.next().toString();
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(name);
                if (file != null) {
                    String extension = FilenameUtils.getExtension(file.getOriginalFilename());
                    if (StringUtils.isBlank(extension)) {
                        throw new UploadFileException("上传文件类型不支持");
                    }
                    if (!supportFileTypes.contains(extension.toUpperCase())) {
                        throw new UploadFileException("上传文件类型不支持");
                    }
                    StorePath storePath = this.storageClient.uploadFile(
                            file.getInputStream(), file.getSize(), extension, null);

                    return new UpFileResponse(file.getOriginalFilename(),storePath.getFullPath());
//                    resultMap.put(name, storePath.getFullPath());
                }
            }
//            return new R<>(resultMap);
        }
//        System.out.println("没有上传文件");
//        return new R(CommonConstants.FAIL, "没有上传文件");
        return null;
    }
}
