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

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.connor.nhjs.gy.findpz.WordBean;
import com.connor.nhjs.gy.findpz.WordCache;
//import com.jacob.activeX.ActiveXComponent;
//import com.jacob.com.ComThread;
//import com.jacob.com.Dispatch;
//import com.jacob.com.Variant;
import com.teamcenter.rac.aif.AbstractAIFOperation;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentDatasetType;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentTcFile;
import com.teamcenter.rac.kernel.TCPreferenceService;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;

public class FindPzOperation extends AbstractAIFOperation {

	private TCSession session;
	private FindPzBean bean;
	private File file;
	private ProgressBarThread wait;
	private String wjjname = "工艺更改单";
	private TCComponentItemRevision rev;
	public FindPzOperation(TCSession session, TCComponentItemRevision rev) {
		//  Auto-generated constructor stub
		this.session = session;
//		this.bean = bean;
		this.rev = rev;
		
//		TCComponentItemRevision rev = (TCComponentItemRevision) target;
//		String type = this.rev.getType();
//		if("NHL8_PChangeRevision".equals(type)) {
//			try {
//		ActiveXComponent word = new ActiveXComponent("Word.Application");
//		word.setProperty("Visible", new Variant(false));
//		word.setProperty("DisplayAlerts", new Variant(false));
//		Dispatch documents = word.getProperty("Documents").toDispatch();
////		Dispatch.call(documents, "Open", docPath).toDispatch();
//		ComThread.InitMTA();
		this.bean = this.loadBean(rev);
////				FindPzOperation operation = new FindPzOperation(session,bean,rev);
////				session.queueOperation(operation);
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}else {
//			MessageBox.post("请选中工艺更改单版本对象执行操作!!!!", "提示", MessageBox.INFORMATION);
//			return null;
//		}

	}

	
	private FindPzBean loadBean(TCComponentItemRevision rev) {
		FindPzBean bean = null;
		try {
			TCComponent form = rev.getReferenceListProperty("IMAN_master_form_rev")[0];
			String[] props = new String[] {"nhl8_PartNub","nhl8_ChangeName","nhl8_DrawingRev",
					"nhl8_ProcessType","nhl8_ProcessCode","nhl8_ProcessRev","nhl8_ReviseReason",
					"nhl8_ProductSolution","nhl8_ProductionSolution"};
			String[] propValues = form.getProperties(props);
			String id = rev.getStringProperty("item_id");
			bean = new FindPzBean(id,propValues[0],propValues[1],propValues[2],
					propValues[3],propValues[4],propValues[5],
					propValues[6],propValues[7],propValues[8]);
			
			String[] prop1 = new String[] {"nhl8_SerialNub", "nhl8_ChangeNub", "nhl8_ChangeName"};
			List<DesignChange> list1 = getTableValue(form, "nhl8_DesignChange", prop1);
			bean.setChanges(list1);
			
			String[] prop2 = new String[] {"nhl8_Mark", "nhl8_BeforeChange", "nhl8_AfterChange"};//TODO nhl8_SerialNub
			List<DesignChange> list2 = getTableValue(form, "nhl8_ChangeDesc", prop2);
			
			bean.setDescs(list2);
		} catch (Exception e) {
			//  Auto-generated catch block
			e.printStackTrace();
		}
		
		//  Auto-generated method stub
		return bean;
	}
	public List<DesignChange> getTableValue(TCComponent item, String prop, String[] propNames) {
		List<DesignChange> list = new ArrayList<DesignChange>();
		try {
			TCComponent[] com = item.getTCProperty(prop).getReferenceValueArray();
			for (int i = 0; i < com.length; ++i) {
				TCComponent tableValue = com[i];
				String[] value = new String[propNames.length];
				for (int j = 0; j < propNames.length; ++j) {
					value[j] = tableValue.getProperty(propNames[j]);
//					System.out.println("value==="+value[j]);
				}
				DesignChange bean = new DesignChange(value[0], value[1], value[2]);
				list.add(bean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	
	@Override
	public void executeOperation() throws Exception {
		//  Auto-generated method stub
		WordCache.init();
		file = getSXX();
		if (file != null) {
			wait = new ProgressBarThread("生成word", "生成数据中，请稍等...");
			wait.start();// 开启进度条
			// getVal();
			try {
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
				String time = df.format(new Date());
				wjjname = "工艺更改单" + time;
				writeWord(bean);
			} catch (Exception e) {
				//  Auto-generated catch block
				e.printStackTrace();
				wait.setBool(true);// 关闭进度条
				wait.interrupt();
				MessageBox.post("生成失败" + e.getMessage(), "错误", MessageBox.ERROR);
				Thread thread = new Thread() {
					public void run() {
						WordCache.clear();
					}
				};
				thread.start();
				return;
			}
			wait.setBool(true);// 关闭进度条
			wait.interrupt();
//			MessageBox.post("工艺更改单生成完成,请查看", "完成", MessageBox.INFORMATION);
		}
		Thread thread = new Thread() {
			public void run() {
				WordCache.clear();
			}
		};
		thread.start();

	}

	public File getSXX() {
		TCPreferenceService pref = session.getPreferenceService();
		String puid = pref.getStringValue("Connor_Word_Pz_Puid");// 首选项查puid QKlJVPqKphnsxD wdjJGQe1phnsxD
		if (puid != null && !("".equals(puid))) {
			try {
				TCComponentDataset dataset = (TCComponentDataset) session.stringToComponent(puid);
				if (dataset == null) {
					return null;
				}
				TCComponentTcFile[] file = dataset.getTcFiles();
				if (file.length == 0 || file.length != 1) {
					MessageBox.post("数据集没有命名引用的文件或文件过多，请检查！", "WARNING", MessageBox.WARNING);
					return null;
				} else {
					File fmsFile = file[0].getFmsFile();
					return fmsFile;
				}
			} catch (Exception e) {
				//  Auto-generated catch block
				e.printStackTrace();
			}

		} else {
			MessageBox.post("未找到首选项[Connor_Word_Pz_Puid]或首选项配置错误", "错误", MessageBox.ERROR);
			return null;
		}
		return null;
	}

	private void writeWord(FindPzBean bean) {
		// TODO writeWord
//		FileSystemView fsv = FileSystemView.getFileSystemView(); // 得到系统的fileview
//		String deskPath = fsv.getHomeDirectory().getPath(); // 当前用户的桌面路径

		try {
			String itemname = bean.getChangeName();
			String filepath = System.getProperty("java.io.tmpdir");
			File tempwjjfile = new File(filepath + File.separator + wjjname);
			if (!tempwjjfile.exists()) {// 如果文件夹不存在
				tempwjjfile.mkdir();// 创建文件夹
			}
			String parentpath = filepath + File.separator + wjjname + File.separator + itemname;
			String temppath = parentpath + ".doc";
			String ystemppath = parentpath + "模板.doc";
			String pdfpath = parentpath + ".pdf";


			Util.copyFile(file.getPath(), temppath);
			Util.copyFile(file.getPath(), ystemppath);
			WordBean word = null;
			PzCard card = new PzCard(bean, new File(temppath),new File(ystemppath), session);
			word = card.writeDataToWord();	
			if (word != null) {
				word.save(temppath);
				word.saveToPDF(pdfpath);
				word.closeDocument();
				word.close();
				//				String filePathtoSave = deskPath + File.separator + wjjname + File.separator + itemname + ".doc";
				//				File wjjfile = new File(deskPath + File.separator + wjjname);
				//				if (!wjjfile.exists()) {// 如果文件夹不存在
				//					wjjfile.mkdir();// 创建文件夹
				//				}
				//				Util.copyFile(temppath, filePathtoSave);
				String name = rev.getStringProperty("object_name");
				TCComponent[] datas = rev.getReferenceListProperty("IMAN_Rendering");
				for (int i = 0; i < datas.length; i++) {
					String type = datas[i].getType();
					String data_name = datas[i].getStringProperty("object_name");
					if("PDF".equals(type) && name.equals(data_name)) {
						rev.remove("IMAN_Rendering", datas[i]);
						datas[i].delete();
						break;
					}
				}
				TCComponentDataset dataset = createDataset(name, "PDF");
				String[] path = new String[1];
				String[] ref_type = new String[1];
//				path[0] = temppath;
//				ref_type[0] = "word";
				path[0] = pdfpath;
				ref_type[0] = "PDF_Reference";
				dataset.setFiles(path, ref_type);
				rev.add("IMAN_Rendering", dataset);
			}
		} catch (Exception e) {
			//  Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 方法描述
	 * 根据参数创建模板文件数据集。
	 * @param 
	 * CPTID ：需要创建的数据集id
	 * 返回值描述
	 * 返回创建的模板数据集对象
	 */
	private TCComponentDataset createDataset(String name, String type) {
		TCComponentDataset mbDataset = null;
//		String type = "MSWord";
		try {
			TCComponentDatasetType datasetType = (TCComponentDatasetType) session.getTypeComponent("Dataset");
			mbDataset = datasetType.create(name, "", type);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mbDataset;
	}
}
