package com.izouma.awesomeadmin.web;

import com.izouma.awesomeadmin.dto.Result;
import com.izouma.awesomeadmin.service.OSSFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
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.io.UnsupportedEncodingException;
import java.util.Iterator;

/**
 * Created by xiongzhu on 2017/3/8.
 */
@Controller
@RequestMapping("/assets")
public class AssetsController {

    @Autowired
    private OSSFileService OSSFileService;


    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    @ResponseBody
    public Result uploadImg(@RequestParam(value = "base64", required = true) String base64) {

        try {
            String path = OSSFileService.uploadImg(base64);
            return new Result(true, path);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new Result(false, "上传失败");
    }


    @RequestMapping(value = "/uploadFile")
    @ResponseBody
    public Result uploadFile(HttpServletRequest request) {

        long startTime = System.currentTimeMillis();
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();

            String paths = "";

            while (iter.hasNext()) {
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    try {
                        String path = OSSFileService.upload(file.getInputStream(), "izouma/application/" + System.currentTimeMillis()
                                + file.getOriginalFilename().replaceAll(".+\\.", "."));
                        paths += path + ";";

                    } catch (IOException e) {
                        e.printStackTrace();
                        return new Result(false, "上传失败");
                    }
                }

            }
            return new Result(true, paths.split(";"));
        }
        return new Result(false, "上传失败");
    }
}
