package com.ejweb.modules.upload.api;

import com.alibaba.fastjson.JSON;
import com.ejweb.conf.ErrorCode;
import com.ejweb.conf.GConstants;
import com.ejweb.core.api.RequestBean;
import com.ejweb.core.api.ResponseBean;
import com.ejweb.core.utils.IdWorker;
import com.ejweb.core.utils.Util;
import com.ejweb.modules.upload.bean.FileBean;
import com.ejweb.modules.upload.bean.UploadBean;
import com.ejweb.modules.upload.bean.UploadFileBean;
import com.ejweb.modules.upload.service.UploadService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.commons.CommonsMultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @team IT Team
 * @author renmb
 * @version 1.0
 * @time 2016-03-22
 *
 */
@Controller
@RequestMapping(value = "${adminPath}/api/upload")
public class UploadController {

    @Autowired
    private UploadService uploadService;

    /**
     * 使用BASE64上传文件
     * 
     * @author renmb
     * @time 2016年11月1日
     * @param request
     * @param requestBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/base64", method ={RequestMethod.POST}, produces={MediaType.APPLICATION_JSON_VALUE})
    public ResponseBean base64(HttpServletRequest request, RequestBean requestBean) {

        ResponseBean responseBean = new ResponseBean();
        List<UploadFileBean> uploadFiles = null;

        // String clientip = Util.getOnlineIP(request);
        UploadBean uploadFile = null;
        uploadFile = JSON.parseObject(requestBean.getContent(), UploadBean.class);
        String clientip = StringUtils.isEmpty(uploadFile.getClientip()) ? Util.getOnlineIP(request)
                : uploadFile.getClientip();
        String message = uploadService.validate(uploadFile);
        if (message == null) {
            uploadFiles = new ArrayList<UploadFileBean>(6);
            // uploadFile.setFiles(uploadFiles);

            List<UploadFileBean> files = uploadFile.getFiles();
            if (files == null || files.size() == 0) {
                responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
                responseBean.setMessage("获取不到文件列表！");
                return responseBean;
            }
            // 生成本次会话的随机数随机数
            String sessionId = IdWorker.getNextId();
            for (UploadFileBean file : files) {// 遍历所有提交的文件
                try {
                    String originalFilename = file.getName();
                    if (StringUtils.isBlank(originalFilename))
                        originalFilename = "base64.png";
                    if (StringUtils.isNotBlank(originalFilename)) {// 文件扩展名称不能为NULL
                        if (originalFilename.contains("%") || originalFilename.contains(";")) {
                            responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
                            responseBean.setMessage("上传文件不允许含有非法字符，请改正！");
                            return responseBean;
                        }
                    }
                    if (StringUtils.isNotBlank(file.getData())) {// 文件扩展名称不能为NULL

                        BASE64Decoder decoder = new BASE64Decoder();
                        byte[] buf = decoder.decodeBuffer(file.getData());
                        for (int i = 0, len = buf.length; i < len; ++i) {
                            if (buf[i] < 0) {// 调整异常数据
                                buf[i] += 256;
                            }
                        }
                        InputStream in = new ByteArrayInputStream(buf);
                        UploadFileBean fileBean = uploadService.addUploadFile(sessionId, in, file.getName(),
                                originalFilename, "image/png", uploadFile.getModule(), uploadFile.getAppCode(), clientip, "");
                        uploadFiles.add(fileBean);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }
        if (uploadFiles == null || uploadFiles.size() == 0) {

            responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
            responseBean.setMessage("获取不到文件列表！");
            return responseBean;
        }
        uploadFile.setFiles(uploadFiles);
        uploadFile.setSize(uploadFiles.size());
        uploadFile.setUrl(GConstants.FILE_PREFIX_URL);
        responseBean.setStatus(ErrorCode.STATUS_CODE_2000);
        responseBean.setMessage(GConstants.OK);
        responseBean.setData(uploadFile);
        return responseBean;
    }

    @ResponseBody
    @RequestMapping(value="/files", method ={RequestMethod.POST}, produces={MediaType.APPLICATION_JSON_VALUE})
    public ResponseBean files(HttpServletRequest request, @RequestParam("file") CommonsMultipartFile[] files,
            RequestBean requestBean) {

        ResponseBean responseBean = new ResponseBean();
        List<UploadFileBean> uploadFiles = null;

        String clientip = Util.getOnlineIP(request);
        UploadBean uploadFile = null;
        uploadFile = JSON.parseObject(requestBean.getContent(), UploadBean.class);
//        for (CommonsMultipartFile file : files) {// 遍历文件名，含有非法字符提示错误
//            
//            String originalFilename = file.getOriginalFilename();
//            if (StringUtils.isNotBlank(originalFilename)) {// 文件扩展名称不能为NULL
//                if (originalFilename.contains("%") || originalFilename.contains(";")) {
//                    responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
//                    responseBean.setMessage("上传文件不允许含有非法字符，请改正！");
//                    return responseBean;
//                }
//            }
//        }
//        String message = uploadService.check(files, uploadFile, clientip);
//        if (StringUtils.isNotEmpty(message)) {
//            responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
//            responseBean.setMessage(message);
//            return responseBean;
//        }
        uploadFiles = uploadService.addMultipartFile(files, uploadFile, clientip);
        if (uploadFiles == null || uploadFiles.size() == 0) {

            responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
            responseBean.setMessage("获取不到文件列表！");
            return responseBean;
        }
        if(uploadFiles != null && uploadFiles.size() > 0 && uploadFiles.get(0).getPath() == null) {
            responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
            responseBean.setMessage("此类型文件不允许上传");
            return responseBean;
        }
        uploadFile.setSize(uploadFiles.size());
        uploadFile.setUrl(GConstants.FILE_PREFIX_URL);
        responseBean.setStatus(ErrorCode.STATUS_CODE_2000);
        responseBean.setMessage(GConstants.OK);
        responseBean.setData(uploadFile);
        return responseBean;
    }

    @ResponseBody
    @RequestMapping(value="/multipart", method ={RequestMethod.POST}, produces={MediaType.APPLICATION_JSON_VALUE})
    public ResponseBean multipart(HttpServletRequest request, HttpServletResponse response, RequestBean requestBean) {
        ResponseBean responseBean = new ResponseBean();

        // UploadBean uploadFile = null;
        List<UploadFileBean> uploadFiles = null;

        String clientip = Util.getOnlineIP(request);
        // UploadBean uploadFile = null;
        // uploadFile = JSON.parseObject(requestBean.getContent(),
        // UploadBean.class);

        UploadBean uploadFile = new UploadBean();
        // uploadFile.setModule("user/company");
        uploadFile.setAppCode(GConstants.DEFAULT_APP_CODE);

        uploadFiles = uploadService.addMultipartFile(request, uploadFile, clientip);

        if (uploadFiles == null || uploadFiles.size() == 0) {

            responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
            responseBean.setMessage("获取不到文件列表！");
            return responseBean;
        }
        uploadFile.setSize(uploadFiles.size());
        uploadFile.setUrl(GConstants.FILE_PREFIX_URL);
        responseBean.setStatus(ErrorCode.STATUS_CODE_2000);
        responseBean.setMessage(GConstants.OK);
        responseBean.setData(uploadFile);
        return responseBean;
    }

    @ResponseBody
    @RequestMapping(value="/token", method ={RequestMethod.POST}, produces={MediaType.APPLICATION_JSON_VALUE})
    public Map<String, Object> token(HttpServletRequest req, HttpServletResponse resp) {
        // 创建一个通用的多部分解析器

        // final String token = req.getParameter("token");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", true);
        map.put("token", Util.getGenericCode());
        return map;
    }

    @ResponseBody
    @RequestMapping(value="/doUploadFile", method ={RequestMethod.GET}, produces={MediaType.APPLICATION_JSON_VALUE})
    public Map<String, Object> doUploadFile() {
        // 创建一个通用的多部分解析器
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", true);
        map.put("message", "");
        map.put("start", 0);
        return map;
    }

    @ResponseBody
    @RequestMapping(value="/doUploadFile", method ={RequestMethod.POST}, produces={MediaType.APPLICATION_JSON_VALUE})
    public Map<String, Object> doUploadFile(HttpServletRequest request, HttpServletResponse resp) {
        // 创建一个通用的多部分解析器

        int start = 0;
        try {

            start = Integer.parseInt(request.getParameter("size"));
            String name = request.getParameter("name");
            String moduleName = request.getParameter("moduleName");
            String appCode = request.getParameter("appCode") == null ? GConstants.DEFAULT_APP_CODE
                    : request.getParameter("appCode");// 本次文件上传记录CODE
            String clientip = Util.getOnlineIP(request);
            if (StringUtils.isBlank(moduleName)) {// 如果没有传则默认保存到files下面
                moduleName = "files";
            } else {
                moduleName = moduleName.replaceAll("^/+|/+$|[^0-9|a-z|A-Z|/]+", "");// 替换非法字符串
                if (moduleName.length() == 0 || moduleName.length() > 64)// 如果没有传则默认保存到files下面
                    moduleName = "files";
            }
            String sessionId = DigestUtils.md5Hex(
                    Util.getRandom(100, 999) + ":" + System.currentTimeMillis() + ":" + Util.getRandom(100, 999));
            UploadFileBean fileBean = null;
            fileBean = uploadService.addUploadFile(sessionId, request.getInputStream(), "", name, "", moduleName, appCode,
                    clientip, "");
            if (fileBean != null) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("success", true);
                map.put("message", "");
                map.put("start", start);
                map.put("file", fileBean);
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);
        map.put("message", "");
        map.put("start", 0);
        return map;
    }

    @ResponseBody
    @RequestMapping(value="/download", method ={RequestMethod.GET}, produces={MediaType.APPLICATION_JSON_VALUE})
    public void download(RequestBean requestBean, HttpServletResponse response, HttpServletRequest request) {

        FileBean bean = requestBean.getObjectBean(FileBean.class);
        // File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, filepath);
        InputStream in = null;
        OutputStream out = null;
        try {

            // 设置文件MIME类型
            response.setContentType("application/form-data;charset=utf-8");
            // String downloadFileName=Encodes.urlEncode(bean.getName());
            String downloadFileName = new String(bean.getName().getBytes("gbk"), "ISO8859-1");
            String agent = (String) request.getHeader("USER-AGENT");
            if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
                downloadFileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(bean.getName().getBytes("UTF-8"))))
                        + "?=";
            } /*
               * else{ downloadFileName = URLDecoder.decode(bean.getName(),
               * "UTF-8"); }
               */
            // 设置Content-Disposition
            response.setHeader("Content-Disposition", "attachment; filename=" + downloadFileName);
            // 获取目标文件的绝对路径
            String fullFileName = GConstants.FILE_UPLOAD_DIR + bean.getPath();

            // 读取文件
            in = new FileInputStream(fullFileName);
            out = response.getOutputStream();

            // 写文件
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }
}
