package com.fjs.scenic.controller;

import java.io.*;
import java.net.SocketException;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.fjs.scenic.upload.FileUtil;
import com.fjs.scenic.utils.Cons;
import com.fjs.scenic.utils.Data;
import com.fjs.scenic.utils.FtpFileUtil;
import com.fjs.scenic.utils.ImgeNameUtils;
import com.fjs.scenic.utils.ReturnResult;

/**
 * @author 作者 :yangya
 * @version 创建时间：2018年3月29日 下午2:10:36 类说明:
 */
@RestController
@RequestMapping("/upload")
public class UploadPicController {

    @Value("${FTP_ADDRESS}")
    private String ftpAddress;
    @Value("${FTP_PORT}")
    private int ftpPort;
    @Value("${FTP_USERNAME}")
    private String ftpUserName;
    @Value("${FTP_PASSWORD}")
    private String ftpPassword;
    @Value("${FTP_BASEPATH}")
    private String ftpBasePath;
    @Value("${FTP_VOID_BASEPATH}")
    private String ftpVoidBasePath;
    @Value("${NGINX_PORT}")
    private String nginxPort;
    
    @Autowired
    private FileUtil fileUtil;

    @PostConstruct
    public void init() {
        FtpFileUtil.FTP_ADDRESS = this.ftpAddress;
        FtpFileUtil.FTP_PORT = this.ftpPort;
        FtpFileUtil.FTP_USERNAME = this.ftpUserName;
        FtpFileUtil.FTP_PASSWORD = this.ftpPassword;
        FtpFileUtil.FTP_BASEPATH = this.ftpBasePath;
        FtpFileUtil.FTP_VOID_BASEPATH = this.ftpVoidBasePath;
        FtpFileUtil.NGINX_PORT = this.nginxPort;
    }

    /**
     * 上传图片
     */
    @PostMapping("/pic")
    public ReturnResult uploadImg(@RequestParam("upload") MultipartFile file) throws IOException {
    	try {
			String uploadFile = fileUtil.uploadFile(file);
			return ReturnResult.ok(new Data(uploadFile, ""));
		} catch (Exception e) {
			e.printStackTrace();
			return ReturnResult.error("上传失败");
		}
    	// return upload(file);
    }

    /**
     * 上传视频
     */
    @PostMapping("/void")
    public ReturnResult uploadVoid(@RequestParam("upload") MultipartFile file, HttpSession session,String sessionID) throws IOException {
//        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = servletRequestAttributes.getRequest();
        return ReturnResult.ok(FtpFileUtil.uploadFile(file, session,sessionID));
    }

    /**
     * 获取进度
     */
    @PostMapping("/getProcess")
    public ReturnResult getProcess(HttpSession session,String sessionID) throws IOException {
        String process = (String) session.getAttribute(sessionID);
        System.out.println(process);
        if(process==null){
            return ReturnResult.ok(0);
        }else if (process.equals("100")) {
            session.removeAttribute(sessionID);
            return ReturnResult.ok(100);
        } else {
            return ReturnResult.ok(process);
        }
    }

    /**
     * 上传
     *
     * @param file   上传文件
     * @param isVoid 是否是上传视频
     * @return
     * @throws IOException
     */
    public ReturnResult upload(MultipartFile file, boolean isVoid) throws IOException {
        String fileName = file.getOriginalFilename();
        String newName = ImgeNameUtils.genImageName();
        // 新名字
        newName = newName + fileName.substring(fileName.lastIndexOf("."));
        InputStream inputStream = file.getInputStream();
        String picUrl = isVoid ? FtpFileUtil.uploadVoidFile(newName, inputStream) : FtpFileUtil.uploadFile(newName, inputStream);
        if (!StringUtils.isEmpty(picUrl)) {
            return ReturnResult.ok(new Data(picUrl, ""));
        } else {
            return ReturnResult.build(Cons.RESULT_ERR, "上传失败");
        }
    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     * @throws IOException
     */
    public ReturnResult upload(MultipartFile file) throws IOException {
        return upload(file, false);
    }

    /**
     * 上传图片
     */
    @PostMapping("/data")
    public ReturnResult uploadData(@RequestParam("fileData") MultipartFile file, String fileName) throws IOException {
        Assert.notNull(fileName, "manager-文件后缀名不能为空.");

        // 新名字
        String newName = ImgeNameUtils.genImageName();
        newName = newName + fileName.substring(fileName.lastIndexOf("."));
        InputStream inputStream = file.getInputStream();
        String picUrl = FtpFileUtil.uploadFile(newName, inputStream);
        if (!StringUtils.isEmpty(picUrl)) {
            return ReturnResult.ok(new Data(picUrl, ""));
        } else {
            return ReturnResult.build(Cons.RESULT_ERR, "上传失败");
        }
    }

    /**
     * 删除图片
     */
    @DeleteMapping("/delete/{fileName}/{fix}")
    public @ResponseBody
    ReturnResult refundList(@PathVariable String fileName, @PathVariable String fix) {
        Assert.notNull(fileName, "文件名不能为空.");
        Assert.notNull(fix, "文件格式后缀不能为空.");
        fileName = fileName + "." + fix;
        return new ReturnResult(Cons.RESULT_OK, "请求成功", FtpFileUtil.deleteFile(fileName));
    }

    /**
     * 下载视频到本地
     *
     * @param fileName 文件名称
     * @return 文件相对地址
     */
    @PostMapping("/downVoid")
    public ReturnResult downVoid(String fileName) {
        if (fileName == null) {
            return ReturnResult.build(500, "文件名不能爲空");
        }
        fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
        char seq = File.separatorChar;
        //判断文件是否已存在
        String picPath = "fjs-scenic-manager" + seq + "src" + seq + "main" + seq + "resources" + seq + "static" + seq + "void" + seq;
        File pic = new File(picPath + fileName);
        File pic1 = new File("fjs-scenic-manager");
        if (!pic.exists()) {
            try {
                FileUtils.cleanDirectory(new File(picPath));
                pic.createNewFile();
                FtpFileUtil.downloadFtpVoidFile(picPath, fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ReturnResult.ok("../../void/" + fileName);
    }
}
