/**串联问题*/
public with sharing class NFM504Controller {

	public class Tender_element {
		public NFMUtil.Monitoring Monitoring;//请求头
		public Tenders_element[] GeData;//要发送的数据
	}
	public class Tenders_element {
		public String oldProjectId;//要删除招投标的项目Id
		public String oldInfoId;// 要删除招投标的信息Id
		public String newProjectId;// 要保留招投标的项目Id
	}
	public String DTenId;
	public NFM504Controller(String DTenId) {
		this.DTenId = DTenId;
	}

	public NFM504Controller() {

	}
	@future (callout = true)
	public static void sendRequest(String DTenId) {
		Tender_information__c BTenInfo;
		// 删除的招投标
		Tender_information__c DTenInfo = [Select Id, InfoId__c, ProjectId__c, CursorMark__c, Retain_Tender__c From Tender_information__c Where Id = : DTenId];
		if (String.isNotBlank(DTenInfo.Retain_Tender__c)) {
			// 保留的招投标
			BTenInfo = [Select Id, InfoId__c, ProjectId__c, Retain_Tender__c From Tender_information__c Where Id = : DTenInfo.Retain_Tender__c];
		}
		// Monitoringの設定
		Datetime nowDT = Datetime.now();
		String nowStr = nowDT.format('yyyyMMddHHmm');
		Tender_element tenders = new Tender_element();
		tenders.Monitoring = new NFMUtil.Monitoring();
		tenders.Monitoring.Tag                  = 'MSGH';
		tenders.Monitoring.Sender               = 'SFDC';
		tenders.Monitoring.Receiver             = 'QLM';
		tenders.Monitoring.MessageType          = 'NFM504';
		tenders.Monitoring.MessageGroupNumber   = DTenInfo.CursorMark__c;
		tenders.Monitoring.NumberOfRecord       = '2';
		tenders.Monitoring.TransmissionDateTime = nowStr;
		tenders.Monitoring.Text = '';
		BatchIF_Log__c rowData = null;

		//存放报错信息
		BatchIF_Log__c iflog504 = new BatchIF_Log__c();
		iflog504.Type__c = 'NFM504';
		iflog504.RowDataFlg__c = false;
		iflog504.Log__c = ' ';
		iflog504.ErrorLog__c = ' ';
		iflog504.MessageGroupNumber__c = DTenInfo.CursorMark__c;
		// insert iflog504;
		try {
			String token;
			Datetime oldTime;
			// 从转换表中获取token
			BatchIF_Transfer__c token504 = [Select ID, NFM501_Token__c
			                                FROM BatchIF_Transfer__c Where Table__c = 'NFM501Token'];
			token = token504.NFM501_Token__c;
			// 从转换表中获取获取完token的时间
			BatchIF_Transfer__c oldTime504 = [Select ID, NFM501_Gain_End_Time__c
			                                  FROM BatchIF_Transfer__c Where Table__c = 'NFM501GainEndTime'];
			oldTime = oldTime504.NFM501_Gain_End_Time__c;

			// 判断token是否失效（失效条件为30分钟之后），如果失效，重新获取
			Long timeslot;
			Datetime newTime = System.now();
			if (oldTime == null) {
				timeslot = 2800000;
			} else {
				// 当前时间与获取token结束时间的时间差
				timeslot = newTime.getTime() - oldTime.getTime();
			}
			// System.debug('++++1++++' + token + '  : ' + timeslot);
			if (string.isblank(token) || timeslot > 1800000) {
				System.debug('---------1----------');
				NFMUtil.response response = NFMUtil.receiveToken();
				//判断rowdata中数据获取成功与否，如果失败重发三次，如果大于三次则手动操作
				if (String.isBlank(response.responseBody)) {
					// System.debug('response.responseBody:' + response.responseBody);
					iflog504.ErrorLog__c = '504token:' + response.status;
					// rowData.NFM501_Web_Annex_Count__c = 0;
					// if (!Manual_execution502) {
					// NFM501Controller.againSendRequest(iflog502, 'NFM501_Web_Annex_Count__c', rowData);
					// }
					//更新日志数据
					// System.debug('123@@@');
					return;
				}
				token = response.responseBody;
				oldTime = Datetime.now();
				System.debug('---------7----------' + token);
				token504.NFM501_Token__c = token;
				oldTime504.NFM501_Gain_End_Time__c = oldTime;
			}

			tenders.GeData = new List<Tenders_element>();
			Tenders_element tender = new Tenders_element();
			tenders.GeData.add(tender);
			if (String.isNotBlank(DTenInfo.Retain_Tender__c)) {
				tender.newProjectId = BTenInfo.ProjectId__c;
			}
			tender.oldInfoId = DTenInfo.InfoId__c;
			tender.oldProjectId = DTenInfo.ProjectId__c;

			if (tenders.GeData.size() > 0) {
				NFMUtil.Monitoring Monitoring   = new NFMUtil.Monitoring();
				Monitoring.Tag                  = tenders.Monitoring.Tag;
				Monitoring.Sender               = tenders.Monitoring.Sender;
				Monitoring.Receiver             = tenders.Monitoring.Receiver;
				Monitoring.MessageType          = tenders.Monitoring.MessageType;
				Monitoring.MessageGroupNumber   = tenders.Monitoring.MessageGroupNumber;
				Monitoring.NumberOfRecord       = tenders.Monitoring.NumberOfRecord;
				Monitoring.TransmissionDateTime = tenders.Monitoring.TransmissionDateTime;
				Monitoring.Text = '';

				rowData = NFMUtil.makeRowData(Monitoring, 'NFM504', tenders);

				System.debug('---------2----------' + rowData);
				execute(rowData, iflog504, token);
			}
		} catch (Exception ex) {
			iflog504.ErrorLog__c += ex.getMessage() + '\n';
			iflog504.ErrorLog__c += ex.getStackTraceString() + '\n';
		}
		if (rowData != null) {
			upsert rowData;
		}
		System.debug('---------6----------' + rowData);
		upsert iflog504;
		System.debug('---------3----------' + iflog504);
	}
	public static void execute(BatchIF_Log__c rowData, BatchIF_Log__c iflog504, String token) {
		Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
		String rowDataStr = 'text=' + NFMUtil.getRowDataStr(rowData);
		System.debug('---------4----------' + rowDataStr);
		try {
			// 向SPO送信
			NFMUtil.sendTenInfo(token, rowDataStr, NFMUtil.NFM504_ENDPOINT);
			rowData.retry_cnt__c = 0;
		} catch (Exception ex) {
			iflog504.ErrorLog__c += ex.getMessage() + '\n';
			iflog504.ErrorLog__c += ex.getStackTraceString() + '\n';
			NFM501Controller.againSendExceptionRequest(iflog504, 'retry_cnt__c', rowData,
			        '504抛出异常：' + ex.getMessage() + '\n' + ex.getStackTraceString()
			        + '\n' + rowData.ErrorLog__c +
			        '错误次数已经超过自动收信设定的最大次数，请手动收信');
		}
		upsert iflog504;
		System.debug('---------5----------' + iflog504);
		upsert rowData;

	}
}