package cn.yw.nhyw.nhywjtxcrzgl.action;

import java.io.*;
import java.net.InetAddress;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Component;
import cn.base.bean.BaseAction;
import cn.base.conf.ModuleConfFactory;
import cn.base.conf.YwPatrol;
import cn.base.util.DateUtil;
import cn.base.util.FTPUrl;
import cn.base.util.FTPUtil;
import cn.base.util.Struts2Utils;
@Component("uploadPictureAction")
public class UploadPictureAction extends BaseAction{

	private Logger logger = Logger.getLogger(UploadPictureAction.class);
	private List<File> myFile; // 上传的文件
    private List<String> myFileFileName; // 文件名称
    private List<String> myFileContentType; // 文件类型

	private static final int BUFFER_SIZE = 16 * 1024;


//    private String savePath;

//    public void uploadPicture() throws Exception {
//
//        ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
//        try{
//        	//获取配置信息
//            YwPatrol ywPatrol = ModuleConfFactory.getInstance().getYwPatrol();
//            if(ywPatrol==null){
//            	Struts2Utils.renderJson(null);
//            }
//            //基础路径
//    		String basePath = ywPatrol.getBasePath();
//    		String ftpStartPath = "";
//    		if(StringUtils.isNotEmpty(basePath)) {
//    			ftpStartPath = basePath +"/"+ InetAddress.getLocalHost().getHostAddress();
//    		}else {
//    			ftpStartPath = InetAddress.getLocalHost().getHostAddress();
//    		}
//    		//ftp对象
//    		FTPUrl ftpUrl = null;
//    		//返回上传路径
//    		String resultBaseFtpPath = "";
//    		if(StringUtils.isNotEmpty(ywPatrol.getFtp())){
//    			String[] ftp = ywPatrol.getFtp().split(":");
//    			resultBaseFtpPath = "ftp://"+ftp[2]+":"+ftp[3]+"@"+ftp[0]+":"+ftp[1]+"/";
//    			ftpUrl = FTPUtil.getFtpUrlObj(ftp[0],ftp[1],ftp[2],ftp[3]);
//    		}
//            // 取得需要上传的文件数组
//            List<File> files = getMyFile();
//            String nowDate = DateUtil.currentDate();
//            String path = ftpStartPath + "/" + nowDate.substring(0, 4) + "/"
//            				+ nowDate.substring(5,7) + "/"
//            				+ nowDate.substring(8,10);
//            String result = "";
//            if (files != null && files.size() > 0) {
//                for (int i = 0; i < files.size(); i++) {
//                    FileInputStream fis = new FileInputStream(files.get(i));
//                    result += resultBaseFtpPath + path + "/" + (System.currentTimeMillis()+new Random().nextInt(999)+"-"+myFileFileName.get(i))+"," ;
//                    FTPUtil.uploadFile(ftpUrl,path , (System.currentTimeMillis()+new Random().nextInt(999)+"-"+myFileFileName.get(i)),fis);
//                }
//            }
//            Struts2Utils.renderJson(result==""?"":result.subSequence(0,result.length()-1 ));
//        }catch(Exception e){
//        	e.printStackTrace();
//        	logger.error(Thread.currentThread().getClass().getSimpleName()+" UploadPictureAction-error:" + e);
//        	Struts2Utils.renderJson(null);
//        }
//
//    }

	private  void copy(File src, File dst) {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			logger.error(Thread.currentThread().getClass().getSimpleName()+" UploadPictureAction-error:" + e);

		} finally {
			if (null != in) {
				try {
					in.close();

				} catch (IOException e) {
					logger.error(Thread.currentThread().getClass().getSimpleName()+" UploadPictureAction-error:" + e);
				}
			}

			if (null != out) {
				try {
					out.close();

				} catch (IOException e) {
					logger.error(Thread.currentThread().getClass().getSimpleName()+" UploadPictureAction-error:" + e);

				}

			}

		}

	}


	public void uploadPicture() throws Exception {

		ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
		try{
			List<File> files = getMyFile();

			if (null == files || files.size()==0) {
				logger.error("NhywjjzcxxAction-imp_Nhywjjzcxx-error:文件不存在");
			}
			String directory = "/upload";
			String targetDirectory = ServletActionContext.getServletContext().getRealPath(directory);
			String result = "";
			String path = targetDirectory + "/" +directory+ "/" + DateUtil.currentDate().substring(0, 4) + "/"
					+ DateUtil.currentDate().substring(5,7) + "/"
					+ DateUtil.currentDate().substring(8,10);
			if (files != null && files.size() > 0) {
				for (int i = 0; i < files.size(); i++) {
					FileInputStream fis = new FileInputStream(files.get(i));
					//记录存放地址，放入数据库
					result += path + "/" + (System.currentTimeMillis()+new Random().nextInt(999)+"-"+myFileFileName.get(i))+"," ;
					//生成上传的文件对象
					File target = new File(path,(System.currentTimeMillis()+new Random().nextInt(999)+"-"+myFileFileName.get(i)));
					//如果文件已经存在，则删除原有文件
					if (target.exists()) {
						target.delete();
					}
					copy(files.get(i), target);           //复制file对象，实现上传
				}
			}
			//返回存放地址，存入验收表中的验收数据字段
			Struts2Utils.renderJson(result==""?"":result.subSequence(0,result.length()-1 ));

		}catch(Exception e){
			e.printStackTrace();
			logger.error(Thread.currentThread().getClass().getSimpleName()+" UploadPictureAction-error:" + e);
			Struts2Utils.renderJson(null);
		}


	}
	public static void main(String[] args) {
		String nowDate = DateUtil.currentDate();
		System.out.println(nowDate);
		System.out.println(nowDate.substring(0, 4));
		System.out.println(nowDate.substring(5,7));
		System.out.println(nowDate.substring(8,10));
		System.out.println(new Random().nextInt(999));
	}
    

	
    public List<File> getMyFile() {
		return myFile;
	}
	public void setMyFile(List<File> myFile) {
		this.myFile = myFile;
	}
	public List<String> getMyFileFileName() {
		return myFileFileName;
	}
	public void setMyFileFileName(List<String> myFileFileName) {
		this.myFileFileName = myFileFileName;
	}
	public List<String> getMyFileContentType() {
		return myFileContentType;
	}
	public void setMyFileContentType(List<String> myFileContentType) {
		this.myFileContentType = myFileContentType;
	}
	/**
     * 返回上传文件保存的位置
     * 
     * @return
     * @throws Exception
     */
  /*  public String getSavePath() throws Exception {
        return ServletActionContext.getServletContext().getRealPath(savePath);
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }*/

}
