package com.foreverwin.mesnac.common.controller;

import com.foreverwin.mesnac.common.ftp.CappFtpClient;
import com.foreverwin.mesnac.common.service.FileService;
import com.foreverwin.mesnac.meapi.util.StringUtils;
import com.foreverwin.modular.core.exception.BaseException;
import com.foreverwin.modular.core.util.R;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 *
 * @author roc_li
 * @since 2020-11-03
 */
@Controller
@Component
@RequestMapping("/files")
public class FileController {

    private final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileService fileService;

    @Autowired
    public CappFtpClient ftpClient;

    /**
     * 获取图号路径
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/getPdfPath")
    public R getPdfPath(String sfc)  {
        try {
            if(StringUtils.isBlank(sfc)){
                throw new BaseException("产品条码不能为空!");
            }
            return R.ok(fileService.getFilePaths(sfc));
        }catch (Exception e){
            return R.failed("获取图纸路径失败:"+e.getMessage());
        }
    }
    /**
     * 获取图号路径-根据输入的物料号
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/getPdfPathByItem")
    public R getPdfPathByItemBo(String itemBo)  {
        try {
            if(StringUtils.isBlank(itemBo)){
                throw new BaseException("物料编码不能为空!");
            }
            return R.ok(fileService.getFilePathsByItemBo(itemBo));
        }catch (Exception e){
            return R.failed("获取图纸路径失败:"+e.getMessage());
        }
    }

    /**
     * 获取文件流
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/{fileName}")
    public R getPdfNew(HttpServletRequest request, HttpServletResponse response, @PathVariable("fileName") String fileName)  {
        InputStream in = null;
        OutputStream out = null;
        String path = request.getParameter("Path");
        try {
            //服务器发布
            //String coderPath = new String(path.getBytes("ISO8859_1"));
            //String newPath = new String(coderPath.getBytes("GBK"), FTPClient.DEFAULT_CONTROL_ENCODING);
            in = ftpClient.getFtp(path);
            if(null == in){
                in = ftpClient.getFtp(new String(path.getBytes("GBK"), FTPClient.DEFAULT_CONTROL_ENCODING));
            }

            //本地测试
            /*String newPath = new String(path.getBytes("GBK"), FTPClient.DEFAULT_CONTROL_ENCODING);
            in = plmFtpClient.getFtp(newPath);
            if(null == in){
                in = plmFtpClient.getFtp(new String(path.getBytes("UTF-8"), FTPClient.DEFAULT_CONTROL_ENCODING));
            }*/

            if(null == in){
                throw new BaseException("获取FTP文件路径为:【"+path+"】的文件流失败!");
            }
            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){
            return R.failed("获取CAPP文件失败:文件路径为"+path+":"+e.getMessage());
        }finally {
            try {
                if(null != out){
                    out.close();
                }
                if(null != in){
                    in.close();
                }

            }catch (Exception e1){
                return R.failed("获取CAPP文件失败:关闭文件流处理异常"+e1.getMessage());
            }
        }
        return R.ok(null,"获取CAPP文件成功!");
    }
}