public with sharing class NFM503Controller implements Queueable {
	public String rowData_id;
	public NFM503Controller(String rowData_id) {
		this.rowData_id = rowData_id;
	}
	public static Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
	public void execute(QueueableContext context) {
		// 通过Rowdata.Id来检索日志中的内容（千里马数据等）
		BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c,
		                          Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c,
		                          Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c,
		                          NFM501Future_Count__c, NFM501_Other_Annex_Count__c,
		                          NFM501_Web_Annex_Count__c from BatchIF_Log__c where Id = :rowData_id];

		//存放报错信息
		BatchIF_Log__c iflog503 = new BatchIF_Log__c();
		iflog503.Type__c = 'NFM501';
		iflog503.RowDataFlg__c = false;
		iflog503.Log__c = ' ';
		iflog503.ErrorLog__c = ' ';
		iflog503.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
		insert iflog503;
		NFM503Controller.OtherAnnexGain(rowData.Id, iflog503.Id);
	}
	@future(callout = true)
	public static void OtherAnnexGain(String rowData_id, String iflog503_id) {
		BatchIF_Log__c rowData = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c,
		                          Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c,
		                          Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c,
		                          NFM501Future_Count__c, NFM501_Other_Annex_Count__c,
		                          NFM501_Web_Annex_Count__c from BatchIF_Log__c
		                          where RowDataFlg__c = true and Id = :rowData_id];
		BatchIF_Log__c iflog503 = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c,
		                           Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c,
		                           Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c,
		                           NFM501Future_Count__c, NFM501_Other_Annex_Count__c,
		                           NFM501_Web_Annex_Count__c from BatchIF_Log__c
		                           where Id = :iflog503_id];
		iflog503.Log__c = iflog503.Log__c == null ? '' : iflog503.Log__c;
		iflog503.ErrorLog__c = iflog503.ErrorLog__c == null ? '' : iflog503.ErrorLog__c;
		rowData.Log__c = rowData.Log__c == null ? '' : rowData.Log__c;
		rowData.ErrorLog__c = rowData.ErrorLog__c == null ? '' : rowData.ErrorLog__c;

		// Savepoint sp = Database.setSavepoint();
		try {
			String token;
			Datetime oldTime;
			// 从转换表中获取token
			BatchIF_Transfer__c token503 = [Select ID, NFM501_Token__c
			                                FROM BatchIF_Transfer__c Where Table__c = 'NFM501Token'];
			token = token503.NFM501_Token__c;
			// 从转换表中获取获取完token的时间
			BatchIF_Transfer__c oldTime503 = [Select ID, NFM501_Gain_End_Time__c
			                                  FROM BatchIF_Transfer__c Where Table__c = 'NFM501GainEndTime'];
			oldTime = oldTime503.NFM501_Gain_End_Time__c;
			// 对日志中的数据进行解析
			String WebUrl = NFMUtil.QLMgetRowDataStr(rowData);
			NFM501Controller.AllData getQLMData503 = (NFM501Controller.AllData)
			        JSON.deserialize(WebUrl, NFM501Controller.AllData.class);
			if (getQLMData503 == null) {
				return;
			}

			// 判断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) {
				NFMUtil.response response = NFMUtil.receiveToken();
				//判断rowdata中数据获取成功与否，如果失败重发三次，如果大于三次则手动操作
				if (String.isBlank(response.responseBody)) {
					System.debug('response.responseBody:' + response.responseBody);
					iflog503.ErrorLog__c = '503token:' + response.status;
					rowData.NFM501_Other_Annex_Count__c = 0;
					NFMUtil.againSendRequest(iflog503, 'NFM501_Other_Annex_Count__c', rowData,
					                         '错误次数已经超过自动收信设定的最大次数，请手动收信');
					System.debug('-------5-------');
					//更新日志数据
					upsert rowData;
					upsert iflog503;
					return;
				}
				token = response.responseBody;
				oldTime = Datetime.now();
				token503.NFM501_Token__c = token;
				oldTime503.NFM501_Gain_End_Time__c = oldTime;
			}
			//关联附件与招投标项目（通过Id）
			//1.读出招投标中的唯一标识（projecId），将全部招投标projectId存入ProjectIdList
			List<String> ProjectIdList = new List<String>();
			for (NFM501Controller.ListItem ProId : getQLMData503.data.list1) {
				ProjectIdList.add(ProId.projectId);
			}
			System.debug('---===ProjectIdList' + ProjectIdList);
			//2.取其对应的
			List<Tender_information__c> TIList =
			    [Select Id, ProjectId__c, InfoType__c, Overstep_12M_infofile__c, File_Surpass_12M__c
			     FROM Tender_information__c
			     Where ProjectId__c in :ProjectIdList];
			System.debug('---===2345TIList' + TIList);
			Map<String, Tender_information__c> TenIdMap = new Map<String, Tender_information__c>();
			for (Tender_information__c Ten : TIList) {
				TenIdMap.put(Ten.ProjectId__c, Ten);
			}
			//3.如果有多个file
			// Map<Id, List<String>> TenFileMap = new Map<Id, List<String>>();
			// for (NFM501Controller.ListItem Fileid : getQLMData503.data.list1) {
			// 	TenFileMap.put(TenIdMap.get(Fileid.projectId), Fileid.InfoFile);
			// }
			// List<Attachment> SelList = [select Id, Name from Attachment where ];
			//循环URL
			List<Attachment> TenOtherAttList = new List<Attachment>();
			List<String> FileList = new List<String>();
			Map <string, Tender_information__c> updateTenderMap = new  map <string, Tender_information__c>();

			for (NFM501Controller.ListItem QLMFileAtt : getQLMData503.data.list1) {
				if (QLMFileAtt.projectId == null) {
					iflog503.ErrorLog__c += 'Error! [' + QLMFileAtt.projectId + ']NotExist. This information is skipped.\n';
					continue;
				}
				if (QLMFileAtt.areaProvince.equals('香港特别行政区')
				        || QLMFileAtt.areaProvince.equals('澳门特别行政区')
				        || QLMFileAtt.areaProvince.equals('台湾省')) {
					iflog503.ErrorLog__c += 'Error! [' + QLMFileAtt.areaProvince +
					                        ']Is 香港特别行政区(澳门特别行政区,台湾省). This information is skipped.\n';
					continue;
				}
				//调用接口3
				for (String singleFile : QLMFileAtt.InfoFile) {
					NFMUtil.response503 response = NFMUtil.getFileData(token, singleFile);
					System.debug('---------' + response.responseBody);
					if (response.responseBody == null) {
						System.debug('response.responseBody:' + response.responseBody);
						iflog503.ErrorLog__c = '503接口调用：' + response.status;
						rowData.NFM501_Other_Annex_Count__c = 0;
						NFMUtil.againSendRequest(iflog503, 'NFM501_Other_Annex_Count__c', rowData,
						                         '错误次数已经超过自动收信设定的最大次数，请手动收信');
						System.debug('-------5-------');
						//更新日志数据
						upsert rowData;
						upsert iflog503;
						update token503;
						update oldTime503;
						return;
					}
					Attachment WebAtt = new Attachment();
					if (response.Name.equals('文件大小超过12M')) {
						id tendID = TenIdMap.get(QLMFileAtt.projectId).Id;
						Tender_information__c tempTender = new Tender_information__c();
						tempTender.id = tendID;
						tempTender.File_Surpass_12M__c = true;
						if (String.isBlank(tempTender.Overstep_12M_infofile__c)) {
							tempTender.Overstep_12M_infofile__c = singleFile;
						} else {
							if (!tempTender.Overstep_12M_infofile__c.contains(singleFile)) {
								// List<String> urlList = singleFile.split(',');
								tempTender.Overstep_12M_infofile__c += singleFile + ',';
							}
						}
						updateTenderMap.put(QLMFileAtt.projectId, tempTender);
					}
					// 将路径存入附件中

					// 使其点击附件，跳转到下载页面，直接下载

					// 获取网页信息转存为附件
					//将其转换为附件
					System.debug('---------' + response.responseBody);
					System.debug('projectId:' + QLMFileAtt.projectId);
					System.debug('ParentId:' + TenIdMap.get(QLMFileAtt.projectId));
					WebAtt.ParentId = TenIdMap.get(QLMFileAtt.projectId).Id;
					WebAtt.Body = response.responseBody;
					WebAtt.Name = TenIdMap.get(QLMFileAtt.projectId).InfoType__c + ':' + response.Name;
					if(!response.Name.equals('文件大小超过12M')){
						TenOtherAttList.add(WebAtt);
					}
					FileList.add(WebAtt.Name);
				}
			}
			if (updateTenderMap.values().size() > 0) {
				update updateTenderMap.values();
			}
			//删除同名的附件
			List<Attachment> DeleOtherAttList = [select id, name from Attachment where name = :FileList];
			if (DeleOtherAttList.size() > 0) {
				delete DeleOtherAttList;
			}
			System.debug('----1----' + TenOtherAttList);
			if (TenOtherAttList.size() > 0 ) {
				upsert TenOtherAttList;
			}

// 				xNFM501schedule1223 06.15 0.00
// NFM501Schedulex0 0 12 16 6 ? 2021  2021/06/16 每月16日
			rowData.NFM501_Other_Annex_Count__c = 0;
		} catch (Exception ex) {
			// Database.rollback(sp);
			// System.debug(Logginglevel.ERROR, 'QLMData_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
			// System.debug(Logginglevel.ERROR, 'QLMData_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
			// logstr += '\n' + ex.getMessage();
			iflog503.ErrorLog__c = '503抛出异常：' + ex.getMessage() + '\n' + ex.getStackTraceString()
			                       + '\n' + iflog503.ErrorLog__c;
			NFM501Controller.againSendExceptionRequest(iflog503, 'NFM501_Other_Annex_Count__c', rowData,
			        '503抛出异常：' + ex.getMessage() + '\n' + ex.getStackTraceString()
			        + '\n' + rowData.ErrorLog__c + '错误次数已经超过自动收信设定的最大次数，请手动收信');
		}
		update rowData;

		System.debug('+++++++5+++++++' + rowData);
		System.debug('+++++++4+++++++' + iflog503);
		System.debug('+++++++3+++++++' + iflog503.Log__c);
		System.debug('+++++++2+++++++' + iflog503.ErrorLog__c);
		//如果存入信息超出限制，用省略号代替
		if (iflog503.Log__c.length() > 131072) {
			iflog503.Log__c = iflog503.Log__c.subString(0, 131065) + ' ...';
		}
		if (iflog503.ErrorLog__c.length() > 32768) {
			iflog503.ErrorLog__c = iflog503.ErrorLog__c.subString(0, 32760) + ' ...';
		}
		upsert iflog503;


	}
}