package cust.com.rac.integration;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Pattern;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentTcFile;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCUserService;

@SuppressWarnings("deprecation")
public class InterationOperation {

	private static String totalCost = "";
	private static String norobotCost = "";
	private static int startRow = 0;
	private static int stepNo = 1;
	private static HashMap<String, Integer> jqrbt;
	private static DecimalFormat df = new DecimalFormat(".00");
	private static String[] stations = new String[] { "", "", "", "", "" };
	
	public static String sendProjectPlanToBPM(TCComponentItemRevision itemRevision, String url){
		
		String errMsg = "";
		
		try {
			TCComponentForm masterForm = (TCComponentForm) itemRevision.getRelatedComponent("IMAN_master_form_rev");
//			String itemInfo = XMLDocAPI.createProjectPlanXML(masterForm, itemRevision.getProperty("project_ids"));// lidy20190603处理特殊字符
			String itemInfo = XMLDocAPI.createProjectPlanXML(masterForm, itemRevision.getProperty("project_ids"))
					.replaceAll("%26", "&amp;").replaceAll("%3C", "&lt;").replaceAll("%3E", "&gt;").replaceAll("%27", "&apos;")
					.replaceAll("%22", "&quot;");
			if( !itemInfo.startsWith("Error")){
				System.out.println("deliveryInfo = "+itemInfo);
				String subUrl = url + "method=Submit&from_system_id=PLM&process=%e9%a1%b9%e7%9b%ae%e8%bf%9b%e5%ba%a6";
				String requestXML = RequestServer.request(subUrl, itemInfo);
				if(!requestXML.startsWith("Error")){
					System.out.println("sendProjectPlanToBPM errMsg = "+requestXML);
					errMsg = XMLDocAPI.readXmlErrorMsg(requestXML);
				}else{
					errMsg = requestXML;
				}
				if(errMsg.equals("")){
					TCComponent[] components = itemRevision.getRelatedComponents("IMAN_specification");
					if (components != null && components.length != 0) {
						for (TCComponent comp : components) {
							if (comp instanceof TCComponentDataset) {
								TCComponentDataset dataSet = (TCComponentDataset)comp;
								if ((dataSet.getTcFiles() != null) && (dataSet.getTcFiles().length > 0)) {
									TCComponentTcFile tcFile = dataSet.getTcFiles()[0];
									String fileName = tcFile.getProperty("original_file_name");
									File file = tcFile.getFile(System.getenv("temp"), fileName);
									if(file != null){
//										subUrl = url + "from_system_id=PLM&process=%e9%a1%b9%e7%9b%ae%e8%bf%9b%e5%ba%a6&taskid="
//												+XMLDocAPI.readXmlTaskID(requestXML);//itemRevision.getProperty("item_id"); 
										subUrl = "http://192.168.0.69:3378/YZSoft/Attachment/Upload.ashx?from_system_id=PLM&process"
												+ "=%e9%a1%b9%e7%9b%ae%e8%bf%9b%e5%ba%a6&taskid="+XMLDocAPI.readXmlTaskID(requestXML);
										System.out.println("subUrl="+subUrl);
										errMsg = RequestServer.sendFile(subUrl, file.getAbsolutePath());
										if(!errMsg.startsWith("Error")){
											System.out.println("sendFileToBPM errMsg = "+errMsg);
											errMsg = XMLDocAPI.readXmlErrorMsg(errMsg);
										}
									}
								}
								break;
							}
						}
					}
				}
				if(errMsg.equals("")){
					errMsg = "传递成功!";
				}
			}else{
				errMsg = itemInfo;
			}
		} catch (TCException e) {
			errMsg = e.getMessage();
			e.printStackTrace();
		}
		return errMsg;
	}

	public static String sendDeliveryApplicationToBPM(TCComponentItemRevision DeliveryRevision, String url){
		
		String errMsg = "";
		
		try {
			TCComponentForm masterForm = (TCComponentForm) DeliveryRevision.getRelatedComponent("IMAN_master_form_rev");
			String deliveryInfo = XMLDocAPI.createDeliveryApplicationXML(masterForm);
			if( !deliveryInfo.startsWith("Error")){
				System.out.println("deliveryInfo = "+deliveryInfo);
				url = url + "method=Submit&from_system_id=PLM&process=%e5%8f%91%e8%b4%a7%e7%94%b3%e8%af%b7%e5%8d%95";
				errMsg = RequestServer.request(url, deliveryInfo);
				if(!errMsg.startsWith("Error")){
					System.out.println("errMsg = "+errMsg);
					errMsg = XMLDocAPI.readXmlErrorMsg(errMsg);
				}
				if(errMsg.equals("")){
					errMsg = "传递成功!";
				}
			}else{
				errMsg = deliveryInfo;
			}
		} catch (TCException e) {
			errMsg = e.getMessage();
			e.printStackTrace();
		}
		return errMsg;
	}
	
	public static String sendAccepComToBPM(TCComponentItemRevision AccepComRevision, String url){
		
		String errMsg = "";
		
		try {
			TCComponentForm masterForm = (TCComponentForm) AccepComRevision.getRelatedComponent("IMAN_master_form_rev");
			// lidy20190603处理特殊字符
//			String acceptComInfo = XMLDocAPI.createAcceptComInfoXML(masterForm, AccepComRevision.getProperty("item_id"));
			String acceptComInfo = XMLDocAPI.createAcceptComInfoXML(masterForm, AccepComRevision.getProperty("item_id"))
					.replaceAll("%26", "&amp;").replaceAll("%3C", "&lt;").replaceAll("%3E", "&gt;").replaceAll("%27", "&apos;")
					.replaceAll("%22", "&quot;");
			if( !acceptComInfo.startsWith("Error")){
				System.out.println("deliveryInfo = "+acceptComInfo);
				url = url + "method=Submit&from_system_id=PLM&process=%e9%aa%8c%e6%94%b6%e5%a7%94%e6%89%98";
				errMsg = RequestServer.request(url, acceptComInfo);
				if(!errMsg.startsWith("Error")){
					System.out.println("errMsg = "+errMsg);
					errMsg = XMLDocAPI.readXmlErrorMsg(errMsg);
				}
				if(errMsg.equals("")){
					errMsg = "传递成功!";
				}
			}else{
				errMsg = acceptComInfo;
			}
		} catch (TCException e) {
			errMsg = e.getMessage();
			e.printStackTrace();
		}
		return errMsg;
	}
	
	public static String sendQuotationApplicationToBPM(TCSession session, TCComponentItemRevision quotationRevision, String url){
		System.out.println("sendQuotationApplicationToBPM");
		
		String errMsg = "";
		jqrbt = new HashMap<String, Integer>();
		FileInputStream in = null;
		
		try {
			TCComponentForm masterForm = (TCComponentForm) quotationRevision.getRelatedComponent("IMAN_master_form_rev");
			Date finished = masterForm.getDateProperty("ysr8_FinishedDate");//lidy20181108完成日期不为空不允许传递
			if(finished!=null) {
				return "该报价已完成传递，请勿重复传递！";
			}
			TCComponent quotationMX = null;
			TCComponent quotationFA = null;
			String tempName = "";
			
			String itemID = quotationRevision.getProperty("item_id");
			String version = quotationRevision.getProperty("item_revision_id");//lidy20181106增加版本号
			TCComponent[] relatedComs = quotationRevision.getRelatedComponents();
			int cnt = relatedComs.length;
			
			for(int ix = 0; ix < cnt; ix++){
				tempName = relatedComs[ix].getProperty("object_name");
				if(tempName.startsWith(itemID+"MX")){
					quotationMX = relatedComs[ix];
//				}else if(tempName.equals(itemID+"FA.docx") || tempName.equals(itemID+"FA.doc")){//lidy20180925数据集名称加后缀
				}else if(tempName.startsWith(itemID+"FA")){//lidy20180925数据集名称加后缀
					quotationFA = relatedComs[ix];
				}
			}
			
			if(quotationMX != null && quotationMX.getType().equals("MSExcelX")){
				TCComponentDataset dataset = (TCComponentDataset) quotationMX;
				if(dataset.getTcFiles() != null){
					File file = dataset.getTcFiles()[0].getFile(System.getenv("temp"));
					System.out.println("file:"+file.getPath());
					
					in = new FileInputStream(file);// 
					System.out.println("in");
					XSSFWorkbook wb = new XSSFWorkbook(in);
					System.out.println("wb:"+wb.getNumberOfSheets());
					XSSFSheet sheet = wb.getSheetAt(0);
					
					Document document = DocumentHelper.createDocument();
					Element FormData = document.addElement("FormData"); 
					
//					readBaseInfo(sheet, FormData, itemID, version, masterForm.getProperty("ysr8_Remark"));
					System.out.println("readBaseInfo");
					readBaseInfo(sheet, FormData, itemID, version, quotationRevision.getItem().getProperty("ysr8_QuotationRemarks"));
					System.out.println("getTotalCostMX");
					getTotalCostMX(sheet, FormData);
					System.out.println("getLabourCostMX");
					getLabourCostMX(sheet, FormData);
					System.out.println("getWorkStation");
					
					int sheetCount = wb.getNumberOfSheets();
					for(int ix = 1; ix < sheetCount; ix++){
						sheet = wb.getSheetAt(ix);
						if(isInteger(sheet.getSheetName())){
							getWorkStation(sheet,FormData);
						}
					}
					in.close();
					
					XMLWriter xmlWriter = null;
			        StringWriter stringWrite = new StringWriter();
			        
			        OutputFormat format = OutputFormat.createPrettyPrint();  //转换字符串格式
			        format.setEncoding("UTF-8");
			        format.setNewlines(true);
			        
			      //输出字符串
			        xmlWriter = new XMLWriter(stringWrite, format);
			        xmlWriter.write(document);
			        xmlWriter.flush();
			        xmlWriter.close();
			        //lidy20190314处理特殊字符
//			        String msg = stringWrite.toString().replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
//			        		.replaceAll("'", "&apos;").replaceAll("\"", "&quot;");
			        String msg = stringWrite.toString().replaceAll("%26", "&amp;").replaceAll("%3C", "&lt;").replaceAll("%3E", "&gt;")
			        		.replaceAll("%27", "&apos;").replaceAll("%22", "&quot;");
			        System.out.println("msg="+msg);
			        
			        String subUrl = url + "method=Submit&from_system_id=PLM&process=%e6%8a%a5%e4%bb%b7%e6%b8%85%e5%8d%95%e6%95%b0%e6%8d%ae";
					String requestXML = RequestServer.request(subUrl, msg);
					if(!requestXML.startsWith("Error")){
						System.out.println("sendProjectPlanToBPM errMsg = "+requestXML);
						errMsg = XMLDocAPI.readXmlErrorMsg(requestXML);
					}else{
						errMsg = requestXML;
					}
					
					if(errMsg.equals("")){
						String taskid = XMLDocAPI.readXmlTaskID(requestXML);
						subUrl = "http://192.168.0.69:3378/YZSoft/Attachment/Upload.ashx?from_system_id=PLM&process="
								+ "%e6%8a%a5%e4%bb%b7%e6%b8%85%e5%8d%95%e6%95%b0%e6%8d%ae&taskid="+taskid;
						System.out.println("subUrl="+subUrl);
						errMsg = RequestServer.sendFile(subUrl, file.getAbsolutePath());
						if(!errMsg.startsWith("Error")){
							System.out.println("sendFileToBPM errMsg = "+errMsg);
							errMsg = XMLDocAPI.readXmlErrorMsg(errMsg);
						}
						
//						if(quotationFA != null && (quotationMX.getType().equals("MSWordX") || quotationMX.getType().equals("MSWord"))){
						if(quotationFA != null){
							dataset = (TCComponentDataset) quotationFA;
							if(dataset.getTcFiles() != null){
								file = dataset.getTcFiles()[0].getFile(System.getenv("temp"));
								errMsg = RequestServer.sendFile(subUrl, file.getAbsolutePath());
								if(!errMsg.startsWith("Error")){
									System.out.println("sendFileToBPM errMsg = "+errMsg);
									errMsg = XMLDocAPI.readXmlErrorMsg(errMsg);
								}
							}
						}
						
						if(errMsg.equals("")){
							errMsg = "传递成功!";
							if(masterForm != null){
								//lidy20181108更新已传递版本
								TCComponentItem quotation = quotationRevision.getItem();
								String ysr8_HistoricRev = quotation.getStringProperty("ysr8_HistoricRev");
								if(ysr8_HistoricRev.isEmpty()) {
									ysr8_HistoricRev = version;
								} else {
									ysr8_HistoricRev = ysr8_HistoricRev+","+version;
								}
							    String params = quotation.getUid() + "^^^^ysr8_HistoricRev^^^^" + ysr8_HistoricRev;
								String cmd = "Update_Item_TCProperty";
								Object[] objParams = new Object[2];
								objParams[0] = cmd;
								objParams[1] = params;
								TCUserService userService = session.getUserService();
								String result = (String) userService.call("YSR8UserService", objParams);
								System.out.println("更新Item属性："+result);

//								Calendar cal = Calendar.getInstance();

//						        System.out.println("ysr8_FinishedDate:"+cal.getTime()+"--ysr8_OfferAmount:"+totalCost+"--jqrbt:"+jqrbt.size());

								// 20191029取A版完成时间
								if(!version.equals("A")) {
									TCComponentForm formA = (TCComponentForm)getItemRevisionFromItem(quotation, "A")
											.getRelatedComponent("IMAN_master_form_rev");
									masterForm.setDateProperty("ysr8_FinishedDate", formA.getDateProperty("ysr8_FinishedDate"));
								}else
									masterForm.setDateProperty("ysr8_FinishedDate", new Date());
								if(totalCost.isEmpty())
									totalCost = "0";
								masterForm.setProperty("ysr8_OfferAmount", totalCost);
								StringBuffer robotModelAndNum = new StringBuffer();
						        for (String s : jqrbt.keySet()) {
						        	System.out.println(s+"×"+jqrbt.get(s));
						        	robotModelAndNum.append(s).append("×").append(jqrbt.get(s)).append(";");
						        }
						        System.out.println("key:" + robotModelAndNum);
								masterForm.setProperty("ysr8_RobotModelAndNum", robotModelAndNum.toString());
								
								masterForm.setProperty("ysr8_NoRobotCost", norobotCost);//TODO 
								masterForm.setProperty("ysr8_RobotCount", stations[0]);
								masterForm.setProperty("ysr8_Positioner", stations[1]);
								masterForm.setProperty("ysr8_Fixture", stations[2]);
								masterForm.setProperty("ysr8_Grid", stations[3]);
								masterForm.setProperty("ysr8_Attachment", stations[4]);
							}
						}
					}
				}
			} else {
				errMsg="未找到正确的报价明细表！";
			}
			
		} catch (Exception e) {
			errMsg = "错误："+e.getMessage();
			e.printStackTrace();
		}finally {
			if(in != null)
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return errMsg;
	}
	
	private static void readBaseInfo(XSSFSheet sheet, Element FormData, String itemID, String version, String remark){
		
		String customerName = "";
		String projectName = "";
		String validityPeriod = "";
		String manuCycle = "";
//		String totalCost = "";
		String quotationOrderNo = "";
		String quoteDate = "";
		String approver = "";
		String reviewer = "";
		String creator = "";
	
//		sheet.setForceFormulaRecalculation(true);
		XSSFRow row = sheet.getRow(5);
		if(row != null){
			XSSFCell cell = row.getCell(1);
			if(cell != null){
				customerName = cell.getStringCellValue();
			}
			cell = row.getCell(6);
			if(cell != null){
				quotationOrderNo = cell.getStringCellValue();
			}
		}
		row = sheet.getRow(6);
		if(row != null){
			XSSFCell cell = row.getCell(1);
			if(cell != null){
				projectName = cell.getStringCellValue();
			}
			cell = row.getCell(6);
			if(cell != null){
				//lidy20190301支持日期格式
				if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC && DateUtil.isCellDateFormatted(cell)) {
					quoteDate = String.format("%tF", cell.getDateCellValue()).replaceAll("-0", "-").replaceAll("-", ".");
				}else
					quoteDate = cell.getStringCellValue();
			}
		}
		row = sheet.getRow(7);
		if(row != null){
			XSSFCell cell = row.getCell(1);
			if(cell != null){
				validityPeriod = cell.getStringCellValue();
			}
		}
		row = sheet.getRow(8);
		if(row != null){
			XSSFCell cell = row.getCell(1);
			if(cell != null){
				manuCycle = cell.getStringCellValue();
			}
			cell = row.getCell(5);
			if(cell != null){
				approver = cell.getStringCellValue();
			}
			cell = row.getCell(6);
			if(cell != null){
				reviewer = cell.getStringCellValue();
			}
			cell = row.getCell(7);
			if(cell != null){
				creator = cell.getStringCellValue();
			}
		}
		row = sheet.getRow(9);
		if(row != null){
			XSSFCell cell = row.getCell(1);
			if(cell != null){
				int type = cell.getCellType();
				if(type==XSSFCell.CELL_TYPE_FORMULA || type==XSSFCell.CELL_TYPE_BLANK) {
					totalCost = df.format(cell.getNumericCellValue());
					if(totalCost.equals(".00"))
						totalCost = "";
				}else {
					cell.setCellType(XSSFCell.CELL_TYPE_STRING);
					totalCost = cell.getStringCellValue();
				}
			}
		}
		row = sheet.getRow(10);
		if(row != null){
			XSSFCell cell = row.getCell(1);
			if(cell != null){
				int type = cell.getCellType();
				if(type==XSSFCell.CELL_TYPE_FORMULA || type==XSSFCell.CELL_TYPE_BLANK) {
					norobotCost = df.format(cell.getNumericCellValue());
					if(norobotCost.equals(".00"))
						norobotCost = "";
				}else {
					cell.setCellType(XSSFCell.CELL_TYPE_STRING);
					norobotCost = cell.getStringCellValue();
				}
			}
		}
		
//		System.out.println("客户名称="+customerName);
//		System.out.println("项目名称="+projectName);
//		System.out.println("报价有效期="+validityPeriod);
//		System.out.println("制造周期="+manuCycle);
//		System.out.println("成本总金额="+totalCost);
//		System.out.println("报价委托单编号="+quotationOrderNo);
//		System.out.println("报价时间="+quoteDate);
//		System.out.println("批准="+approver);
//		System.out.println("审核="+reviewer);
//		System.out.println("作成="+creator);
		
		Element home1 = FormData.addElement("Home1");
		home1.addElement("PLMItemID").addText(itemID);
		try {
			home1.addElement("ysr8_CustomerName").addText(URLEncoder.encode(customerName,"UTF-8"));
			home1.addElement("ysr8_ProjectName").addText(URLEncoder.encode(projectName,"UTF-8"));
			home1.addElement("ysr8_Version").addText(version);
			home1.addElement("ValidityPeriod").addText(URLEncoder.encode(validityPeriod,"UTF-8"));
			home1.addElement("ManuCycle").addText(URLEncoder.encode(manuCycle,"UTF-8"));
			home1.addElement("TotalCost").addText(URLEncoder.encode(totalCost,"UTF-8"));
			home1.addElement("QuotationOrderNo").addText(URLEncoder.encode(quotationOrderNo,"UTF-8"));
			home1.addElement("QuoteDate").addText(URLEncoder.encode(quoteDate,"UTF-8"));
			home1.addElement("Approver").addText(URLEncoder.encode(approver,"UTF-8"));
			home1.addElement("Reviewer").addText(URLEncoder.encode(reviewer,"UTF-8"));
			home1.addElement("Creator").addText(URLEncoder.encode(creator,"UTF-8"));
			home1.addElement("ysr8_Remark").addText(URLEncoder.encode(remark,"UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	private static void getTotalCostMX(XSSFSheet sheet, Element FormData) throws UnsupportedEncodingException{
		
		startRow = 11;
		XSSFRow row = sheet.getRow(startRow);
		while(startRow<20){
			row = sheet.getRow(startRow);
			if(row != null){
				XSSFCell cell = row.getCell(0);
				if(cell != null){
					if(cell.getStringCellValue().equals("成本总金额明细")){
						break;
					}else{
						startRow++;
					}
				}
			}
		}
		
		if(startRow<20){
			startRow+=3;
		}
		System.out.println("成本总金额明细startRow="+startRow);
		int[] cols = new int[] { 7, 9 };
		row = sheet.getRow(startRow-1);
		XSSFCell cell = row.getCell(5);
		if(cell != null && cell.getRichStringCellValue().toString().equals("价格")){//TODO Price
			cols = new int[] { 5, 6 };
		}
		
		String cValue = "";
		row = sheet.getRow(startRow);
		while(row != null ){
			cell = row.getCell(1);
			if(cell != null){
//				System.out.println(row.getCell(0).getRawValue() + ";"+row.getCell(1).getRichStringCellValue()+";"+row.getCell(2).getRawValue()
//						+";"+row.getCell(3).getRawValue()+";"+row.getCell(4).getRawValue()+";"+row.getCell(5).getRawValue()
//						+";"+row.getCell(6).getRawValue());
				if(cell.getRichStringCellValue().toString().equals("合计")) {
					cValue = row.getCell(2).getRawValue();
					stations[0] = cValue==null? "":cValue;

					cValue = row.getCell(3).getRawValue();
					stations[1] = cValue==null? "":cValue;

					cValue = row.getCell(4).getRawValue();
					stations[2] = cValue==null? "":cValue;

					if(cols[0]==7) {
						cValue = row.getCell(5).getRawValue();
						stations[3] = cValue==null? "":cValue;

						cValue = row.getCell(6).getRawValue();
						stations[4] = cValue==null? "":cValue;
					}
					
					break;
				}
				
				Element home2 = FormData.addElement("Home2");
				home2.addElement("RelationRowGuid").addText(String.valueOf(stepNo++));
				home2.addElement("RowPrimaryKeys");
				
				cValue = row.getCell(0).getRawValue();
				cValue = cValue==null?"":cValue;
				home2.addElement("SerialNo").addText(cValue);
				
				cValue = cell.getRichStringCellValue().toString();
				cValue = cValue==null?"":cValue;
				home2.addElement("WorkStationName").addText(URLEncoder.encode(cValue,"UTF-8"));
				
				cValue = row.getCell(2).getRawValue();
				cValue = cValue==null?"":cValue;
				home2.addElement("RobotSystem").addText(URLEncoder.encode(cValue,"UTF-8"));
				
				cValue = row.getCell(3).getRawValue();
				cValue = cValue==null?"":cValue;
				home2.addElement("Positioner").addText(URLEncoder.encode(cValue,"UTF-8"));
				
				cValue = row.getCell(4).getRawValue();
				cValue = cValue==null?"":cValue;
				home2.addElement("Fixture").addText(URLEncoder.encode(cValue,"UTF-8"));

//				cValue = row.getCell(5).getRawValue();
//				cValue = cValue==null?"":cValue;
//				home2.addElement("Price").addText(URLEncoder.encode(cValue,"UTF-8"));
				cValue = getNum(row.getCell(cols[0]));
				home2.addElement("Price").addText(URLEncoder.encode(cValue,"UTF-8"));
				
				cValue = row.getCell(cols[1]).getStringCellValue();
				cValue = cValue==null?"":cValue;
				home2.addElement("Remark").addText(URLEncoder.encode(cValue,"UTF-8"));
				
				row = sheet.getRow(++startRow);
				
			}else{
				break;
			}
		}
	}
	
	private static void getLabourCostMX(XSSFSheet sheet, Element FormData) throws UnsupportedEncodingException{
		
		startRow+= 2;
		int rowCount = sheet.getLastRowNum();
		XSSFRow row = sheet.getRow(startRow);
		while(startRow<rowCount){
			row = sheet.getRow(startRow);
			if(row != null){
				XSSFCell cell = row.getCell(0);
				if(cell != null){
					if(cell.getStringCellValue().equals("人工成本明细")){
						break;
					}else{
						startRow++;
					}
				}
			}
		}
		
		startRow+=2;
		System.out.println("人工成本明细startRow="+startRow);
		
		String cValue = "";
		row = sheet.getRow(startRow);
		while(row != null ){
			XSSFCell cell = row.getCell(1);
			if(cell != null && !cell.getRichStringCellValue().toString().equals("合计")){
//				System.out.println(row.getCell(0).getRawValue() + ";"+row.getCell(1).getRichStringCellValue()+";"+row.getCell(2).getRawValue()
//						+";"+row.getCell(3).getRawValue()+";"+row.getCell(4).getRawValue()+";"+row.getCell(5).getRawValue()+";"
//						+row.getCell(6).getRawValue());
				
				Element home3 = FormData.addElement("Home3");
				home3.addElement("RelationRowGuid").addText(String.valueOf(stepNo++));
				home3.addElement("RowPrimaryKeys");
				
				cValue = row.getCell(0).getRawValue();
				cValue = cValue==null?"":cValue;
				home3.addElement("SerialNo").addText(cValue);
				
				cValue = cell.getRichStringCellValue().toString();
				cValue = cValue==null?"":cValue;
				home3.addElement("WorkStationName").addText(URLEncoder.encode(cValue,"UTF-8"));
				
				cValue = row.getCell(2).getRawValue();
				cValue = cValue==null?"":cValue;
				home3.addElement("DesignFee").addText(URLEncoder.encode(cValue,"UTF-8"));
				
				cValue = row.getCell(3).getRawValue();
				cValue = cValue==null?"":cValue;
				home3.addElement("EngineeringFee").addText(URLEncoder.encode(cValue,"UTF-8"));
				
				cValue = row.getCell(4).getRawValue();
				cValue = cValue==null?"":cValue;
				home3.addElement("ElectricFee").addText(URLEncoder.encode(cValue,"UTF-8"));
				
//				cValue = row.getCell(5).getRawValue();
//				cValue = cValue==null?"":cValue;
//				home3.addElement("Subtotal").addText(URLEncoder.encode(cValue,"UTF-8"));
				cValue = getNum(row.getCell(5));
				home3.addElement("Subtotal").addText(URLEncoder.encode(cValue,"UTF-8"));
				
				cValue = row.getCell(6).getStringCellValue();
				cValue = cValue==null?"":cValue;
				home3.addElement("Remark").addText(URLEncoder.encode(cValue,"UTF-8"));
				
				row = sheet.getRow(++startRow);
				
			}else{
				break;
			}
		}
	}
	
	private static void getWorkStation(XSSFSheet sheet, Element FormData) throws UnsupportedEncodingException{
		
		NumberFormat nf = NumberFormat.getNumberInstance();
		String cValue = "";
		String WorkStationName = "";
		String modelName = "";
		boolean isFind = false;
		int rowCount = sheet.getLastRowNum()-1;
		System.out.println(sheet.getSheetName()+"rowCount="+rowCount);
		XSSFRow row = null;
		XSSFCell cell = null;
		row = sheet.getRow(0);
		if(row != null){
			cell = row.getCell(2);
			if(cell != null){
				WorkStationName = cell.getStringCellValue();
			}
		}
		for(int ix = 3; ix < rowCount; ix++){
			row = sheet.getRow(ix);
			if(row != null){
				
				cell = row.getCell(0);
				if(cell == null){
					break;
				}
				
				switch (cell.getCellType()) {
				case Cell.CELL_TYPE_NUMERIC:
					cValue = String.valueOf(nf.format(cell.getNumericCellValue()));
					break;
				case Cell.CELL_TYPE_STRING:
					cValue = cell.getStringCellValue();	
					break;
				case Cell.CELL_TYPE_FORMULA:
					cValue = String.valueOf(nf.format(cell.getNumericCellValue()));
					break;	
				case Cell.CELL_TYPE_BLANK:
					cValue = "";	
					return;
				default:
					cValue = "";	
					break;
				}
				if(cValue.equals("")){//lidy20190624序号为空即停止
					break;
				}
//				System.out.println(sheet.getSheetName()+">"+cValue+";"+cell.getCellType());
				
				Element home4 = FormData.addElement("Home4");
				home4.addElement("RelationRowGuid").addText(String.valueOf(stepNo++));
				home4.addElement("RowPrimaryKeys");
				home4.addElement("WorkStationName").addText(URLEncoder.encode(WorkStationName,"UTF-8"));
				
				cValue = cValue==null?"":cValue;
				home4.addElement("SerialNo").addText(URLEncoder.encode(cValue,"UTF-8"));
				
				cValue = row.getCell(1).getRichStringCellValue().toString();
				cValue = cValue==null?"":cValue;
				home4.addElement("Name").addText(URLEncoder.encode(cValue,"UTF-8"));
				isFind =  cValue.equals("机器人本体");
				
				modelName = row.getCell(2).getRichStringCellValue().toString();
				modelName = modelName==null?"":modelName;
				home4.addElement("Model").addText(URLEncoder.encode(modelName,"UTF-8"));
				
				XSSFCell countCell = row.getCell(3);
				if (countCell == null) {
				    cValue = "";
				} else if (countCell.getCellType()==0) {
				    double numericValue = countCell.getNumericCellValue();
				    // 格式化为两位小数，避免科学计数法
				    System.out.println("numericValue==="+numericValue);
				    cValue = String.format("%.2f", numericValue);
				} else {
				    cValue = countCell.getStringCellValue();
				}
				cValue = cValue == null ? "" : cValue;

				System.out.println("cValue=="+cValue);
				
				home4.addElement("Count").addText(URLEncoder.encode(cValue, "UTF-8"));
				
				
				
				
				if( isFind ){
					if(jqrbt.get(modelName) != null){
						jqrbt.put(modelName,jqrbt.get(modelName)+ parseToInt(cValue));
					}else{
						jqrbt.put(modelName, parseToInt(cValue));
					}
				}
				
				cValue = row.getCell(4)==null?"":row.getCell(4).getStringCellValue();
				cValue = cValue==null?"":cValue;
				home4.addElement("Unit").addText(URLEncoder.encode(cValue,"UTF-8"));
				
				cValue = row.getCell(5)==null?"":row.getCell(5).getRawValue();
				cValue = cValue==null?"":cValue;
				home4.addElement("UnitPrice").addText(URLEncoder.encode(cValue,"UTF-8"));
				
				cValue = row.getCell(6)==null?"":row.getCell(6).getRawValue();
				cValue = cValue==null?"":cValue;
				home4.addElement("DesignFee").addText(URLEncoder.encode(cValue,"UTF-8"));

				cValue = row.getCell(7)==null?"":row.getCell(7).getRawValue();
				cValue = cValue==null?"":cValue;
				home4.addElement("TotalPrice").addText(URLEncoder.encode(cValue,"UTF-8"));

//				System.out.println(sheet.getSheetName()+">"+row.getRowNum()+">"+row.getLastCellNum());
//				System.out.println("cell:"+row.getCell(8));
				cValue = row.getCell(8)==null?"":row.getCell(8).getStringCellValue();
				cValue = cValue==null?"":cValue;
				home4.addElement("Brand").addText(URLEncoder.encode(cValue,"UTF-8"));
				
				cValue = row.getCell(9)==null?"":row.getCell(9).getStringCellValue();
				cValue = cValue==null?"":cValue;
				home4.addElement("Remark").addText(URLEncoder.encode(cValue,"UTF-8"));
				
			}
		}
		
	}
	
	/*
	 * 判断是否为整数
	 * 
	 * @param str 传入的字符串
	 * 
	 * @return 是整数返回true,否则返回false
	 */

	private static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}
	private static TCComponentItemRevision getItemRevisionFromItem(TCComponentItem item, String rev) throws TCException {
		if (item != null) {
//			System.out.println("rev-----" + rev);
			AIFComponentContext[] contexts = item.getChildren("revision_list");
			if (contexts != null && contexts.length > 0) {
				for (int i = 0; i < contexts.length; i++) {
					InterfaceAIFComponent component = contexts[i].getComponent();
					if (component instanceof TCComponentItemRevision) {
						TCComponentItemRevision revision = (TCComponentItemRevision) component;
						if (revision.getProperty("item_revision_id").equals(rev)) {
							return (TCComponentItemRevision) revision;
						}
					}
				}
			}
		}
		return null;
	}
	private static String getNum(XSSFCell cell) {
		String cValue = "";
		int type = cell.getCellType();
//		System.out.println("PriceCell:"+type);
		if(type==XSSFCell.CELL_TYPE_FORMULA || type==XSSFCell.CELL_TYPE_BLANK) {
			cValue = df.format(cell.getNumericCellValue());
			cValue = cValue.equals(".00") ? "":cValue;
		}else {
			cValue = cell.getRawValue();
			cValue = cValue==null?"":cValue;
		}
		return cValue;
	}
	
	
	public static int parseToInt(String str) {
	    if (str == null || str.trim().isEmpty()) {
	        return 0;
	    }
	    try {
	        return (int) Double.parseDouble(str.trim());
	    } catch (NumberFormatException e) {
	       return 0;
	    }
	}
}
