package com.dev.swms.server.model.interfaceLog.pojo;




import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.RandomStringUtils;

import com.dev.energy.server.exception.BusinessException;
import com.dev.energy.server.model.Entity;
import com.dev.energy.server.model.EntityFactory;
import com.dev.energy.server.service.pojo.DefaultBaseManager;
import com.dev.energy.server.util.EncoderUtil;
import com.dev.energy.server.util.LocalizedMessage;
import com.dev.energy.server.web.security.UserHolder;
import com.dev.swms.server.service.GlobalParamUtils;
import com.dev.swms.server.utils.ZipUtils;
import com.dev.swms.server.model.base.Item;
import com.dev.swms.server.model.base.SignFile;
import com.dev.swms.server.model.interfaceLog.ImageFileManager;
import com.dev.swms.server.model.inventory.Inventory;
import com.dev.swms.server.model.receiving.ASN;
import com.dev.swms.server.model.shipping.Label;
import com.dev.swms.server.model.shipping.PickTicket;


public class DefaultImageFileManager extends DefaultBaseManager implements ImageFileManager {

	@Override
	public <T extends Entity> void importImageZip(Long id, File file,
			String imageType, String objectType) {
		// TODO Auto-generated method stub
		if (file != null) {
			String filename = file.getName();
			int index = filename.lastIndexOf("-");
			if (index > -1) {
				filename = filename.substring(0, index);
			}
			if (filename.endsWith(".ZIP") || filename.endsWith(".zip")) { // ZIP压缩文件
				List<String> list = ZipUtils.unZip(file.getPath());
				if (!list.isEmpty()) {
					for (int i = 0; i < list.size(); i++) {
						String fname = (String) list.get(i);
						File f = new File(fname);
						File newFile = new File(fname + "-"
								+ RandomStringUtils.randomAlphanumeric(6));
						f.renameTo(newFile);
						if (checkImageFormat(filename)){
							importImageFile(id, newFile, imageType, objectType);
						}else{
							throw new BusinessException("only.zip.or.pic");
						}
						newFile.delete();
					}
				} else {
					throw new BusinessException("zip.empty");
				}
			} else if (checkImageFormat(filename)){
				importImageFile(id, file, imageType, objectType);
			} else {
				throw new BusinessException("only.zip.or.pic");
			}
		} else {
			throw new BusinessException("file.empty.or.too.big");
		}
		LocalizedMessage.addLocalizedMessage("上传成功");
	}

	Boolean checkImageFormat(String filename){
		return Boolean.TRUE;
//		if (filename.endsWith(".jpg") || filename.endsWith(".gif")
//				|| filename.endsWith(".bmp") || filename.endsWith(".png")
//				|| filename.endsWith(".JPG") || filename.endsWith(".GIF")
//				|| filename.endsWith(".BMP") || filename.endsWith(".PNG")
//				||filename.endsWith(".pdf")||filename.endsWith(".PDF")) {
//			return Boolean.TRUE;
//		}else{
//			return Boolean.FALSE;
//		}
	}
	
	public <T extends Entity> void importImageFile(Long id, File file,
			String imageType, String objectType ){
		SignFile imageFile = (SignFile) EntityFactory.getEntity(SignFile.class);
		String fileName = "";
		String code = "";
		Date date = new Date();
		if (objectType.equals("ORDER")) {
			Label label = this.commonDao.load(Label.class, id);
			imageFile.setLabel(label);
			String imageNameType = getImageNameType(file);
			code = "TH";
			fileName =  EncoderUtil.GB2312ToUniCode(code+"_"+getImageNameSuffix()+imageNameType);//getImageName(file);
			date = label.getCreateDate();
			commonDao.store(label);
		}
		if (objectType.equals("ITEM")) {
			Item item = this.commonDao.load(Item.class, id);
			imageFile.setItem(item);
			String imageNameType = getImageNameType(file);
			code = item.getCode();
			fileName =  EncoderUtil.GB2312ToUniCode(code+"_"+getImageNameSuffix()+imageNameType);
			date = new Date();
			
			commonDao.store(item);
		}
		if (objectType.equals("ASN")) {
			ASN asn = this.commonDao.load(ASN.class, id);
			imageFile.setAsn(asn);
			String imageNameType = getImageNameType(file);
			code = asn.getCode();
			fileName =  EncoderUtil.GB2312ToUniCode(code+"_"+getImageNameSuffix()+imageNameType);
			date = new Date();
			commonDao.store(asn);
		}
		if (objectType.equals("PickTicket")) {
			PickTicket pickTicket = this.commonDao.load(PickTicket.class, id);
			imageFile.setPickTicket(pickTicket);
			String imageNameType = getImageNameType(file);
			code = pickTicket.getCode();
			fileName =  EncoderUtil.GB2312ToUniCode(code+"_"+getImageNameSuffix()+imageNameType);
			date = new Date();
			commonDao.store(pickTicket);
		}
		if (objectType.equals("Inventory")) {
			Inventory inventory = this.commonDao.load(Inventory.class, id);
			imageFile.setInventory(inventory);
			String imageNameType = getImageNameType(file);
			code = inventory.getItemKeyInventory().getItemKey().getItem().getCode();
			fileName =  EncoderUtil.GB2312ToUniCode(code+"_"+getImageNameSuffix()+imageNameType);
			date = new Date();
			commonDao.store(inventory);
		}
		StringBuffer stringBuffer = new StringBuffer();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = format.format(date.getTime());
		if (file != null) {
			createFile(file, fileName, code);// 生成图片资料
			createShareFile(file, dateString, code, fileName);// 生成共享照片
			getHtmlCode(stringBuffer, file, fileName, code);
			imageFile.setFileName(fileName);
			imageFile.processFileUrl(stringBuffer.toString());// 生成带img标签的目标图片的url地址
			imageFile.setImageType(imageType);
			imageFile.setObjectType(objectType);
			imageFile.setOperate(UserHolder.getUser().getName());
			imageFile.setOperateDate(new Date());
			imageFile.setFileDate(new Date());
			imageFile.setObjectId(id);
			commonDao.store(imageFile);
			// asn.addFiles(imageFile);// 创建和附件的关联
		} else {
			throw new BusinessException(
					"file.not.exist.or.file.length.bigger.than.2M");
		}
	}

	/**
	 * 获取文件的文件扩展名如：.jpg
	 * 
	 * @param file
	 * @return
	 */
	private String getImageNameType(File file) {
		int a = file.getName().lastIndexOf(".");
		int b = file.getName().lastIndexOf("-");
		String name = file.getName().substring(a, b);
		return name;
	}

	/**
	 * 获取图片名称的后缀:一个６位的随机数
	 * 
	 * @author dev
	 * @param order
	 * @return
	 */
	private String getImageNameSuffix() {
		String a = RandomStringUtils.randomAlphanumeric(6);
		return a;
	}

	/**
	 * 将临时文件转换成图片
	 * 
	 * @author dev
	 * @param file
	 * @param 进仓编号或者预配编号
	 */
	private void createFile(File file, String fileName, String code) {
		Calendar date = Calendar.getInstance();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

		String dateString = format.format(date.getTime());

		// 判断待存放图片的目录文件夹是否存在,如果不存在新建一个
		File file1 = new File(
				GlobalParamUtils.getGloableStringValue("tempFileDir"));// 源文件存放的临时文件夹
		if (!file1.exists()) {
			throw new BusinessException("tempFile.not.exists");
		}
		File file2 = new File(
		// GlobalParamUtils.getGloableStringValue("imageTarget")+dateString+"\\"+code+"\\");
				GlobalParamUtils.getGloableStringValue("imageTarget"));// 存放生成的图片的目标文件夹
		if (!file2.exists()) {
			file2.mkdirs();
		}
		try {
			// File outputFile = new File(
			// GlobalParamUtils.getGloableStringValue("imageTarget")+dateString+"\\"+code+"\\"
			// + fileName);

			File outputFile = new File(
					GlobalParamUtils.getGloableStringValue("imageTarget")
							+ fileName);
			FileInputStream in = new FileInputStream(file);// 定义文件输入流
			BufferedInputStream bin = new BufferedInputStream(in);// 将文件输入流构造到缓存中
			FileOutputStream out = new FileOutputStream(outputFile);// 定义文件输出流
			BufferedOutputStream bout = new BufferedOutputStream(out);// 将文件输出流构造到缓存中
			int i;
			while ((i = bin.read()) != -1) {
				bout.write(i);
			}
			bin.close();
			bout.close();// 关闭输入输出流，释放资源
		} catch (IOException e) {
			throw new BusinessException("IO.error");
		}
	}
	
	/**
	 * 将临时文件共享到指定目录
	 * 
	 * @author dev
	 * @param file
	 * @param 箱号或进仓编号
	 *            ，进仓时间或箱子进场时间
	 */
	private void createShareFile(File file, String date, String code,
			String fileName) {

		// 判断待存放图片的目录文件夹是否存在,如果不存在新建一个
		/*
		 * File file1 = new File(
		 * GlobalParamUtils.getGloableStringValue("tempFileDir"));// 源文件存放的临时文件夹
		 * if (!file1.exists()) { throw new
		 * BusinessException("tempFile.not.exists"); }
		 */
		File file2 = new File("d:\\picture\\" + date + "\\" + code + "\\");
		// GlobalParamUtils.getGloableStringValue("imageTarget"));//
		// 存放生成的图片的目标文件夹
		if (!file2.exists()) {
			file2.mkdirs();
		}
		try {
			File outputFile = new File("d:\\picture\\" + date + "\\" + code
					+ "\\" + fileName);

			/*
			 * File outputFile = new File(
			 * GlobalParamUtils.getGloableStringValue("imageTarget") +
			 * fileName);
			 */
			FileInputStream in = new FileInputStream(file);// 定义文件输入流
			BufferedInputStream bin = new BufferedInputStream(in);// 将文件输入流构造到缓存中
			FileOutputStream out = new FileOutputStream(outputFile);// 定义文件输出流
			BufferedOutputStream bout = new BufferedOutputStream(out);// 将文件输出流构造到缓存中
			int i;
			while ((i = bin.read()) != -1) {
				bout.write(i);
			}
			bin.close();
			bout.close();// 关闭输入输出流，释放资源
		} catch (IOException e) {
			throw new BusinessException("IO.error");
		}
	}
	
	/**
	 * 获取图片存放目录的路径
	 * 
	 * @author dev
	 * @param buffer
	 * @param file
	 * @param asn
	 */
	private void getHtmlCode(StringBuffer buffer, File file, String fileName,
			String code) {
		Calendar date = Calendar.getInstance();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = format.format(date.getTime());
		String fileSite = GlobalParamUtils.getGloableStringValue("imageTarget");
		// String fileSite =
		// GlobalParamUtils.getGloableStringValue("imageTarget")+dateString+"\\"+code+"\\";
		// 目标文件夹存放的路径
		buffer.append(fileSite + fileName);
	}

	@Override
	public <T extends Entity> void importImageItem(Long id, File file1,File file2,File file3,File file4,File file5,File file6,
			File file7,File file8,File file9,File file10,String imageType,String objectType) {
		if(file1!=null){
			importImageFile(id, file1, imageType, objectType);
		}
		if(file2!=null){
			importImageFile(id, file2, imageType, objectType);
		}
		if(file3!=null){
			importImageFile(id, file3, imageType, objectType);
		}
		if(file4!=null){
			importImageFile(id, file4, imageType, objectType);
		}
		if(file5!=null){
			importImageFile(id, file5, imageType, objectType);
		}
		if(file6!=null){
			importImageFile(id, file6, imageType, objectType);
		}
		if(file7!=null){
			importImageFile(id, file7, imageType, objectType);
		}
		if(file8!=null){
			importImageFile(id, file8, imageType, objectType);
		}
		if(file9!=null){
			importImageFile(id, file9, imageType, objectType);
		}
		if(file10!=null){
			importImageFile(id, file10, imageType, objectType);
		}
	}
	
}
