package com.foreverwin.mesnac.anomaly.service.impl;

import cn.hutool.extra.ftp.Ftp;
import com.foreverwin.mesnac.anomaly.service.FileUploadedService;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.modular.core.exception.BusinessException;
import com.foreverwin.modular.core.util.CommonMethods;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @Description TODO
 * @Author zhaojiawei
 * @Since 2021-07-10
 */
@Service("FileUploaded")
@Transactional(rollbackFor = Exception.class)
@ConditionalOnProperty( prefix = "ftp",name = {"host","port","username","password"})
public class FileUploadedServiceImpl implements FileUploadedService {

    @Value("${ftp.host}")
    private String host;
    @Value("${ftp.port}")
    private Integer port;
    @Value("${ftp.username}")
    private String username;
    @Value("${ftp.password}")
    private String password;

    private final static Logger logger = LoggerFactory.getLogger("FileUploadedServiceImpl");

    /**
     * 附件上传
     *
     * @param fileItem
     * @return
     */
    @Override
    public void uploadAttachment(MultipartFile fileItem,String site,String taskNo,String fileType,String status)  {
        if (StringUtil.isBlank(site)) {
            site = CommonMethods.getSite();
        }
        String ftpPath = taskNo + "/" + status;
        //上传附件名称
        String fileName = fileItem.getOriginalFilename();
        try {
            Ftp ftp = new Ftp(host, port,username,password);
            ftp.upload(ftpPath, fileName, fileItem.getInputStream());
            ftp.close();
        } catch (IOException e) {
            logger.info(e.getMessage());
            throw BusinessException.build("上传图片失败：" + e.getMessage());
        }

//        try{
//            FTPClient ftpClient = new FTPClient();
//            ftpClient.connect(host,port);
//            ftpClient.login(username,password);
//            InputStream inputStream = fileItem.getInputStream();
//            FileInputStream  fileInputStream= (FileInputStream) inputStream;
//            ftpClient.changeWorkingDirectory(ftpPath);
//            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//            ftpClient.storeFile("ces",fileInputStream);
//            ftpClient.logout();
//        }catch (Exception e){
//            throw BusinessException.build("上传图片失败：" + e.getMessage());
//        }

    }

    @Override
    public String showFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String path = request.getParameter("PATH");
//        InputStream in = null;
        OutputStream out = null;
        try {
            String coderPath = new String(path.getBytes("ISO8859_1"));
            String newPath = new String(coderPath.getBytes("GBK"), FTPClient.DEFAULT_CONTROL_ENCODING);
            //

            FTPClient ftpClient = new FTPClient();
            ftpClient.connect(host,port);
            ftpClient.login(username,password);
            if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
                ftpClient.disconnect();
            }
            ftpClient.enterLocalActiveMode();
            // 设置文件类型为二进制，与ASCII有区别
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            // 设置编码格式
            ftpClient.setControlEncoding("GBK");
            // 提取绝对地址的目录以及文件名
            path = path.replace("ftp://"+path+":"+port+"/", "");
            String dir = path.substring(0, path.lastIndexOf("/"));
            String file = path.substring(path.lastIndexOf("/")+1);
            // 进入文件所在目录，注意编码格式，以能够正确识别中文目录
            boolean cdStatus = ftpClient.changeWorkingDirectory(new String(dir.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING));
            // 检验文件是否存在
            InputStream in = ftpClient.retrieveFileStream(new String(file.getBytes("GBK"),FTP.DEFAULT_CONTROL_ENCODING));
            if(in == null || ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE){
                throw BusinessException.build("预览图片失败，该文件不存在");
            }

            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while( (len=in.read(buffer)) != -1 ){
                outStream.write(buffer, 0, len);
            }
            byte[] data = outStream.toByteArray();
            out = response.getOutputStream();
            out.write(data);
            out.flush();
        }catch (Exception e){
            throw BusinessException.build("预览图片失败"+e.getMessage());
        }finally {
            out.close();
//            in.close();
        }

        return null;
    }

    @Override
    public boolean deleteFile(String pathname, String filename){
        boolean flag = false;
        FTPClient ftpClient = null;
        try {
            //System.out.println("开始删除文件");
             ftpClient = new FTPClient();
            ftpClient.connect(host,port);
            ftpClient.login(username,password);
            if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
                ftpClient.disconnect();
            }
            ftpClient.enterLocalActiveMode();
            // 设置文件类型为二进制，与ASCII有区别
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            // 设置编码格式
            ftpClient.setControlEncoding("GBK");
            //切换FTP目录
            if(StringUtil.isBlank(filename)){
                ftpClient.changeWorkingDirectory(pathname);
                FTPFile[] ftpFiles = ftpClient.listFiles();
                for (FTPFile ftpFile : ftpFiles) {
                    ftpClient.dele(ftpFile.getName());
                }
            }else{
                ftpClient.changeWorkingDirectory(pathname);
                ftpClient.dele(filename);
            }
            ftpClient.logout();
            flag = true;
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    public void uploadImage(FileItem fileItem, HttpServletRequest request){
        String site = request.getParameter("site");
        String taskNo = request.getParameter("taskNo");
        String fileType = request.getParameter("fileType");
        String status = request.getParameter("status");
        String ftpPath = taskNo + "/" + status;

        if (StringUtil.isBlank(site)) {
            site = CommonMethods.getSite();
        }
        //上传附件名称
        String fileName = fileItem.getName();
        try {
            Ftp ftp = new Ftp(host, port,username,password);
            ftp.upload(ftpPath, fileName, fileItem.getInputStream());
            ftp.close();
        } catch (IOException e) {
            logger.info(e.getMessage());
            throw BusinessException.build("上传图片失败" + e.getMessage());
        }
    }
}
