global class NFM503InfoFileBatch implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {
    public String TenId;
    public String bidInfoFileID;
    /* 迁移ali sushanhu 20231018
    //add staic sushanhu 20220302 start
	public static String transUrl;
	public static String transId;
	public static String token;
    public static  integer isSuccess=0; 
    public static List<String> sfRecordIds =new List<String>();
	//add staic sushanhu 20220302 end
    */
    Boolean IsNeedExecute = false;  //2021-06-28 mzy  WLIG-BYHD79  SFDC环境batch合并调查  是否符合执行条件
    /*迁移ali sushanhu 20231018
    //add nfm 503 aws response start sushanhu 20220301
    global class File{
        public String key;
        public String name;
    }
    //add nfm 503 aws response sushanhu 20220301 end
    */
    //2021-06-28  mzy update  千里马-Batch start
    global NFM503InfoFileBatch() {
        this.IsNeedExecute = true;
    }
    //2021-06-28 mzy  update  千里马-Batch end
    global NFM503InfoFileBatch(String TenId) {
        this.TenId = TenId;
    }

    global NFM503InfoFileBatch(String bidInfoFileID, boolean a) {
        this.bidInfoFileID = bidInfoFileID;
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'select Id, Tender_information__c, infoAddress__c, ' +
                        // SWAG-C9S9P6 新增字段 2022-05-25 ssm start
                        'Tender_information__r.InfoId__c, Tender_information__r.subInfoType__c, ' +    
                        // SWAG-C9S9P6 新增字段 2022-05-25 ssm end 
                        'Tender_information__r.InfoType__c, isProcessed__c, ' +
                        ' ErrorMessage__c from bidInfoFile__c where isProcessed__c = false ';
        if (String.isNotBlank(TenId)) {
            query += 'and Tender_information__r.Id =: TenId';
        }
        if (String.isNotBlank(bidInfoFileID)) {
            query += 'and Id =: bidInfoFileID';
        }

        return Database.getQueryLocator( query );
    }

    global void execute(Database.BatchableContext BC, list<bidInfoFile__c> bidInfoFileList) {
        Savepoint sp;
        bidInfoFile__c bidInfoFile = bidInfoFileList[0];
        List<String> queryfileList = new List<String>();
        queryfileList.add(bidInfoFile.infoAddress__c);
        try {
           //update 同staic 20220302 satrt
			String token;
			//update 同staic 20220302 end
            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;

            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();
                if (String.isBlank(response.responseBody)) {
                    bidInfoFile.ErrorMessage__c = '503token:' + response.status;
                }
                token = response.responseBody;
                oldTime = Datetime.now();
                token503.NFM501_Token__c = token;
                oldTime503.NFM501_Gain_End_Time__c = oldTime;
            }
            /* 迁移ali sushanhu 20231018
            PIHelper.piIntegration pi =PIHelper.getPIIntegrationInfo('NFM503');
            if (string.isblank(token) || timeslot > 1800000) {
                //UP TO AWAS TOKEN 20220225 SUSHANHU START
                // NFMUtil.response response = NFMUtil.getAWSToken();
                // //UP TO AWAS TOKEN 20220225 SUSHANHU END
                // if (String.isBlank(response.responseBody)) {
                //     bidInfoFile.ErrorMessage__c = '503token:' + response.status;
                // }
                token = pi.token;
                oldTime = Datetime.now();
                token503.NFM501_Token__c = token;
                oldTime503.NFM501_Gain_End_Time__c = oldTime;
            }
            */ 
             // 存放超过12M的附件
             //List<Attachment> TenOtherAttList = new List<Attachment>();
             //迁移ali sushanhu 20231018 start
             List<ContentVersion> TenOtherAttList = new List<ContentVersion>();
             List<ContentDocumentLink> docLinkList = new List<ContentDocumentLink>();
             //迁移ali sushanhu 20231018 end
             // 存放所有附件
             List<String> FileList = new List<String>();
             // 如果文件大小超过12M更新
             List< Tender_information__c> updateTenderList = new  List< Tender_information__c>();
             // 获取接口3中数据
             NFMUtil.response503 response = NFMUtil.getFileData(token, bidInfoFile.infoAddress__c);
            //UP TO NEW  AWS method sushanhu start 20220301
            //List< Tender_information__c> updateTenderList = new  List< Tender_information__c>();
            /*迁移ali sushanhu 20231018
            List<FileAddress__c> fileList = new List<FileAddress__c>();
            transUrl =pi.searchUrl;
            NFMUtil.response response = NFMUtil.getAWSQLMData(pi.newUrl ,JSON.serialize(queryfileList), token);
            system.debug('aws result'+response.responseBody);
            Map<String, Object> result = (Map<String, Object>)JSON.deserializeUntyped(response.responseBody);
            system.debug('NFM503 aws result--'+response.responseBody+'status'+response.status);
            transId =(String)result.get('txId');
            //UP TO NEW  AWS method sushanhu start 20220301 
            */
            // 新得存储 不需要判断文件超过12m
            // 文件大小超过12M
             if (response.Name.equals('文件大小超过12M')) {
                 id tendID = bidInfoFile.Tender_information__c;
                 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 = bidInfoFile.infoAddress__c;
                 } else {
                     if (!tempTender.Overstep_12M_infofile__c.contains(bidInfoFile.infoAddress__c)) {
                         // List<String> urlList = singleFile.split(',');
                         tempTender.Overstep_12M_infofile__c += bidInfoFile.infoAddress__c + ',';
                     }
                 }
                 updateTenderList.add(tempTender);
             }
             // 将获取到的数据存成附件
             /* 迁移ali 改为 contentdocment存附件 sushanhu 20231019
             Attachment WebAtt = new Attachment();
             WebAtt.ParentId = bidInfoFile.Tender_information__c;
             WebAtt.Body = response.responseBody;
             WebAtt.Name = bidInfoFile.Tender_information__r.InfoType__c + ':' + response.Name;
             if (!response.Name.equals('文件大小超过12M')) {
                TenOtherAttList.add(WebAtt);
            }
            */
             ContentVersion CV =  new ContentVersion();
             CV.Title = bidInfoFile.Tender_information__r.InfoType__c + ':' + response.Name;
             CV.PathOnClient = response.Name;
             CV.VersionData = response.responseBody;
             //新加的字段 存到descrption add by tiger 20231019
             CV.Description = bidInfoFile.Tender_information__r.InfoId__c +';' 
             + bidInfoFile.Tender_information__r.InfoType__c +';'
             + bidInfoFile.Tender_information__r.subInfoType__c +';'
             + String.valueof(Date.today());
             CV.IsMajorVersion = true;
             if (!response.Name.equals('文件大小超过12M')) {
                TenOtherAttList.add(CV);
                }
             sp = Database.setSavepoint();

             if (updateTenderList.size() > 0) {
                 update updateTenderList;
             }

             System.debug('----1----' + TenOtherAttList);
             if (TenOtherAttList.size() > 0 ) {
                 upsert TenOtherAttList;
             }
             List<String> cdIdList = new List<String>();
             for (ContentDocument cd : [SELECT Id, LatestPublishedVersionId
                                   FROM ContentDocument
                                   WHERE LatestPublishedVersionId = :TenOtherAttList[0].Id 
                                   ]) {
                cdIdList.add(cd.Id);
            }
            docLinkList.add(new ContentDocumentLink(ContentDocumentId = cdIdList[0], LinkedEntityId= bidInfoFile.Tender_information__c, ShareType='V'));
            upsert docLinkList;
             bidInfoFileList[0].isProcessed__c = true;
             bidInfoFileList[0].ErrorMessage__c = '';

             update bidInfoFileList;
             if (System.Test.isRunningTest()) {
                 throw new ControllerUtil.myException('aaa');
             }
             return;
             /* 迁移ali sushanhu 20231018
            String statusCode =String.valueOf(result.get('status')) ;
            system.debug('statuscode aws-- '+statusCode);
            if (!'0'.equals(statusCode)) {
                System.debug('response.responseBody:' + response.responseBody);
                return;
            }
            Map<String, Object> fileMap = (Map<String, Object >)result.get('object');
            system.debug('fileMap'+fileMap.toString());
            Map<String, Object> fileVO =(Map<String, Object>)fileMap.get(bidInfoFile.infoAddress__c);

            String Name =(String)fileVO.get('name');
            // if (Name.equals('文件大小超过12M')) {
            //     id tendID = bidInfoFile.Tender_information__c;
            //     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 = bidInfoFile.infoAddress__c;
            //     } else {
            //         if (!tempTender.Overstep_12M_infofile__c.contains(bidInfoFile.infoAddress__c)) {
            //             // List<String> urlList = singleFile.split(',');
            //             tempTender.Overstep_12M_infofile__c += bidInfoFile.infoAddress__c + ',';
            //         }
            //     }
            //     updateTenderList.add(tempTender);
            // }
           
            //将获取的AWS文件地址存储
            FileAddress__c file = new FileAddress__c();
            file.ParentRecordId__c = bidInfoFile.Tender_information__c;
            file.FileName__c = bidInfoFile.Tender_information__r.InfoType__c + ':' + Name;
            file.DownloadLink__c =pi.undeleteUrl+(String)fileVO.get('key')+'&fileName='+file.FileName__c;
            file.ViewLink__c = pi.queryUrl+(String)fileVO.get('key');
            file.AWS_File_Key__c =(String)fileVO.get('key');
            // SWAG-C9S9P6 新增字段 start
            file.InfoId__c = bidInfoFile.Tender_information__r.InfoId__c;
            file.InfoType__c = bidInfoFile.Tender_information__r.InfoType__c;
            file.subInfoType__c = bidInfoFile.Tender_information__r.subInfoType__c;
            file.UpdateDate__c = Date.today(); 
            // SWAG-C9S9P6 新增字段 end
            fileList.add(file);
            sp = Database.setSavepoint();

            System.debug('----1----' + fileList);
            if (fileList.size() > 0 ) {
                upsert fileList;
            }

            bidInfoFileList[0].isProcessed__c = true;
            bidInfoFileList[0].ErrorMessage__c = '';

            update bidInfoFileList;
            // add 确认事务 sushanhu 20220302 start
            
            if (fileList.size() > 0 ) {
			for (FileAddress__c fileAddress : fileList) {
                system.debug('fileAddress.Id---'+json.serialize(fileAddress));
				sfRecordIds.add(fileAddress.Id);
                system.debug('fileAddress.Id---'+fileAddress.Id);
			}
            }
            system.debug('成功的token'+token);
            isSuccess =1;
           
            // if (!confirm) {
			// 	//回滚
            //     if (sp != null) {
            //         Database.rollback(sp);
            //     }
			// }
            // add 确认事务 sushanhu 20220302 end
            if (System.Test.isRunningTest()) {
                throw new ControllerUtil.myException('aaa');
            }
            // return;
            */
        } catch (Exception ex) {
            if (sp != null) {
                Database.rollback(sp);
            }
            // //add 确认事务 20220302 sushanhu start
            // system.debug('失败的token'+token);
            //  PIHelper.confirmFileTrans('NFM503',0,'',transId,token,transUrl);
            //add 确认事务 20220302 sushanhu end
            bidInfoFile.ErrorMessage__c = '503抛出异常：' + ex.getMessage() + '\n' + ex.getStackTraceString();
            system.debug('ErrorMessage'+bidInfoFile.ErrorMessage__c);
        }
        update bidInfoFile;
    }

    global void finish(Database.BatchableContext BC) {
        /* 迁移ali sushanhu 20231018
        // add confirm transaction for pipl  sushanhu 20220314 start
        if (isSuccess==0) {
            PIHelper.confirmFileTrans('NFM503',isSuccess,'',transId,token,transUrl);
        }else {
            PIHelper.confirmFileTrans('NFM503',isSuccess,JSON.serialize(sfRecordIds),transId,token,transUrl);
        }
         
         // add confirm transaction for pipl  sushanhu 20220314 end
         */
    }
              
}