package com.ejweb.modules.front.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.util.Util;
import com.ejweb.core.utils.IdGen;
import com.ejweb.core.utils.IdWorker;
import com.ejweb.modules.front.upload.bean.FileBean;
import com.ejweb.modules.front.upload.bean.FileResponse;
import com.ejweb.modules.front.upload.bean.UploadBean;
import com.ejweb.modules.front.upload.bean.UploadFileBean;
import com.ejweb.modules.front.upload.service.FrontUploadService;
import com.ejweb.modules.front.upload.util.ReportAttachmentUtils;
import com.ejweb.modules.report.entity.ReportAttachmentEntity;
import io.swagger.annotations.ApiOperation;
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.*;
import java.net.URLDecoder;
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 = "/front/api/upload")
class FrontUploadController {

    @Autowired
    private FrontUploadService frontUploadService;

    private static final String savePath = GConstants.getValue("file.upload.dir");
    private String viewServer = GConstants.getValue("file.prefix.url");

    /**
     * 使用BASE64上传文件
     * 
     * @author renmb
     * @time 2016年11月1日
     * @param request
     * @param requestBean
     * @return
     */
    @ApiOperation(value = "BASE64文件上传", httpMethod = "POST", response = ResponseBean.class, notes = "使用BASE64上传文件", position = 1)
    @ResponseBody
    @RequestMapping(value="/base64", method ={RequestMethod.POST})
    public ResponseBean base64(HttpServletRequest request,  HttpServletResponse response, RequestBean requestBean ,String files) {

        ResponseBean responseBean = new ResponseBean();
        FileResponse file = new FileResponse();
        response.setCharacterEncoding("UTF-8");
        String path = "";
        try {
            request.setCharacterEncoding("UTF-8");
            String fileContent = request.getParameter("files");
            byte[] bytes = null;
            if(StringUtils.isNotBlank(fileContent)){
                String name = request.getParameter("name");
                String suffix = name.split("\\.")[1];
                path = "wap/" + System.currentTimeMillis() + "." + suffix;
                bytes = new BASE64Decoder().decodeBuffer(fileContent.split(",")[1]);
                for (int i = 0; i < bytes.length; ++i) {
                    if (bytes[i] < 0) {// 调整异常数据
                        bytes[i] += 256;
                    }
                }
                OutputStream out = new FileOutputStream(savePath + path);
                out.write(bytes);
                out.flush();
                out.close();
                //ReportAttachment表的记录
                ReportAttachmentEntity entity = new ReportAttachmentEntity();
                entity.setAttachmentName(name);
                entity.setAttachmentPath(viewServer + path);
                entity.setAttachmentSize(fileContent.getBytes().length);
                entity.setAttachmentType("0");
                String id = IdGen.uuid();
                entity.setId(id);
                ReportAttachmentUtils.add(entity);
                //返回数据
                file.setName(name);
                file.setSize(bytes.length);
                file.setUri(viewServer + path);
                file.setId(id);
                responseBean.setData(file);
            }else {
                responseBean.setStatus(ErrorCode.STATUS_CODE_4001);
                responseBean.setMessage("获取不到文件！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            responseBean.setStatus(ErrorCode.STATUS_CODE_4004);
            responseBean.setMessage("系统错误！");
        }
        return responseBean;
    }

    @ApiOperation(value = "15.1 文件上传接口1", httpMethod = "POST", response = ResponseBean.class, notes = "批量文件上传", position = 1)
    @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 = frontUploadService.addMultipartFile(files, 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;
    }

    @ApiOperation(value = "15.2 文件上传接口2", httpMethod = "POST", response = ResponseBean.class, notes = "批量文件上传", position = 1)
    @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 = frontUploadService.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;
    }

    @ApiOperation(value = "批量文件上传", httpMethod = "POST", response = ResponseBean.class, notes = "批量文件上传", position = 1)
    @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;
    }

    @ApiOperation(value = "批量文件上传", httpMethod = "GET", response = ResponseBean.class, notes = "批量文件上传", position = 1)
    @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;
    }

    @ApiOperation(value = "批量文件上传", httpMethod = "POST", response = ResponseBean.class, notes = "批量文件上传", position = 1)
    @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 = frontUploadService.addUploadFile(sessionId, request.getInputStream(), "", name, "", moduleName, appCode,
                    clientip,null);
            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;
    }

    @ApiOperation(value = "批量文件上传", httpMethod = "GET", response = ResponseBean.class, notes = "批量文件上传", position = 1)
    @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);
        }
    }
}
