public with sharing class SWOController {

	public SWO__c swo {get; set;}

	public String swoid {get; set;}
	public String accId {get; set;}
	public String conId {get; set;}
	public List<EmailInfo> mailList {get; set;}

	public String baseUrl {get; set;}
	public String type {get; set;}
	public String caseId {get; set;}

	public String name {get; set;}

	public List<Quotes_item__c> qiList {get; set;}

	public List<RepairPart__c> rpList {get; set;}

	public List<Attachment> attachmentList {get; set;}

	public List<diagnosisInfo> diagnosisList {get; set;} 

	public String errorMessageInfo{get;set;}

	public String assignedUser{get;set;}

	public Integer lineCount{get; set;}
	//RepairPart 自开发页面保存返回接收
	public String repairId{get;set;}
	//RepairPart 自开发页面保存返回后查询更新
	public RepairPart__c repairPart{get;set;}

	private String SwoStatus;
    public String staticResource { get; private set; }// 20220313 PI改造 by Chen Yanan
    public String contactstaticResource { get; private set; }// 20220313 PI改造 by Chen Yanan
    public String contactAWSDataId { get; private set; }// 20220313 PI改造 by Chen Yanan
    public Boolean isNew { get; set; }// 20220313 PI改造 by Chen Yanan
	//ASSIGNEDTO__c
	public SWOController() {
		
	}

	public SWOController(ApexPages.StandardController stdController) {
		isNew = true;
		swoid = System.currentPageReference().getParameters().get('id');
		caseId = System.currentPageReference().getParameters().get('caseId');
		accId = System.currentPageReference().getParameters().get('accId');
		conId = System.currentPageReference().getParameters().get('conId');
		type = System.currentPageReference().getParameters().get('type');
        staticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('SWO__c'));// 20220313 PI改造 by Chen Yanan
        contactstaticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('Contact'));// 20220313 PI改造 by Chen Yanan
	}

	public void init() {

		lineCount = 0;
		//获取初始URL
		baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
		String path = URL.getCurrentRequestUrl().getPath();
		if (path.indexOf('/apex') > 0) {
			baseUrl += path.substring(0, path.indexOf('/apex'));
		} else if (path.indexOf('production/') > 0) {
			baseUrl += '/production';
		}
		//初始化全局变量
		swo = new SWO__c();
		mailList = new List<EmailInfo>();
		if(String.isBlank((type))){
			type = 'Product';
		}
		//如果ID不为空初始化SWO和相关列表
		User_FaultInfo__c ca = new User_FaultInfo__c();
		List<SWO__c> temp = new List<SWO__c>();
		if (caseId != null) {
			// ca = [select id, NUMBER__c,COMPANY__c,CONTACT__c,SUBJECT__c from User_FaultInfo__c where id = : caseId];
			ca = [select id, NUMBER__c,COMPANY__c,CONTACT__c,SUBJECT__c, CONTACT__r.AWS_Data_Id__c, CONTACT__r.Name, CONTACT__r.Email from User_FaultInfo__c where id = : caseId];// 20220313 PI改造 by Chen Yanan
			temp = [select id from SWO__c where CASE_NUMBER__c = :caseId];
			contactAWSDataId = String.isNotBlank(ca.CONTACT__r.AWS_Data_Id__c)?ca.CONTACT__r.AWS_Data_Id__c:'';
		}
		System.debug('ca' + ca.NUMBER__c);
		System.debug('temp' + temp.size());
		if (swoid != null) {
			isNew = false;// 20220313 PI改造 by Chen Yanan
			//初始化SWO
			Schema.DescribeSobjectResult d_swo = SWO__c.sObjectType.getDescribe();
			Map<String, Schema.SObjectField> d_swo_map = d_swo.fields.getMap();
			String soql_swo = 'select ';
			String fields_odr = '';
			for (String field : d_swo_map.keySet()) {
				if (fields_odr.length() > 0) {
					fields_odr += ', ';
				}
				fields_odr += field;
			}
			// soql_swo += fields_odr;
			soql_swo += fields_odr + ', CONTACT__r.AWS_Data_Id__c, CONTACT__r.Name, CONTACT__r.Email ';// 20220313 PI改造 by Chen Yanan
			soql_swo += ' from SWO__c where Id = \'' + swoid + '\'';
			System.debug('soql_swo: ' + soql_swo);// 20220313 PI改造 by Chen Yanan
			List<SWO__c> swoList = Database.query(soql_swo);
			System.debug('swoList: ' + swoList);// 20220313 PI改造 by Chen Yanan
			if (swoList.size() > 0) {
				swo = swoList[0];
				contactAWSDataId = String.isNotBlank(swo.CONTACT__r.AWS_Data_Id__c)?swo.CONTACT__r.AWS_Data_Id__c:'';
			}
			//初始化记录SWO 原始ASSIGNED TO，保存时判断用户是否变更，如果变更给用户发送邮件
			assignedUser = swo.ASSIGNEDTO__c;
			//初始化Mail Merge
			List<String> mailIdList = new List<String>();

			List<Attachment> attList = new List<Attachment>();
			Map<String, List<Attachment>> attMap = new Map<String, List<Attachment>>();

			Map<String, Mail_Merge__c> mailMap = new Map<String, Mail_Merge__c>([select id, FROM__c, ccName__c, SUBJECT__c, MESSAGE__c, DATE__c, toName__c, EMAIL_SENT__c from Mail_Merge__c where SWO__c = :swoid order by id]);
			//mailMap = [select id,FROM__c,ccName__c,SUBJECT__c,MESSAGE__c from Mail_Merge__c where SWO__c = :id order by id];

			if (mailMap != null) {
				mailIdList.addAll(mailMap.keySet());

				attList =  [select id, Name, ParentId from Attachment where ParentId in :mailIdList order by ParentId, id];
				if (attList.size() > 0) {
					for (Attachment att : attList) {
						if (attMap.containsKey(att.ParentId)) {
							attMap.get(att.ParentId).add(att);
						} else {
							List<Attachment> a = new List<Attachment>();
							a.add(att);
							attMap.put(att.ParentId, a);
						}
					}
				}

				for (String id : mailMap.keySet()) {
					if (attMap.containsKey(id)) {
						mailList.add(new EmailInfo(mailMap.get(id), attMap.get(id)));
					} else {
						mailList.add(new EmailInfo(mailMap.get(id), null));
					}
				}
			}

			//初始化Quote

			Map<String, Quotes__c> quoMap = new Map<String, Quotes__c>( [select id from Quotes__c where SWO__c = :swoid order by id]);
			if (quoMap.size() > 0) {
				qiList = [select id, QUOTE__r.id, QUOTE__r.Name, QUOTE__r.STATUS__c, QuotesItemProduct__c, PART_NUMBERNew__c, QUANTITY__c, CURRENCY__c, AMOUNT__c,QUOTE__r.InvalidData__c from Quotes_item__c where QUOTE__r.InvalidData__c = false And QUOTE__c in : quoMap.keySet() order by QUOTE__c, id];
			}

			//初始化rpList
			rpList = new List<RepairPart__c>();
			rpList = [select Id, Name, Product__c, DescriptionNew__c, PART_NUMBERNew__c, INST_SERIAL__c, QUANTITY__c, DEFECT_PART_NUMBER__c, DEFECT_SERIAL_NUMBER__c, ANI_DEFECT_CATEGORY__c, HOURS__c, LOCATION__c, BILL_AT_0_VALUE__c, ECN__c, QTY_PICKED__c,
			Product__r.Description,Product__r.Product_ECCode__c,Product__r.ProductCode from RepairPart__c where SWO_ID__c = :swoid order by Id];
			//初始化附件
			attachmentList = [select Id, Name, CreatedDate, BodyLength from Attachment where ParentId = :swoid];

			//初始化diagnosis
			List<Diagnosis_Part__c> diList = new List<Diagnosis_Part__c>();

			diList = [select Id,SWO__c,DELIVERED__c,DESCRIPTION__c,HOLD_REASON__c,INST_SERIAL__c,PART_NUMBER__c,QUANTITY__c,REMARK__c,RETURN_DATE__c,RETURNED__c,STATUS__c,Product__c,ITEM__c,DeliveredDate__c,
			Product__r.Description,Product__r.Product_ECCode__c,Product__r.ProductCode from Diagnosis_Part__c where SWO__c = :swoid];
			if(diList.size() > 0){
				diagnosisList = new List<diagnosisInfo>();
				for(Diagnosis_Part__c di : diList){
					diagnosisList.add(new diagnosisInfo(di,lineCount));
					lineCount++;
				}
			}
		} else {
			//没有swoId的初始化内容
			swo = new SWO__c();
			if(caseId != null){
				swo.COMPANY__c = ca.COMPANY__c;
				swo.CONTACT__c = ca.CONTACT__c;
				swo.Name = ca.NUMBER__c + '-' + (temp.size() + 1);
				swo.CASE_NUMBER__c = caseId;
				swo.SUBJECT__c = ca.SUBJECT__c;
			}
			if(accId != null){
				swo.COMPANY__c = accId;
			}
			if(conId != null){
				swo.CONTACT__c = conId;
			}
			swo.SWO_STATUS__c = 'Not Started';
			System.debug('SWO: ' + swo);
		}
		SwoStatus = swo.SWO_STATUS__c;
	}

	/**
	 * 保存方法
	 * @return [description]
	 */
	public PageReference save() {
		System.debug('save');
		//errorMessage = '';
		
		//当SWO Status 改变为Quotation for approval时,此时间点自动抓取填充此处；
		if(mustData() == false){
			return null;
		}
		//ASSIGNED_TO_TECHNICIAN_DATE__c
		/*if(swo.SWO_STATUS__c == 'Delivered to Technician'){
			swo.ASSIGNED_TO_TECHNICIAN_DATE__c = Datetime.now();
		}*/
		errorMessageInfo = '';
		//Days-in-house 由 instruments ship date装运时间 与instrument receive date签收时间 计算
		String dateTimeErrorMessage = '';
		/*Boolean dateJudge = true;*/
		if(swo.INSTRUMENT_RECEIVE_DATE__c != null && swo.INSTRUMENT_SHIP_DATE__c != null){
			swo.DAYS_IN_HOUSE__c = getTimeLongStr(swo.INSTRUMENT_SHIP_DATE__c,swo.INSTRUMENT_RECEIVE_DATE__c);
			/*if(swo.INSTRUMENT_SHIP_DATE__c>swo.INSTRUMENT_RECEIVE_DATE__c){
				swo.DAYS_IN_HOUSE__c = getTimeLongStr(swo.INSTRUMENT_SHIP_DATE__c,swo.INSTRUMENT_RECEIVE_DATE__c);
			}else{
				errorMessageInfo += 'DAYS IN HOUSE 开始时间大于结束时间;-';
				dateJudge = false;
			}*/
		}
		//Diagnosis time 由diagnosis end 与diagnosis start计算
		if (swo.DIAGNOSIS_START__c!=null && swo.DIAGNOSIS_END__c!=null) {
			swo.DIAGNOSIS_TIME__c = getTimeLongStr(swo.DIAGNOSIS_START__c,swo.DIAGNOSIS_END__c);
			/*if(swo.DIAGNOSIS_START__c < swo.DIAGNOSIS_END__c){
				swo.DIAGNOSIS_TIME__c = getTimeLongStr(swo.DIAGNOSIS_START__c,swo.DIAGNOSIS_END__c);
			}else{
				errorMessageInfo += 'DIAGNOSIS TIME 开始时间大于结束时间;-';
				dateJudge = false;
			}*/
		}
		//Time awaiting PO由PO received date 与quotation send 计算
		if (swo.PO_RECEIVE_DATE__c != null && swo.Quotation_send__c!=null) {
			swo.TIME_AWAITING_PO__c = getTimeLongStr(swo.PO_RECEIVE_DATE__c,swo.Quotation_send__c);
			/*if(swo.PO_RECEIVE_DATE__c < swo.Quotation_send__c){
				swo.TIME_AWAITING_PO__c = getTimeLongStr(swo.PO_RECEIVE_DATE__c,swo.Quotation_send__c);
			} else {
				errorMessageInfo += 'PO received date 必须小于 quotation send;-';
				dateJudge = false;
			}*/
		}
		//REPAIR_TIME__c
		if(swo.REPAIR_START__c!=null && swo.REPAIR_END__c!=null){
			swo.REPAIR_TIME__c = getTimeLongStr(swo.REPAIR_START__c,swo.REPAIR_END__c);
			/*if(swo.REPAIR_START__c < swo.REPAIR_END__c){
				swo.REPAIR_TIME__c = getTimeLongStr(swo.REPAIR_START__c,swo.REPAIR_END__c);
			}else{
				errorMessageInfo += 'REPAIR TIME 开始时间大于结束时间;-';
				dateJudge = false;
			}*/
		}
		//Calibration time由calibration end 与calibration start计算
		if(swo.CALIBRATION_START__c != null && swo.CALIBRATION_END__c != null){
			//swo.CALIBRATION_TIME__c = swo.CALIBRATION_END__c - CALIBRATION_START__c;
			swo.CALIBRATION_TIME__c = getTimeLongStr(swo.CALIBRATION_START__c,swo.CALIBRATION_END__c);
			/*if(swo.CALIBRATION_START__c < swo.CALIBRATION_END__c){
				swo.CALIBRATION_TIME__c = getTimeLongStr(swo.CALIBRATION_START__c,swo.CALIBRATION_END__c);
			}else{
				errorMessageInfo += 'CALIBRATION TIME 开始时间大于结束时间;-';
				dateJudge = false;
			}*/
		}
		//FQC time 由FQC end 与FQC start计算
		if (swo.FQC_START__c!=null && swo.FQC_end__c!=null) {
			//swo.FQC_TIME__c = swo.FQC_end__c - swo.FQC_START__c;
			swo.FQC_TIME__c = getTimeLongStr(swo.FQC_START__c,swo.FQC_end__c);
			/*if(swo.FQC_START__c < swo.FQC_end__c){
				swo.FQC_TIME__c = getTimeLongStr(swo.FQC_START__c,swo.FQC_end__c);
			}else{
				errorMessageInfo += 'FQC TIME 开始时间大于结束时间;-';
				dateJudge = false;
			}*/
		}
		/*if(!dateJudge){
			return null;
		}*/
		//
		if(swo.Repair_DateTime__c!=null && swo.DELIVERED_TO_SERVICE__c!=null){
			swo.TIME_IN_QUEUE__c = getTimeLongStr(swo.Repair_DateTime__c,swo.DELIVERED_TO_SERVICE__c);
		}
		
		if(swo.SWO_STATUS__c != SwoStatus){
			// if (swo.SWO_STATUS__c == 'Closed') {
			// 	SWOSTATUS_Closed_AddAttachment();//SWOSTATUS_Closed_AddAttachment
			// }
		}
		System.debug('swo save:' + swo);		// Update By Yanan
		if (swoid == null) {
			swo.CASE_NUMBER__c = caseId;
			insert swo;
			swoid = swo.id;
			//ASSIGNED TO 字段变更，给变更后的用户发邮件
			/*if(swo.ASSIGNEDTO__c!=null && swo.ASSIGNEDTO__c!=assignedUser){
				assignedUser = swo.ASSIGNEDTO__c;
				sendEmail(swo.ASSIGNEDTO__c);
			}*/
			// PageReference ref = new Pagereference('/apex/SWOPageRead?id=' + swo.Id +'&type='+type);
			// ref.setRedirect(true);
			// return ref;
		} else {
			//ASSIGNED TO 字段变更，给变更后的用户发邮件
			/*if(swo.ASSIGNEDTO__c!=null && swo.ASSIGNEDTO__c!=assignedUser){
				assignedUser = swo.ASSIGNEDTO__c;
				sendEmail(swo.ASSIGNEDTO__c);
			}*/
			//LATE REASON 添加逻辑：当INSTRUMENT SHIP DATE 晚于ESTIMATED PROMISE DATE时，此项必填。
			update swo;
		}

		if (String.isNotBlank(swo.CASE_NUMBER__c) && (swo.SWO_STATUS__c == 'Close cancel' || swo.SWO_STATUS__c == 'Closed' || swo.SWO_STATUS__c == 'Close Denied')) {
			

			User_FaultInfo__c updateUserFaultInfo = new User_FaultInfo__c();
			updateUserFaultInfo.Id = swo.CASE_NUMBER__c;
			updateUserFaultInfo.STATUS__c = 'Closed';

			update updateUserFaultInfo;

		}

		List<Diagnosis_Part__c> deleteList = new List<Diagnosis_Part__c>();
		// List<Diagnosis_Part__c> insertList = new List<Diagnosis_Part__c>();
		// deleteList = [select Id from Diagnosis_Part__c where SWO__c = :swoid];
		// if(deleteList.size() > 0) delete deleteList;
		// if(diagnosisList != null && diagnosisList.size() > 0){
		// 	for(diagnosisInfo dia : diagnosisList){
		// 		Diagnosis_Part__c dipa = dia.di.clone();
		// 		if(dipa.ITEM__c != null && dipa.Product__c != null){
		// 			if(dipa.SWO__c == null){
		// 				dipa.SWO__c = swoid;
		// 			}
		// 			dipa.id = null;
		// 			insertList.add(dipa);
		// 		}
		// 	}
		// }
		// if(insertList.size() > 0 ) insert insertList;

		PageReference ref = new Pagereference('/apex/SWOPageRead?id=' + swo.Id +'&type='+type);
			ref.setRedirect(true);
			return ref;
	}
	/**
	*数据验证
	**/
	public Boolean mustData(){
		errorMessageInfo = '';
		Boolean temp = true;
		if(swo.OFFICE__c == null){
			System.debug('swo.OFFICE__c:'+swo.OFFICE__c);
			swo.OFFICE__c.addError(errorMessageInfo('OFFICE'));
			//errorMessageInfo += 'OFFICE,';
			temp = false;
		}
		if(swo.SWO_PRIORITY__c == null){
			swo.SWO_PRIORITY__c.addError(errorMessageInfo('SWO PRIORITY'));
			temp = false;
		}
		if(swo.SWO_STATUS__c == null){
			swo.SWO_STATUS__c.addError(errorMessageInfo('SWO STATUS'));
			//errorMessageInfo += 'SWO STATUS,';
			temp = false;
		}
		/*if(swo.SWO_STAGE__c == null){
			//errorMessageInfo += 'SWO STAGE,';
			swo.SWO_STAGE__c.addError(errorMessageInfo('SWO STAGE'));
			temp = false;
		}*/
		if(swo.TYPE__c == null){
			//errorMessageInfo += 'TYPE,';
			swo.TYPE__c.addError(errorMessageInfo('TYPE'));
			temp = false;
		}
		if(swo.ASSIGNEDTO__c == null){
			//errorMessageInfo += 'ASSIGNED TO,';
			swo.ASSIGNEDTO__c.addError(errorMessageInfo('ASSIGNED TO'));
			temp = false;
		}
		if(swo.DEPARTMENT__c == null){
			//errorMessageInfo += 'DEPARTMENT,';
			swo.DEPARTMENT__c.addError(errorMessageInfo('DEPARTMENT'));
			temp = false;
		}
		if(swo.REASON__c == null){
			//errorMessageInfo += 'REASON,';
			swo.REASON__c.addError(errorMessageInfo('REASON'));
			temp = false;
		}
		if(swo.PRODUCT_TYPE__c == null){
			//errorMessageInfo += 'PRODUCT TYPE';
			swo.PRODUCT_TYPE__c.addError(errorMessageInfo('PRODUCT TYPE'));
			temp = false;
		}
		if(swo.ITEM__c == null){
			//errorMessageInfo += 'ITEM,';
			swo.ITEM__c.addError(errorMessageInfo('ITEM'));
			temp = false;
		}
		if(swo.QUANTITY__c == null){
			//errorMessageInfo += 'QUANTITY,';
			swo.QUANTITY__c.addError(errorMessageInfo('QUANTITY'));
			temp = false;
		}
		/*if (swo.ESTIMATED_MATERIAL_COST__c == null) {
			swo.ESTIMATED_MATERIAL_COST__c.addError(errorMessageInfo('ESTIMATED MATERIAL (COST)'));
			temp = false;
		}*/
		/*if (swo.ESTIMATED_LABOUR_HOURS__c == null) {
			swo.ESTIMATED_LABOUR_HOURS__c.addError(errorMessageInfo('ESTIMATED LABOUR (HOURS)'));
			temp = false;
		}*/
		/*if (swo.ESTIMATED_EXPENSES_COSTS__c == null) {
			swo.ESTIMATED_EXPENSES_COSTS__c.addError(errorMessageInfo('ESTIMATED EXPENSES (COSTS)'));
			temp = false;
		}*/
 		if ((swo.INSTRUMENT_SHIP_DATE__c > swo.ESTIMATED_PROMISE_DATE__c) && swo.LATE_REASON__c == null) {
			//errorMessageInfo = 'INSTRUMENT SHIP DATE 时间晚于 ESTIMATED PROMISE DATE 时间 LATE REASON 必填。';
			//errorMessageInfo += 'INSTRUMENT SHIP DATE 时间晚于 ESTIMATED PROMISE DATE 时间 LATE REASON 必填。';
			swo.LATE_REASON__c.addError(errorMessageInfo('LATE REASON'));
 		}
		if(!temp){
			return temp;
		}

		if(swo.REPEAT_REPAIR__c && swo.REPEAT_REPAIR_ORIGINAL_NOTES__c == null){
			//errorMessageInfo += 'REPEAT REPAIR Check REPEAT REPAIR ORIGINAL NOTES 文本框必填';
			//System.debug('errorMessageInfo:'+errorMessageInfo);
			swo.REPEAT_REPAIR_ORIGINAL_NOTES__c.addError(errorMessageInfo('REPEAT REPAIR Check REPEAT REPAIR ORIGINAL NOTES'));
			return false;
		}

		if(swo.INSTRUMENT_RECEIVE_DATE__c == null && swo.ASSIGNED_TO_TECHNICIAN_DATE__c !=null){
			//errorMessageInfo += 'ASSIGNED TO TECHNICIAN DATE 有值 INSTRUMENT RECEIVE DATE 不可为空，';
			swo.INSTRUMENT_RECEIVE_DATE__c.addError(errorMessageInfo('ASSIGNED TO TECHNICIAN DATE has a value INSTRUMENT RECEIVE DATE'));
			temp = false;
		}else if((swo.INSTRUMENT_RECEIVE_DATE__c != null && swo.ASSIGNED_TO_TECHNICIAN_DATE__c !=null) && (swo.INSTRUMENT_RECEIVE_DATE__c.getTime() > swo.ASSIGNED_TO_TECHNICIAN_DATE__c.getTime())){
			//errorMessageInfo += 'INSTRUMENT RECEIVE DATE 不可以大于 ASSIGNED TO TECHNICIAN DATE，';
			swo.INSTRUMENT_RECEIVE_DATE__c.addError('INSTRUMENT RECEIVE DATE cannot be greater than ASSIGNED TO TECHNICIAN DATE');
			temp = false;
		}
		if((swo.ASSIGNED_TO_TECHNICIAN_DATE__c!=null && swo.TECHNICIAN_COMPLETION_DATE__c!=null)&&(swo.ASSIGNED_TO_TECHNICIAN_DATE__c.getTime() > swo.TECHNICIAN_COMPLETION_DATE__c.getTime())){
			//errorMessageInfo += 'ASSIGNED TO TECHNICIAN DATE 不可以大于 TECHNICIAN COMPLETION DATE，';
			swo.ASSIGNED_TO_TECHNICIAN_DATE__c.addError('ASSIGNED TO TECHNICIAN DATE cannot be greater than TECHNICIAN COMPLETION DATE');
			temp = false;
		}
		if(!temp){
			return temp;
		}

		if(swo.SWO_STATUS__c == 'Ready to Ship' && swo.PO_RECEIVE_DATE__c == null){
			//errorMessageInfo = '请输入 PO Receive Date';
			swo.PO_RECEIVE_DATE__c.addError(errorMessageInfo('PO Receive Date'));
			return false;
		}

		if(swo.SWO_STATUS__c == 'Closed'){
			if(swo.INSTRUMENT_RECEIVE_DATE__c == null){
				//errorMessageInfo += 'INSTRUMENT RECEIVE DATE,'; 
				swo.INSTRUMENT_RECEIVE_DATE__c.addError(errorMessageInfo('INSTRUMENT RECEIVE DATE'));
				temp = false;
			}
			if(swo.INSTRUMENT_SHIP_DATE__c == null){
				//errorMessageInfo += 'INSTRUMENT SHIP DATE,'; 
				swo.INSTRUMENT_SHIP_DATE__c.addError(errorMessageInfo('INSTRUMENT SHIP DATE'));
				temp = false;
			}
			if(swo.ASSIGNED_TO_TECHNICIAN_DATE__c == null){
				//errorMessageInfo += 'ASSIGNED TO TECHNICIAN DATE,'; 
				swo.ASSIGNED_TO_TECHNICIAN_DATE__c.addError(errorMessageInfo('ASSIGNED TO TECHNICIAN DATE'));
				temp = false;
			}
			if(swo.TECHNICIAN_COMPLETION_DATE__c == null){
				//errorMessageInfo += 'TECHNICIAN COMPLETION DATE,'; 
				swo.TECHNICIAN_COMPLETION_DATE__c.addError(errorMessageInfo('TECHNICIAN COMPLETION DATE'));
				temp = false;
			}
			if(swo.UNIT_POWERS_UP__c == null){
				//errorMessageInfo += 'UNIT POWERS UP?,'; 
				swo.UNIT_POWERS_UP__c.addError(errorMessageInfo('UNIT POWERS UP?'));
				temp = false;
			}
			if(swo.BATTERY_MORE_THAN_3_YRS_OLD__c == null){
				//errorMessageInfo += 'BATTERY MORE THAN 3-YRS OLD?,'; 
				swo.BATTERY_MORE_THAN_3_YRS_OLD__c.addError(errorMessageInfo('BATTERY MORE THAN 3-YRS OLD?'));
				temp = false;
			}
			if(swo.CONFIRMED_RECEIPT_WITH_CUSTOMER__c == null){
				//errorMessageInfo += 'CONFIRMED RECEIPT WITH CUSTOMER?,'; 
				swo.CONFIRMED_RECEIPT_WITH_CUSTOMER__c.addError(errorMessageInfo('CONFIRMED RECEIPT WITH CUSTOMER?'));
				temp = false;
			}
			if(swo.INCOMING_INSPECTION_COMPLETED_BY__c == null){
				//errorMessageInfo += 'INCOMING INSPECTION COMPLETED BY:,'; 
				swo.INCOMING_INSPECTION_COMPLETED_BY__c.addError(errorMessageInfo('INCOMING INSPECTION COMPLETED BY:'));
				temp = false;
			}
			if(swo.CUSTOM_SETUPS_PRESENT__c == null){
				//errorMessageInfo += 'CUSTOM SETUPS PRESENT?,'; 
				swo.CUSTOM_SETUPS_PRESENT__c.addError(errorMessageInfo('CUSTOM SETUPS PRESENT?'));
				temp = false;
			}
			if(swo.CUSTOM_SETUPS_INCLUDED__c == null){
				//errorMessageInfo += 'CUSTOM SETUPS INCLUDED?,'; 
				swo.CUSTOM_SETUPS_INCLUDED__c.addError(errorMessageInfo('CUSTOM SETUPS INCLUDED?'));
				temp = false;
			}
			if(swo.KEYPAD_FUNCTIONS_CORRECTLY__c == null){
				//errorMessageInfo += 'KEYPAD FUNCTIONS CORRECTLY?,'; 
				swo.KEYPAD_FUNCTIONS_CORRECTLY__c.addError(errorMessageInfo('KEYPAD FUNCTIONS CORRECTLY?'));
				temp = false;
			}
			if(swo.OUTGOING_INSPECTION_COMPLETED_BY__c == null){
				//errorMessageInfo += 'OUTGOING INSPECTION COMPLETED BY:,'; 
				swo.OUTGOING_INSPECTION_COMPLETED_BY__c.addError(errorMessageInfo('OUTGOING INSPECTION COMPLETED BY:'));
				temp = false;
			}
			if(swo.SERIAL_MATCHES_SO__c == null){
				//errorMessageInfo += 'SERIAL# MATCHES SO?,'; 
				swo.SERIAL_MATCHES_SO__c.addError(errorMessageInfo('SERIAL# MATCHES SO?'));
				temp = false;
			}
			if(swo.FACTORY_WARRANTY__c == false && swo.SO_NUMBER__c == null && swo.OAI_WARRANTY__c == false){
				//errorMessageInfo += 'SO NUMBER,';
				swo.SO_NUMBER__c.addError(errorMessageInfo('SO NUMBER'));
				temp = false;
			}
		}
		return temp;
	}
	//拼接错误信息
	public String errorMessageInfo(String type) {
        String result = type + ' can not be empty';
        return result;
    }
	/**
	 * 上传附件
	 * @return [description]
	 */
	public PageReference uploadFile() {

		PageReference ref = new Pagereference('/p/attach/NoteAttach?pid=' + swoid + '&retURL=%2Fapex/SWOPage?id=' + swoid);
		ref.setRedirect(true);
		return ref;
	}

	public Pagereference edit(){
		PageReference ref = new Pagereference('/apex/SWOPage?id=' + swo.Id +'&type='+type);
		ref.setRedirect(true);
		return ref;
	}

	public void addDiagnosisInfo(){
		if(diagnosisList == null){
			diagnosisList = new List<diagnosisInfo>();
		}
		diagnosisList.add(new diagnosisInfo(lineCount));
		lineCount++;
	}

	/**
	 * 切换页面方法。
	 */
	public void setMail() {
		type = 'mail';
	}
	public void setFault() {
		type = 'Fault';
	}
	public void setCase() {
		type = 'Case';
	}
	public void setProduct() {
		type = 'Product';
	}

	public void setQuotes() {
		type = 'Quotes';
	}

	public void setRepair() {
		type = 'Repair';
	}

	public void setTracking() {
		type = 'Tracking';
	}
	public void setTechnical() {
		type = 'Technical';
	}

	public void setEstimation() {
		type = 'Estimation';
	}

	public void setGeneral() {
		type = 'General';
	}

	public void setIncoming() {
		type = 'Incoming';
	}

	public void setOutgoing() {
		type = 'Outgoing';
	}

	public void setDiagnosis() {
		type = 'Diagnosis';
	}

	/**
	 * 邮件数据结构
	 */
	public class EmailInfo {

		public Mail_Merge__c mm {get; set; }
		public List<Attachment> attList {get; set; }
		public String haveAtt {get; set;}
		public EmailInfo() {

		}
		public EmailInfo(Mail_Merge__c mm_in, List<Attachment> attList_in) {
			mm = mm_in;
			if (attList_in == null || attList_in.size() == 0) {
				haveAtt = 'No';
				attList = new List<Attachment>();
			} else {
				attList = attList_in;
				haveAtt = 'Yes';
			}
		}

	}

	public class diagnosisInfo{
		public Diagnosis_Part__c di{get; set;}
		public Integer lineNumber {get; set;}

		public diagnosisInfo(Integer line){
			di = new Diagnosis_Part__c();
			lineNumber = line;
		}
		public diagnosisInfo(Diagnosis_Part__c in_di,Integer line){
			di = in_di;
			lineNumber = line;
		}
	}

	//发送邮件
	public void sendEmail(String id){

		if(String.isBlank(id)){
			return;
		}
		User user = [select Name,Email from User where id=:id];
		if(user!=null && String.isNotBlank(user.Email)){
			String subject = 'Service Work Order ~SWO:'+swo.Name;
			String message = 'SWO status Changed to: '+ swo.SWO_STATUS__c+', Please continue to proceed this SWO.'+'\r';
			message += (baseUrl+'/'+swo.Id);
			List<String> ccAddresses = new List<String>();
			List<String> toAddresses = new List<String>();
			Messaging.SingleEmailMessage sendMail = new Messaging.SingleEmailMessage();
			toAddresses.add(user.Email);
	        sendMail.setToAddresses(toAddresses);
	        sendMail.setSubject(subject);
	        sendMail.setPlainTextBody(message);
	        sendMail.setBccSender(false);
	        sendMail.setUseSignature(false);
	        // ccAddresses.add('swo_listen@z-23gt0jbtzuxf7uka2keyfl65gxjqimwuqbl07g9u0govga7hm6.0t-8aptuaq.cs112.apex.sandbox.salesforce.com');
	        ccAddresses.add(System.label.EmailComeBackListen);
	        ccAddresses.add('dai_Prectech@olympus.com.cn');
	        sendMail.setCcAddresses(ccAddresses);
			Messaging.SendEmailResult[] result_list = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { sendMail });
		}

	}
	//repair parts 页面返回调用
	public void repairReturn(){
		if(String.isNotBlank(repairId)){
			/*RepairPart__c repairPart = new RepairPart__c();
			Schema.DescribeSobjectResult repairPart = RepairPart__c.sObjectType.getDescribe();
			Map<String, Schema.SObjectField> repairPart_fields = d_swo.fields.getMap();
			String soql_repair = 'select ';
			String fields = '';
			for (String field : repairPart_fields.keySet()) {
				if (fields.length() > 0) {
					fields += ', ';
				}
				fields += field;
			}
			soql_repair += fields;
			soql_repair += ' from RepairPart__c where SWO_ID__c = \'' + repairId + '\'';
			rpList = Database.query(soql_repair);*/
			System.debug('新建RepairPart 返回');
			rpList = new List<RepairPart__c>();
			rpList = [select Id, Name, Product__c, DescriptionNew__c, PART_NUMBERNew__c, INST_SERIAL__c, QUANTITY__c, DEFECT_PART_NUMBER__c, DEFECT_SERIAL_NUMBER__c, ANI_DEFECT_CATEGORY__c, HOURS__c, LOCATION__c, BILL_AT_0_VALUE__c, ECN__c, QTY_PICKED__c from RepairPart__c where SWO_ID__c = :swoid order by Id];
			return;
		}
	}

	// 计算两个dateTime之间的时间间隔 返回为几天几小时几分钟的字符串
	public String getTimeLongStr(Datetime startTime,Datetime endTime){
		if(startTime>endTime){
			Datetime a = startTime;
			startTime = endTime;
			endTime = a;
		}
		String str = '';
		Decimal timeLong = Decimal.valueOf(endTime.getTime()) - Decimal.valueOf(startTime.getTime());
		Decimal day = 0;
		Decimal hour = 0;
		Decimal second = timeLong/1000;
		//math.round() 四舍五入
		//math.floor() 取到一个小数的整数部分
		Decimal minute = math.round(second/60);
		if(minute >= 60){
			hour = minute/60;
			if(hour >= 24){
				day = hour/24;
				hour = (day-math.floor(day))*24;
				minute = (hour - math.floor(hour))*60;
				minute = math.round(minute);
				hour = math.floor(hour);
				day = math.floor(day);
				str = day+' Day '+hour+' Hour '+minute+' Minute';
			}else{
				minute = (hour-math.floor(hour))*60;
				minute =  math.round(minute);
				hour = math.floor(hour);
				str = hour+' Hour '+math.round(minute)+' Minute';
			}
		}else{
			str = minute+' Minute';
		}
		System.debug(str);
		return str;
	}
	//打开子页面先保存，防止返回SWO页面时数据被刷新
	public void openPageSave(){
		upsert swo;
		return;
	}
	// SWO的状态变成Closed时，创建csv并添加到附件中
	/*public void SWOSTATUS_Closed_AddAttachment() {
		String repairParts = '';
		if ( rpList.size() > 0) {
			for(RepairPart__c repairPart:rpList){

				if (String.isBlank(repairParts)) {
					repairParts = repairPart.Product__r.ProductCode;
				} else {
					repairParts += '/' + repairPart.Product__r.ProductCode;
				}
			}
		}
		repairParts = String.isBlank(repairParts)  ? '\"\"':repairParts.replaceAll('"', '');
		String claim = String.isBlank(swo.CLAIM__c)  ? '\"\"':swo.CLAIM__c.replaceAll('"', '');
        String serial = String.isBlank(swo.SERIAL__c)  ? '\"\"':swo.SERIAL__c.replaceAll('"', '');
        String description = String.isBlank(swo.DESCRIPTION_F__c)?'': swo.DESCRIPTION_F__c.replaceAll('"', '');
        String strblob = '"swo name","factory warranty","product type","claim#","DESCRIPTION","serial #","repair parts","ESTIMATED LABOUR (HOURS)"\n';
        
        strblob += swo.name +',' + swo.FACTORY_WARRANTY__c + ','+swo.PRODUCT_TYPE__c +','+claim+','+description+','+serial+ ','+repairParts+','+swo.ESTIMATED_LABOUR_HOURS__c;

        Attachment tmpAttachment = new Attachment();
        tmpAttachment.Name = swo.name +'出库单.csv';
        tmpAttachment.Body = Blob.valueOf(strblob);
        tmpAttachment.ParentId = swo.Id;
        insert tmpAttachment;
        
    }
    */
}