package com.teamcenter.rac.workflow.commands.dotask;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import com.connor.nhjs.gy.findpz.WordBean;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.kernel.TCAccessControlService;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentDatasetType;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCSession;

public class Util {

	
	/**
	 * 文件名格式化，不允许的字符替换为空格
	 * @param s
	 * @return
	 */
	public static String formatString( String s)
	{

		if(s.contains(":")
				||s.contains("*")
				||s.contains("?")
				||s.contains("\"")
				||s.contains("|")
				||s.contains("<")
				||s.contains(">")
				||s.contains(" ")
				||s.contains("\\")
				||s.contains("\\\\")
				||s.contains("/"))
		{ 
			s = s.replace(" " , "");
			s = s.replace("\\\\" , "");
			s = s.replace("\\" , "");
			s = s.replace("/" , "");
			s = s.replace("<" , "");
			s = s.replace(">" , "");

			s = s.replace("?" , "");
			s = s.replace("\"" , "");

			s = s.replace(":" , "");
			s = s.replace("*" , "");
			s = s.replace("|" , "");
			s = s.replace(">" , "");
			
		}
		
		return s;
	}
	
//	/**
//	 * list转Map,获取指定长度的内容和图片
//	 * @param list
//	 * @param width
//	 * @return
//	 */
	//76
	public static List<String> list2map(String str, int width) {
		List<String> list2 = new ArrayList<String>();
		Font font = new Font("宋体", Font.PLAIN, 11);   
		FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
//		System.out.println("FontMetrics:"+fm.stringWidth("一二")+"=="+fm.stringWidth("QW"));

		String tmp_str = "";
//		int tmp_width = 0;
//		int tmp_pic_width = 0;
		Pattern pattern = Pattern.compile("w{1}(\\+)?(\\-)?(\\d+\\.\\d+)|(\\d+)");
		Pattern patternt = Pattern.compile("<.{1,}>+?");
		Pattern patternL = Pattern.compile("[A-Z]");
		
		String[] values = str.split("\n");
//		int index = 0;
		for(String value : values) {
			Matcher m = patternt.matcher(value);
			if(m.find()) {
//				System.out.println("patternt:"+value+"::"+patternCount(patternt, value)+"=="+m.end(0));
			}
			for (int j = 0; j < value.length(); j++) {
				tmp_str = tmp_str+value.charAt(j);
//				System.out.println("tmp width="+tmp_str+"=="+patternCount(patternL, tmp_str));
//				if(((fm.stringWidth(tmp_str)+tmp_pic_width)-tmp_width)>=width) {
				if(fm.stringWidth(tmp_str) + patternCount(patternL, tmp_str)*4 >= width) {
					//如果有数字、规格、公差等字符时，需要在同一行输出
					int len = tmp_str.length();
					Matcher matcherBall = pattern.matcher(tmp_str);
					boolean flag = false;
					while (matcherBall.find()) {
						//System.out.println("matcherBall.find");
						int beginIndex = matcherBall.start();
						int endIndex = matcherBall.end();
						
						if(endIndex==len) {
							//判断下一个值
							if(j<value.length()-1) {
								String next_s = ""+value.charAt(j+1);
								String regex1 = "[0-9]";
								Pattern numPattern = Pattern.compile(regex1);
								if(!numPattern.matcher(next_s).matches())
								{
									break;
								}
							}
							
							//数值需要另起一行
							String str1 = tmp_str.substring(0, beginIndex);
							String temp = tmp_str.substring(beginIndex, endIndex);
							list2.add(str1);
//							tmp_width = 0;
//							tmp_pic_width=0;
							tmp_str = temp;
							flag = true;
						}
					}
					
					if(!flag) {
						list2.add(tmp_str);
//						tmp_width = 0;
//						tmp_pic_width=0;
						tmp_str = new String("");
					}
				}
			}
			if(!tmp_str.trim().equals("")) {
				list2.add(tmp_str);
				tmp_str = "";
			}
		}
		
		//System.out.println("list2:"+list2.toString());

		return list2;
	}

	public static int patternCount(Pattern pattern, String str) {
		int count = 0;
		Matcher matcher = pattern.matcher(str);
		while(matcher.find()) {
			count++;
		}
		return count;
	}


	private static int getPictureWidth(String value) {
		//  Auto-generated method stub
		File picture=new File(value);
		try {
			BufferedImage sourceImg = ImageIO.read(new FileInputStream(picture));
			return sourceImg.getWidth();
		} catch (Exception e) {
			//  Auto-generated catch block
			e.printStackTrace();
		}

		return 80;
	}
	
	/**
	 * 获取指定类型的下级BOM行,类型参数如果为*号,则指所有类型
	 * @param parent
	 * @param childType
	 * @return
	 */
	public static ArrayList getChildLines(TCComponentBOMLine parent,String[] childTypes)
	{
		ArrayList list = new ArrayList();
		
		try {
			if(childTypes==null||childTypes.length<=0)
			{
				return list;
			}
			List typeList = (List) Arrays.asList(childTypes);

			
			//如果BOM行本身类型正确，则不需要找下级(工艺过程与空间节点输出层级不一样)
			String parentType = parent.getItem().getType();
			if(typeList.contains(parentType)||parent.getItem().isTypeOf(childTypes))
			{
				list.add(parent);
				return list;
			}
			
			AIFComponentContext[] contexts = parent.getChildren();
			if(contexts!=null&&contexts.length>0)
			{
				for (int i = 0; i < contexts.length; i++) {
					TCComponentBOMLine child = (TCComponentBOMLine) contexts[i].getComponent();
					if(typeList.get(0).equals("*"))
					{
						list.add(child);
					}else
					{
						String childType = child.getItem().getType();
						if(typeList.contains(childType)||child.getItem().isTypeOf(childTypes))
						{
							list.add(child);
						}
					}
				}
			}
		} catch (Exception e) {
			//  Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return list;
	}
	
	
	/**
	 * 创建数据集
	 * @param session
	 * @param name
	 * @param type
	 * @return
	 */
	public static TCComponentDataset createDataset(TCSession session, String name,String type) {
		//  自动生成的方法存根
		TCComponentDataset dataset = null;
		try {
			TCComponentDatasetType datasetType = (TCComponentDatasetType) session.getTypeComponent("Dataset");
			dataset = datasetType.create(name, "", type);
		} catch (Exception e) {
			//  自动生成的 catch 块
			e.printStackTrace();
		}
		return dataset;
	}
	

	/**
	 * 获取关系对象数组
	 * @param comp
	 * @param relation
	 * @return
	 */
	public static TCComponent[] getRelComponents(TCComponent comp, String relation)
	{
		TCComponent[] comps = null;
		try {
			if(comp==null)
			{
				return comps;
			}
			comps = comp.getRelatedComponents(relation);
		} catch (Exception e) {
			//  Auto-generated catch block
			System.out.println("ERROR:"+comp.toString());
			e.printStackTrace();
		}
		
		return comps;
	}
	
	
	/**
	 * 获取关系对象
	 * @param comp
	 * @param relation
	 * @return
	 */
	public static TCComponent getRelComponent(TCComponent comp, String relation)
	{
		TCComponent component = null;
		try {
			
			if(comp==null)
			{
				return component;
			}
			
			TCComponent[] comps = comp.getRelatedComponents(relation);
			if (comps!=null&&comps.length > 0) {
				component = comps[0];// 如果存在多个制造目标怎么解决 ？？？
			}
		} catch (Exception e) {
			//  Auto-generated catch block
			System.out.println("ERROR:"+comp.toString());
			e.printStackTrace();
		}
		
		
		return component;
	}
	
	
	/**
	 * 获取对象的属性
	 * 
	 * @param target2
	 * @param string
	 * @return
	 */
	public static String getObjectProperty(TCComponent comp, String string) {
		//  自动生成的方法存根
		String value = "";
		try {
			if(comp==null)
			{
				return value;
			}
			value = comp.getProperty(string);
		} catch (Exception e) {
			//  自动生成的 catch 块
			System.out.println("ERROR:"+comp.toString());
			e.printStackTrace();
		}
		return value;
	}
	
	
	/**
	 * 获取对象规范关系下名称相同的数据集
	 * @param comp
	 * @param name
	 * @param type
	 * @return
	 */
	public static TCComponent[] getDatasetsByType(TCComponent comp,String[] types)
	{
		TCComponent[] datasets = null;
		try {
			TCComponent[] components = comp.getRelatedComponents("IMAN_specification");
			if(components==null||components.length<=0){
				return null;
			}
			
			ArrayList list = new ArrayList();
			for (int i = 0; i < components.length; i++) {
				String type1 = components[i].getType();
				for (int j = 0; j < types.length; j++) {
					if(components[i] instanceof TCComponentDataset &&type1.equals(types[j]))
					{
						list.add(components[i]);
						break;
					}
				}
			}
			
			datasets = (TCComponent[]) list.toArray(new TCComponent[list.size()]);
		} catch (Exception e) {
			//  Auto-generated catch block
			System.out.println("ERROR:"+comp.toString());
			e.printStackTrace();
		}
		
		return datasets;
	}
	
	
	/**
	 * 获取对象规范关系下名称相同的数据集
	 * @param comp
	 * @param name
	 * @param type
	 * @return
	 */
	public static TCComponent[] getDatasetByNames(TCComponent comp,String[] names,String type)
	{
		TCComponent[] datasets = null;
		try {
			TCComponent[] components = comp.getRelatedComponents("IMAN_specification");
			if(components==null||components.length<=0){
				return null;
			}
			List nameList = (List) Arrays.asList(names);
			
			ArrayList list = new ArrayList();
			for (int i = 0; i < components.length; i++) {
				String name1 = components[i].getProperty("object_name");
				String type1 = components[i].getType();
				if(nameList.contains(name1)&&type1.equals(type))
				{
					list.add(components[i]);
//					break;
				}
			}
			datasets = (TCComponent[]) list.toArray(new TCComponent[list.size()]);
			
		} catch (Exception e) {
			//  Auto-generated catch block
			System.out.println("ERROR:"+comp.toString());
			e.printStackTrace();
		}
		
		return datasets;
	}
	
	
	/**
	 * 获取对象规范关系下名称相同的数据集
	 * @param comp
	 * @param name
	 * @param type
	 * @return
	 */
	public static TCComponent getDatasetByName(TCComponent comp,String name,String type)
	{
		TCComponent dataset = null;
		try {
			TCComponent[] components = comp.getRelatedComponents("IMAN_specification");
			if(components==null||components.length<=0){
				return null;
			}
			for (int i = 0; i < components.length; i++) {
				String name1 = components[i].getProperty("object_name");
				String type1 = components[i].getType();
				if(name1.equals(name)&&type1.equals(type))
				{
					dataset = components[i];
					break;
				}
			}
		} catch (Exception e) {
			//  Auto-generated catch block
			System.out.println("ERROR:"+comp.toString());
			e.printStackTrace();
		}
		
		return dataset;
	}
	
	
	/**
	 * 检查对指定对象的写权限
	 * @param session
	 * @param comp
	 * @return
	 */
	public static boolean hasWritePrivilege(TCSession session, TCComponent comp) {
		try {
			TCAccessControlService accessControlService = session.getTCAccessControlService();
			TCComponent component = (TCComponent) comp;

			if (comp instanceof TCComponentBOMLine) {
				// 检查bomview
				TCComponentBOMLine bomline = (TCComponentBOMLine) comp;
				TCComponentItemRevision ir = bomline.getItemRevision();
				TCComponent[] bvs = ir.getRelatedComponents("structure_revisions");

				if (bvs != null && bvs.length > 0) {
					component = bvs[0];
				}
			}
			return accessControlService.checkPrivilege(component, "WRITE");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}


	/**
	 * 获取BOM行对象的版本
	 * @param partLine
	 * @return
	 */
	public static TCComponentItemRevision getBOMLineRev(TCComponentBOMLine partLine) {
		//  Auto-generated method stub
		try {
			TCComponentItemRevision rev = partLine.getItemRevision();
			if(rev==null)
			{
				System.out.println("WARNING:BOM行版本未加载  "+partLine.toString());
			}
			return rev;
		} catch (Exception e) {
			//  Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * 替换Word中的指定内容为图片
	 * @param word
	 * @param map
	 */
	public static void replaceImage(WordBean word, HashMap map) {
		// TODO Auto-generated method stub
		
		Iterator it =	map.entrySet().iterator();
		while(it.hasNext())
		{
			Map.Entry<String, String> entry = (Entry<String, String>) it.next();
			word.moveStart();
			word.replaceAllImage(entry.getKey(), entry.getValue());
		}
	}

	/**
	 * 下载工程中的图片到本地
	 * @param workDir
	 * @param picName
	 * @return
	 */
	public static String downloadPicture(String workDir, String picName) {
		//  Auto-generated method stub
		InputStream inputStream= Util.class.getResourceAsStream(picName);
		
		if(!workDir.endsWith("\\"))
		{
			workDir = workDir+"\\";
		}
		File file = new File(workDir+picName);

		if(file.exists())
		{
			return file.getAbsolutePath();
		}
		
		try {
			FileOutputStream output = new FileOutputStream(file);
			byte[] b = new byte[1024 * 1024];
			int len;
			while ((len = inputStream.read(b)) != -1) {
				output.write(b, 0, len);
			}
			output.flush();
			output.close();
		} catch (Exception e) {
			//  Auto-generated catch block
			e.printStackTrace();
		}
		
		return file.getAbsolutePath();
	}


	/**
	 * 获取布尔类型的属性值
	 * @param component
	 * @param property
	 * @return
	 */
	public static boolean getLogicalProperty(TCComponent component, String property) {
		//  Auto-generated method stub
		if(component==null)
		{
			return false;
		}
		try {
			boolean flag = component.getLogicalProperty(property);
			return flag;
		} catch (Exception e) {
			//  Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}

	
	
	/**
	 * 获取多个list中最大的大小值
	 * @param lists
	 * @return
	 */
	public static int getMaxListNum(ArrayList lists) {
		// TODO Auto-generated method stub
		int max = 0;
		for (int i = 0; i < lists.size(); i++) {
			ArrayList list = (ArrayList) lists.get(i);
			if (list.size()> max) {
				max = list.size();
			}
		}
		return max;
	}
	
	/**
	 * 获取工装值转为list
	 * @param compList
	 * @return
	 */
	public static ArrayList getToolingPropertyList(ArrayList compList) {
		// TODO Auto-generated method stub
		ArrayList list = new ArrayList();
		for (int i = 0; i < compList.size(); i++) {
			TCComponentBOMLine bomLine = (TCComponentBOMLine) compList.get(i);
			TCComponentItemRevision revision = Util.getBOMLineRev(bomLine);
			String value =  Util.getObjectProperty(revision, "object_name");
			TCComponent form = Util.getRelComponent(revision, "IMAN_master_form_rev");
			String value2 =  Util.getObjectProperty(form, "t5_ToolNumber");
			list.add(value+" "+value2);
		}
		return list;
	}
	
	
	/**
	 * 获取属性值转为list
	 * @param compList
	 * @param property
	 * @return
	 */
	public static ArrayList getAccessoryPropertyList(ArrayList compList, String property) {
		//  Auto-generated method stub
		ArrayList list = new ArrayList();
		for (int i = 0; i < compList.size(); i++) {
			TCComponent component = (TCComponent) compList.get(i);
			String value =  Util.getObjectProperty(component, property);
			
			if(component instanceof TCComponentBOMLine)
			{
				try {
					TCComponentBOMLine bomLine = (TCComponentBOMLine) component;
					TCComponentItemRevision revision = bomLine.getItemRevision();
					TCComponent form = Util.getRelComponent(revision, "IMAN_master_form_rev");
					String paihao = Util.getObjectProperty(form, "t5_paihao");
					value = value+paihao;
				} catch (Exception e) {
					//  Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
			list.add(value);
		}
		return list;
	}
	
	
	/**
	 * 获取属性值转为list
	 * @param compList
	 * @param property
	 * @return
	 */
	public static ArrayList getPropertyList(ArrayList compList, String property) {
		//  Auto-generated method stub
		ArrayList list = new ArrayList();
		for (int i = 0; i < compList.size(); i++) {
			TCComponent component = (TCComponent) compList.get(i);
			String value =  Util.getObjectProperty(component, property);
			list.add(value);
		}
		return list;
	}
	
	
	/**
	 * list添加空值
	 * @param list
	 * @param maxRow
	 * @return
	 */
	public static  ArrayList addNullValue(ArrayList list, int maxRow) {
		//  Auto-generated method stub
		if (list.size() < maxRow) {
			int n = maxRow - list.size();
			for (int k = 0; k < n; k++) {
				list.add("");
			}
		}
		return list;
	}

	/**
	 * 获取对象上级（何处使用）
	 * @param rev
	 * @return
	 */
	public static TCComponent[] gewWhereUsed(TCComponentItemRevision rev) {
		try {
			TCComponent[] parentComps = rev.whereUsed(TCComponentItemRevision.WHERE_USED_ALL);
			List parentList = new ArrayList();
			HashMap map = new HashMap();
			for (int i = 0; i < parentComps.length; i++) {
				if (parentComps[i].getIntProperty("active_seq") == 1) {
					String id = parentComps[i].getProperty("item_id");
					String revId = parentComps[i].getProperty("item_revision_id");
					if (map.containsKey(id)) {
						TCComponent rev1 = (TCComponent) map.get(id);
						String revId1 = rev1.getProperty("item_revision_id");
						if (revId.compareTo(revId1) > 0) {
							parentList.remove(rev1);
							parentList.add(parentComps[i]);
							map.put(id, parentComps[i]);
						} else {
							continue;
						}
					} else {
						parentList.add(parentComps[i]);
						map.put(id, parentComps[i]);
					}
				}
			}

			if (!parentList.isEmpty()) {
				return (TCComponent[]) parentList.toArray(new TCComponent[parentList.size()]);
			}
		} catch (Exception e) {
			//  Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}
	
	
	/**
	 * 判断对象是否已有状态
	 * @param object
	 * @return
	 */
	public static boolean hasStatus(TCComponent object) {
		try {

			object.refresh();
			TCComponent[] relStatus = object.getReferenceListProperty("release_status_list");
			if (relStatus == null || relStatus.length <= 0) {
				// System.out.println("找不到状态");
				return false;
			} else {
				return true;
			}
		} catch (Exception e) {
			//  Auto-generated catch block
			e.printStackTrace();
			return false;
		}

	}
	
	/**
	 * 复制文件
	 * @param srcName
	 * @param targetName
	 * @return
	 * @throws IOException
	 */
	public static int copyFile(String srcName, String targetName) throws Exception {
		File srcFile = new File(srcName);
		File targetFile = new File(targetName);
		File parentDir = new File(targetFile.getParent());
		if (!srcFile.isFile()) {
			return 0;
		}

		if (targetFile.isFile()) {
			targetFile.delete();
		}
		if (!parentDir.isDirectory()) {
			parentDir.mkdirs();
		}

		FileInputStream input = new FileInputStream(srcFile);
		FileOutputStream output = new FileOutputStream(targetFile);

		byte[] b = new byte[1024];
		int len;
		while ((len = input.read(b)) != -1) {
			output.write(b, 0, len);
		}
		output.flush();
		output.close();
		input.close();
		return 1;
	}

//	/**
//	 * 根据内容宽度List转换
//	 * @param list
//	 * @param width
//	 * @return
//	 */
//	public static ArrayList transList(ArrayList list,int width) {
//		//  Auto-generated method stub
//		ArrayList resultList =  new ArrayList();
//		
//		for (int k = 0; k < list.size(); k++) {
//			ArrayList tempList = new ArrayList();
//			tempList.add(list.get(k));
//			Object[] objs = Util.list2map(tempList,width);
//			ArrayList list2  = (ArrayList) objs[0]; 
//			resultList.addAll(list2);
//		}
//		
//		return resultList;
//	}
}
