package cn.pluss.platform.controller.upload;

import cn.pluss.platform.annotation.PassToken;
import cn.pluss.platform.config.OssConfig;
import cn.pluss.platform.controller.BaseNoModelController;
import cn.pluss.platform.systemConfig.SystemConfigService;
import cn.pluss.platform.util.OssOperatUtil;
import cn.pluss.platform.util.ParametersUtil;
import cn.pluss.platform.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;


@Controller
@RequestMapping("upload")
public class UploadController extends BaseNoModelController {
    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OssConfig config;

    @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> uploadImage(HttpServletRequest request, @RequestParam(value = "imageFile") MultipartFile imageFile) throws IOException {

        String fileNameAtr = request.getParameter("filename_atr");
        FileOutputStream fos = null;
        FileInputStream fis = null;
        // 保存文件名称
        String fileName = "file_" + StringUtil.getBillno() + "." + fileNameAtr;
        String uploadPath = ParametersUtil.upload_save_path;
        String visitPath = ParametersUtil.upload_visit_path;
        Properties prop = System.getProperties();
        String os = prop.getProperty("os.name");
        if (os.startsWith("win") || os.startsWith("Win")) {
            //D:\work\workspace_java\syb\pluss-manage-page
            uploadPath = "D:\\work\\workspace_java\\syb\\resources\\manage\\upload";// 测试 // windows目录
        }
        String path = uploadPath + "/" + fileName;
        String suc;
        try {
            InputStream ins = imageFile.getInputStream();
            File f = new File(imageFile.getOriginalFilename());
            inputStreamToFile(ins, f);
            fis = new FileInputStream(f);
            fos = new FileOutputStream(new File(path));
            byte[] strByte = new byte[(int) f.length()];
            // 生成文件
            while (fis.read(strByte) != -1) {
                fos.write(strByte);
            }
            fos.flush();
            suc = "1";
            //Runtime.getRuntime().exec("chmod -R 777 /home/syb/resources/");
            path = visitPath + "/" + fileName;// 测试
            // 访问路劲
            if (os.startsWith("win") || os.startsWith("Win")) {
                path = "http://127.0.0.1/resources/manage/upload" + "/" + fileName;// 测试 // windows目录
            } else {
                Runtime.getRuntime().exec("chmod -R 777 /home/syb/resources/");
            }
        } catch (Exception e) {
            suc = "0";
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
            if (fis != null) {
                fis.close();
            }
        }
        // 返回保存结果
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("result", suc);
        result.put("url", path);
        result.put("fileName", fileName);
        return result;
    }

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> uploadFile(HttpServletRequest request, @RequestParam(value = "file") MultipartFile file) throws IOException {
        FileOutputStream fos = null;
        FileInputStream fis = null;
        // 保存文件名称
        String name = file.getOriginalFilename();
        String suffixName = name.substring(name.lastIndexOf("."));//获取后缀名
        String fileName = "file_" + StringUtil.getBillno() + suffixName;
        String uploadPath = ParametersUtil.upload_save_path;
        String visitPath = ParametersUtil.upload_visit_path;
        Properties prop = System.getProperties();
        String os = prop.getProperty("os.name");
        if (os.startsWith("win") || os.startsWith("Win")) {// windows目录
            uploadPath = "D:/";// 测试
        }
        String path = uploadPath + "/" + fileName;
        String suc;
        try {
            InputStream ins = file.getInputStream();
            File f = new File(file.getOriginalFilename());
            inputStreamToFile(ins, f);
            fis = new FileInputStream(f);
            fos = new FileOutputStream(new File(path));
            byte[] strByte = new byte[(int) f.length()];
            while (fis.read(strByte) != -1) {// 生成文件
                fos.write(strByte);
            }
            fos.flush();
            suc = "1";
            Runtime.getRuntime().exec("chmod -R 777 /home/syb/resources/");
            path = visitPath + "/" + fileName;// 测试
            if (os.startsWith("win") || os.startsWith("Win")) {// 访问路劲
                path = "http://127.0.0.1/resources/manage/upload" + "/" + fileName;// windows目录
            }
        } catch (Exception e) {
            suc = "0";
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
            if (fis != null) {
                fis.close();
            }
        }
        // 返回保存结果
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("result", suc);
        result.put("url", path);
        result.put("fileName", fileName);
        return result;

    }

    @PostMapping("/ossUploadFile")
    @ResponseBody
    public Map<String, Object> ossUploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
        Map<String, Object> result = new HashMap<>();
        if (file.isEmpty()) {
            result.put("code", 500);
            result.put("msg", "上传文件不能为空！");
            return result;
        }
        String fileName = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String url = OssOperatUtil.upload(file.getInputStream(), fileName, suffix);
        if (StringUtils.isEmpty(url)) {
            result.put("code", 501);
            result.put("msg", "上传失败！");
            return result;
        }
        System.out.println("======================================>" + url);
        result.put("code", 200);
        result.put("msg", "上传成功！");
        result.put("url", url);
        return result;
    }



    /*
     * //上传视频 public Map<String, Object> uploadVideo() throws IOException{ String
     * fileNameAtr=this.request.getParameter("filename_atr"); // FileOutputStream
     * fos = null; FileInputStream fis= null; //保存文件名称 String
     * fileName="video_"+StringUtil.getBillno()+".mp4"; String
     * uploadPath=systemConfigService.querySystemConfigValue("upload_visit_path");
     *
     * Properties prop = System.getProperties(); String os1 =
     * prop.getProperty("os.name"); if(os1.startsWith("win") ||
     * os1.startsWith("Win")){ //windows目录
     *
     * //uploadPath="D:/eclipse-workspace/huazhi/resources/manage/upload";
     * uploadPath="D:/eclipse-worksHZ/hz/java/resources/manage/upload"; } String
     * path=uploadPath+"/"+fileName;
     *
     *
     *
     *
     * String suc; try { fis=new FileInputStream(getImageFile()); //
     * path=aliyunOssUpload(fileName, fis); // suc="1"; //访问路劲 // fos = new
     * FileOutputStream(new File(path)); // byte[] strByte =new byte[(int)
     * getImageFile().length()]; // //生成文件 // while(fis.read(strByte)!=-1){ //
     * String str1=new String(strByte); // fos.write(strByte); // } // fos.flush();
     * // suc="1"; //访问路劲 OutputStream os = new FileOutputStream(new File(path));
     * int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead =
     * fis.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); }
     * os.close(); fis.close();
     *
     * suc="1";
     *
     * path=SystemConfigUtil.getSingleProperty("upload_visit_path").getPropertyValue
     * ()+"/"+fileName;
     *
     * if(os1.startsWith("win") || os1.startsWith("Win")){ //windows目录
     *
     * path="http://127.0.0.1/resources/manage/upload"+"/"+fileName; }
     *
     *
     *
     * } catch (Exception e) { suc="0"; e.printStackTrace(); } finally { // if (fos
     * != null) { // try { fos.close(); } catch (IOException e) {} // }
     * if(fis!=null){ fis.close(); } } Map<String, Object> result=new
     * HashMap<String, Object>(); System.out.println(path); //返回保存结果 JSONObject
     * json=new JSONObject(); result.put("result", suc); result.put("url", path);
     * return result; }
     */

    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PassToken
    @PostMapping("ossCallback")
    @ResponseBody
    public Map<String, String> callback(HttpServletRequest request) {
        Map<String, String> result = new HashMap<String, String>(4);
        String fileKey = request.getParameter("filename");
        //String size = request.getParameter("size");
        //String mimeType = request.getParameter("mimeType");
//        AppVersionInfo info = new AppVersionInfo();
//        info.setFileKey(fileKey);
        String url = OssOperatUtil.getUrl(fileKey);
        result.put("code", "200");
        result.put("Status", "OK");
        result.put("msg", "上传成功");
        result.put("url", url);
        return result;
    }
}
