public with sharing class NFM501FutureController implements Queueable {
    //先定义
    //先定义
    // 	投标截止时间
    // 2021/01/04 18:00
    //add by sushanhu for pi 20220310 start
    //public  String txId; //迁移ali sushanhu 20231019
    
    //add by sushanhu for pi 20220310 end
    public String rowData_id;
    public NFM501FutureController(String rowData_id) {
        this.rowData_id = rowData_id;
    }
     //add by sushanhu for pi 20220310 start
    //  public NFM501FutureController(String rowData_id,String txId) {
    //      this.rowData_id = rowData_id;
    //     this.txId = txId;
    //  }
     //add by sushanhu for pi 20220310 end
    public static Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
    public void execute(QueueableContext context /*, String iflog_Id*/ ) {
        //需加一数字变量（如果获取到 html附件，其他附件，在日志中显示数量）
        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_Web_Annex_Count__c
            //,
            //AWS_Transaction_Id__c //ADD BY SUSHANHU for pi 20220310 //迁移ali sushanhu 20231019
            from BatchIF_Log__c where RowDataFlg__c = true and Id = : rowData_id
        ];
        //存放报错信息
/*//迁移ali sushanhu 20231019
        //add by sushanhu for pipl 20220311 start
        system.debug('txId from log'+rowData.AWS_Transaction_Id__c);
        if (!String.isEmpty(rowData.AWS_Transaction_Id__c)) {
            txId =rowData.AWS_Transaction_Id__c; //add by sushanhu for pipl 20220310
        }else {
            system.debug('txId from NF501'+txId);
        }
         //add by sushanhu for pipl 20220311 end
        system.debug('nfm501future awsid'+txId);
*/
        BatchIF_Log__c iflog501Future = new BatchIF_Log__c();
        iflog501Future.Type__c = 'NFM501';
        iflog501Future.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog501Future.Log__c = ' ';
        iflog501Future.ErrorLog__c = ' ';
        iflog501Future.RowDataFlg__c = false;
        //iflog501Future.AWS_Transaction_Id__c=rowData.AWS_Transaction_Id__c;//迁移ali sushanhu 20231019
        insert iflog501Future;
        //NFM501FutureController.main(rowData.Id, iflog501Future.Id, false,txId);//迁移ali sushanhu 20231019
        NFM501FutureController.main(rowData.Id, iflog501Future.Id, false);
    }
    
    @future(callout = true)
    //重发（把从接口获取到的数据存入日志中，再把日志中存入的数据重新JOSN解析一遍）
    public static void main(String rowData_id, String iflog_id, boolean Manual_execution501future
                                //,//迁移ali sushanhu 20231019
                                //String txId //增加事务id forpipl 20220310 
            ) {
        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_Web_Annex_Count__c from BatchIF_Log__c
            where Id = : rowData_id
        ];
        BatchIF_Log__c iflog501Future = [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
            from BatchIF_Log__c where id = : iflog_id
        ];
        // 由于检索出来的rowData和iflog为空，则进行一下判断
        iflog501Future.Log__c = iflog501Future.Log__c == null ? '' : iflog501Future.Log__c;
        iflog501Future.ErrorLog__c = iflog501Future.ErrorLog__c == null ? '' : iflog501Future.ErrorLog__c;
        rowData.Log__c = rowData.Log__c == null ? '' : rowData.Log__c;
        rowData.ErrorLog__c = rowData.ErrorLog__c == null ? '' : rowData.ErrorLog__c;
        // System.debug('+++++++1+++++++'+iflog501Future);
        String QLMDataStr = NFMUtil.QLMgetRowDataStr(rowData);
        system.debug('QLMDataStr---'+QLMDataStr);
        NFM501controller.AllData getQLMData1 = (NFM501controller.AllData)
        JSON.deserialize(QLMDataStr, NFM501controller.AllData.class);
        system.debug('getQLMData1---'+json.serialize(getQLMData1));
        if (getQLMData1 == null) {
            return;
        }
        //List<PIHelper.IdList> idList = new List<PIHelper.IdList>();//存储更新后得sfid和awsid add by sushanhu 20220310 //迁移ali sushanhu 20231019
        //PIHelper.PIIntegration NFM501AWS =PIHelper.getPIIntegrationInfo('QLMNFM501'); //add by sushanhu 20220310 //迁移ali sushanhu 20231019
        Savepoint sp = Database.setSavepoint();
        //IF转换表（为实现选项列表的下拉选项）
        Map < String, String > transferMap = new Map < String, String > ();
        List < BatchIF_Transfer__c > transferList = [select Table__c,
            Column__c,
            External_value__c,
            Internal_value__c
            from BatchIF_Transfer__c
            where Dropped_Flag__c = false
            and Table__c = 'Tender_information__c'
        ];
        for (BatchIF_Transfer__c t: transferList) {
            transferMap.put(t.Column__c + t.External_value__c, t.Internal_value__c);
        }
        //覆盖之前的数据（更新成新数据--以下三步）
        //1、for 遍历接口数据，做一个infoId 的list
        List < String > projectIdList = new List < String > ();
        for (NFM501Controller.ListItem projectId: getQLMData1.data.list1) {
            if (String.isNotBlank(projectId.projectId)) {
                projectIdList.add(projectId.projectId);
            }
        }
        // System.debug('+++++++2+++++++'+ UrlList);
        //2、通过list查招标信息；做一个Map key infoid value 招标信息id
        List < Tender_information__c > TIList = [Select Id, OwnerId, CursorMark__c, ZhaoBiaoUnit1__c, ZhaoBiaoUnit2__c,
            ZhaoBiaoUnit3__c, ZhaoBiaoUnit4__c, ZhaoBiaoUnit5__c, InfoId__c, Keywords__c, Domestic_Or_Import__c, 
            BiddingType__c, InfoQianlimaUrl__c, ZhaoRelationWay__c, IsElectronic__c,
            XmNumber__c, TenderEndTime__c, AreaProvince__c, ZhongBiaoUnit1__c,
            ZhongBiaoUnit2__c, ZhongBiaoUnit3__c, ZhongBiaoUnit4__c, ZhongBiaoUnit5__c,
            IsOther__c, OtherInfoTitle__c, otherInfo__c, InfoType__c, subInfoType__c,
            InfoTitle__c, OpenBidingTime__c, AgentRelationWay__c,
            InfoFile__c,
            BudgetAmount1__c, BudgetAmount2__c, BudgetAmount3__c,
            BudgetAmount4__c, BudgetAmount5__c,
            BudgetUnit__c, Other_units__c,
            InfoPublishTime__c, AgentRelationName__c, BidingEndTime__c,
            WinnerAmount1__c, WinnerAmount2__c, WinnerAmount3__c, WinnerAmount4__c, WinnerAmount5__c,
            WinnerUnit__c, ZhongRelationWay__c, BidingAcquireTime__c, TenderBeginTime__c,
            ProjectId__c,
            Sum__c, status__c,
            SumUnit__c, AreaCity__c, AreaCountry__c, AgentUnit1__c,
            AgentUnit2__c, AgentUnit3__c, AgentUnit4__c, AgentUnit5__c,
            ZhaoRelationName__c, ZhongRelationName__c,
            publicDate__c, noticeDate__c, ResultDate__c
            //,AWS_Data_Id__c //ADD FOR pi SUSHANHU 20220311 //迁移ali sushanhu 20231019
            FROM Tender_information__c Where ProjectId__c in : projectIdList
        ];
        Map < String, Tender_information__c > TenMap = new Map < String, Tender_information__c > ();
        //精琢科技   zxk   2021-11-11  SWAG-C637NF   start
        Map < String, String > TenMap01 = new Map < String, String > ();
        for (Tender_information__c Ten: TIList) {
            String strMap = Ten.InfoType__c;
            String strMap01 = Ten.subInfoType__c;
            TenMap01.put(Ten.ProjectId__c + 'infoType', strMap);
            TenMap01.put(Ten.ProjectId__c + 'subInfoType', strMap01);
            //精琢科技   zxk   2021-11-11  SWAG-C637NF   end
            TenMap.put(Ten.ProjectId__c, Ten);
        }
        Map < string, List < String >> SelectbidInfoFileMap = new map < string, List < String >> ();
        List < bidInfoFile__c > bidInfoFileList = [select Id, Tender_information__r.ProjectId__c, infoAddress__c
            from bidInfoFile__c
            where Tender_information__r.ProjectId__c in : projectIdList
        ];
        for (bidInfoFile__c bidInfoFile: bidInfoFileList) {
            List < String > tempbidInfoFileURLList = new List < String > ();
            if (SelectbidInfoFileMap.containsKey(bidInfoFile.Tender_information__r.ProjectId__c)) {
                tempbidInfoFileURLList = SelectbidInfoFileMap.get(bidInfoFile.Tender_information__r.ProjectId__c);
            }
            tempbidInfoFileURLList.add(bidInfoFile.infoAddress__c);
            SelectbidInfoFileMap.put(bidInfoFile.Tender_information__r.ProjectId__c, tempbidInfoFileURLList);
        }
        
        try {
            // 招标信息
            Map < string, List < bidInfoFile__c >> createbidInfoFileMap = new map < string, List < bidInfoFile__c >> ();
            Map < String, List < Tender_information_details__c >> tempList1 = new Map < String, List < Tender_information_details__c >> ();
            Map < string, Tender_information__c > updateTenderMap = new map < string, Tender_information__c > ();
            Set < String > TarDetailSet = new Set < String > ();
            
            for (NFM501Controller.ListItem LI: getQLMData1.data.list1) {
                system.debug('LI----'+json.serialize(LI));
                // 項目転送のセット
                Tender_information__c te1 = new Tender_information__c();
/* //迁移ali sushanhu 20231019
                //add aws dataid sushanhu 20220223 start
                if(String.isEmpty(LI.DataId)){
                    continue;
                }
                te1.AWS_Data_Id__c = LI.DataId;
                //add aws dataid sushanhu 20220223 end
*/
                if (String.isBlank(LI.projectId)) {
                    iflog501Future.ErrorLog__c += 'Error! [' + LI.projectId + ']NotExist. This information is skipped.\n';
                    continue;
                } else {
                    te1.ProjectId__c = LI.projectId;
                }
                //确定每条数据对应的每个招投标(原来的数据)
                if (TenMap.containsKey(LI.projectId)) {
                    te1 = TenMap.get(LI.projectId);
                }
                // （要更新的数据）
                if (updateTenderMap.containsKey(LI.projectId)) {
                    te1 = updateTenderMap.get(LI.projectId);
                }
                if (String.isBlank(LI.areaProvince) || (String.isNotBlank(te1.status__c) && !te1.status__c.equals('01.待确认'))) {
                    te1.AreaProvince__c = te1.AreaProvince__c;
                } else if (LI.areaProvince.equals('香港特别行政区') || LI.areaProvince.equals('澳门特别行政区') || LI.areaProvince.equals('台湾省')) {
                    iflog501Future.ErrorLog__c += 'Error! [' + LI.areaProvince + ']Is 香港特别行政区(澳门特别行政区,台湾省). This information is skipped.\n';
                    continue;
                } else {
                    te1.AreaProvince__c = LI.areaProvince;
                }
                te1.RecordTypeId = Schema.SObjectType.Tender_information__c.getRecordTypeInfosByDeveloperName().get('QLM').getRecordTypeId();
                te1.CursorMark__c = getQLMData1.data.cursorMark;
                te1.OwnerId = String.isBlank(te1.OwnerId) ? System.label.tender_3 : te1.OwnerId;
                //只存前五个，有关键字的提前，无关键字的按顺序排，排到第五个
                if (LI.ZhaoBiaoUnit != null && LI.ZhaoBiaoUnit.size() > 0) {
                    List < String > NewStringList = new List < String > ();
                    NFM501FutureController.ZBU(LI.ZhaoBiaoUnit, NewStringList);
                    //如果接口有数据传过来，就全覆盖
                    //如果接口没有数据穿过来，不覆盖
                    //如果接口有数据且不够五个，全覆盖
                    for (Integer i = 0; i < NewStringList.size(); i++) {
                        Integer b = i + 1;
                        te1.put('ZhaoBiaoUnit' + b + '__c', NewStringList.get(i));
                    }
                    if (LI.ZhaoBiaoUnit.size() > 5) {
                        te1.Other_units__c = true;
                    }
                }
                te1.InfoId__c = String.isBlank(LI.infoId) ? te1.InfoId__c : LI.infoId;
                te1.Keywords__c = String.isBlank(LI.keywords) ? te1.Keywords__c : LI.keywords;
                // add fxk 2021/12/06
                if(String.isBlank(te1.Domestic_Or_Import__c)){
                    te1.Domestic_Or_Import__c = String.isBlank(LI.allKeywords) ? te1.Domestic_Or_Import__c : LI.allKeywords;
                }
                //转换表（实现选项列表的下拉选项）
                te1.BiddingType__c = NFMUtil.getMapValue(transferMap, 'BiddingType__c', LI.biddingType, iflog501Future);
                te1.InfoQianlimaUrl__c = String.isBlank(LI.infoQianlimaUrl) ? te1.InfoQianlimaUrl__c : LI.infoQianlimaUrl;
                System.debug('======111111111111========');
                //拼接字符串
                if (LI.ZhaoRelationWay != null && LI.ZhaoRelationWay.size() > 0) {
                    System.debug('======LI.ZhaoRelationWay========'+LI.ZhaoRelationWay);
                    te1.ZhaoRelationWay__c = String.join(LI.ZhaoRelationWay, '，');
                     //add 密文 sushanhu 20220223 start
                     //System.debug('======LI.ZhaoRelationWayEncrypted========'+LI.ZhaoRelationWayEncrypted);       //zhj 新方案改造 2022-12-09
                     //te1.ZhaoRelationWay_Encrypted__c =String.join(LI.ZhaoRelationWayEncrypted,'，');             //zhj 新方案改造 2022-12-09
                     System.debug('======2222222222222========');
                     //add 密文 sushanhu 20220223 end
                }
                //转换表（选项列表的下拉选项）
                System.debug('======3333333333333333========');
                te1.IsElectronic__c = NFMUtil.getMapValue(transferMap, 'IsElectronic__c', LI.isElectronic, iflog501Future);
                te1.XmNumber__c = String.isBlank(LI.xmNumber) ? te1.XmNumber__c : LI.xmNumber;
                if ( String.isnotBlank(LI.tenderEndTime) ) {
                    te1.TenderEndTime__c = Datetime.valueOf(LI.tenderEndTime);
                }
                //只存前五个，有关键字的提前，无关键字的按顺序排，排到第五个
                if ((LI.ZhongBiaoUnit != null && LI.ZhongBiaoUnit.size() > 0) 
                || (LI.moreZhongBiaoUnit != null && LI.moreZhongBiaoUnit.size() > 0)) {
                    List < String > NewStringList = new List < String > ();
                    List < String > NewStringList1 = new List < String > ();
                    if (LI.ZhongBiaoUnit != null && LI.ZhongBiaoUnit.size() > 0) {
                        NewStringList1.addAll(LI.ZhongBiaoUnit);
                    }
                    if (LI.moreZhongBiaoUnit != null && LI.moreZhongBiaoUnit.size() > 0){
                        NewStringList1.addAll(LI.moreZhongBiaoUnit);
                    }
                    NFM501FutureController.ZBU(NewStringList1, NewStringList);
                    //如果接口有数据传过来，就全覆盖
                    //如果接口没有数据穿过来，不覆盖
                    //如果接口有数据且不够五个，全覆盖
                    for (Integer i = 0; i < NewStringList.size(); i++) {
                        Integer b = i + 1;
                        te1.put('ZhongBiaoUnit' + b + '__c', NewStringList.get(i));
                    }
                    if (LI.ZhongBiaoUnit.size() > 5) {
                        te1.Other_units__c = true;
                    }
                }
                //转换表（选项列表的下拉选项）
                //接口传来其他公告
                if (String.isBlank(te1.Id)) { //判断招标项目是否存在
                    if ('5'.equals(LI.infoType) || '2'.equals(LI.infoType)) {  //20220510 lt SWAG-CE6C45
                        //招投标项目名称
                        te1.InfoTitle__c = LI.infoTitle == null ? te1.InfoTitle__c : LI.infoTitle;
                        //项目阶段
                        te1.InfoType__c = NFMUtil.getMapValue(transferMap, 'InfoType__c', LI.infoType, iflog501Future);
                        //阶段补充说明
                        te1.subInfoType__c = NFMUtil.getMapValue(transferMap, 'subInfoType__c', LI.infoTypeSegment, iflog501Future);
                        //项目名称
                        if (te1.InfoTitle__c != null && te1.InfoTitle__c != '') {
                            if (te1.InfoTitle__c.length() >= 80) {
                                te1.Name = te1.InfoTitle__c.subString(0, 79);
                            } else {
                                te1.Name = te1.InfoTitle__c;
                            }
                        }
                        //其他补充说明
                    }
                }
                if ('5'.equals(LI.infoType)) {
                    te1.IsOther__c = true;
                    te1.OtherInfoTitle__c = LI.infoTitle;
                    //其他补充说明
                    te1.otherInfo__c = NFMUtil.getMapValue(transferMap, 'otherInfo__c', LI.infoTypeSegment, iflog501Future);
                }
                if (!'2'.equals(LI.infoType) && !'5'.equals(LI.infoType)) {
                    te1.InfoTitle__c = LI.infoTitle == null ? te1.InfoTitle__c : LI.infoTitle;
                    //项目阶段
                    te1.InfoType__c = NFMUtil.getMapValue(transferMap, 'InfoType__c', LI.infoType, iflog501Future);
                    //阶段补充说明
                    te1.subInfoType__c = NFMUtil.getMapValue(transferMap, 'subInfoType__c', LI.infoTypeSegment, iflog501Future);
                    //项目名称
                    if (te1.InfoTitle__c != null && te1.InfoTitle__c != '') {
                        if (te1.InfoTitle__c.length() >= 80) {
                            te1.Name = te1.InfoTitle__c.subString(0, 79);
                        } else {
                            te1.Name = te1.InfoTitle__c;
                        }
                    }
                }
                // 中标时间(OpenBidingTime__c)
                // 2022-05-17 中标日逻辑错误，接口里没有中标日字段，仅中标阶段时，用当前日期填充 ssm
                // if (String.isNotBlank(LI.openBidingTime) ) {
                //     te1.OpenBidingTime__c = Datetime.valueOf(LI.openBidingTime);
                //     System.debug('OpenBidingTime__c1:' + te1.OpenBidingTime__c);
                // } else 
                if (te1.OpenBidingTime__c == null && '3'.equals(LI.infoType)) {
                    te1.OpenBidingTime__c = Date.today();
                    System.debug('OpenBidingTime__c2:' + te1.OpenBidingTime__c);
                }
                // 预告记录日	取第一次获取到预告的当前时间
                // 如果有值，不是第一次，如果没值
                if (('1'.equals(LI.infoType)) && te1.noticeDate__c == null) {  //20220510 lt SWAG-CE6C45
                    te1.noticeDate__c = Date.today();
                    System.debug('noticeDate__c:' + te1.noticeDate__c);
                }
                System.debug('LI.infoType:' + LI.infoType);
                System.debug('te1.ResultDate__c:' + te1.ResultDate__c);
                // 结果记录日	取第一次获取到结果的当前时间
                if (('3'.equals(LI.infoType)) && te1.ResultDate__c == null) {  //20220510 lt SWAG-CE6C45
                    te1.ResultDate__c = Date.today().addDays(-1);  //20230913 lt DB202308327700 众成 add   .addDays(-1)
                    System.debug('ResultDate__c:' + te1.ResultDate__c);
                }
                // 公告记录日	取第一次获取到公告的当前时间
                if (('0'.equals(LI.infoType)) && te1.publicDate__c == null) {  //20220510 lt SWAG-CE6C45
                    te1.publicDate__c = Date.today();
                    System.debug('publicDate__c:' + te1.publicDate__c);
                }
                if (LI.AgentRelationWay != null && LI.AgentRelationWay.size() > 0) {
                    te1.AgentRelationWay__c = String.join(LI.AgentRelationWay, '，');
                    //add 密文 sushanhu 20220223 start
                    //te1.AgentRelationWay_Encrypted__c =String.join(LI.AgentRelationWayEncrypted,'，');  //zhj 新方案改造 2022-12-09
                    //add 密文 sushanhu 20220223 end
                }
                // 将改附件存入招投标项目子对象中
                if (LI.InfoFile != null && LI.InfoFile.size() > 0) {
                    te1.InfoFile__c = String.join(LI.InfoFile, '，');
                    // 获取数据库里面当前项目ID对应的URL集合
                    List < string > existUrls = SelectbidInfoFileMap.get(LI.ProjectId);
                    // 循环当前infofile
                    List < bidInfoFile__c > tempbidInfoFileList = new List < bidInfoFile__c > ();
                    if (createbidInfoFileMap.containsKey(LI.projectId)) {
                        tempbidInfoFileList = createbidInfoFileMap.get(LI.projectId);
                    }
                    for (string InfoFile: LI.InfoFile) {
                        if (existUrls == null || !existUrls.contains(InfoFile)) {
                            bidInfoFile__c bidInfoFile = new bidInfoFile__c();
                            bidInfoFile.infoAddress__c = InfoFile;
                            tempbidInfoFileList.add(bidInfoFile);
                        }
                    }
                    createbidInfoFileMap.put(LI.projectId, tempbidInfoFileList);
                }
                if (LI.Budget != null && LI.Budget.size() > 0) {
                    //如何将从接口中获取到的数据进行存入
                    Set < String > UnitSet = new Set < String > ();
                    for (NFM501Controller.AmountItem BI: LI.Budget) {
                        UnitSet.add(BI.Unit);
                    }
                    if (UnitSet.contains('元')) {
                        NFM501FutureController.CurrencySort(LI.Budget, te1, 'BudgetAmount');
                        te1.BudgetUnit__c = '元';
                    } else if ((UnitSet.contains('美元') || UnitSet.contains('$'))) {
                        NFM501FutureController.USACurrency(LI.Budget, te1, 'BudgetAmount');
                        te1.BudgetUnit__c = '元';
                    } else if (UnitSet.size() > 0) {
                        NFM501FutureController.OtherCurrency(LI.Budget, te1, 'Budget');
                    }
                    if (LI.Budget.size() > 5) {
                        te1.Other_units__c = true;
                    }
                }
                if (String.isNotBlank(LI.infoPublishTime)) {
                    te1.InfoPublishTime__c = Datetime.valueOf(LI.infoPublishTime);
                }
                if (LI.AgentRelationName != null && LI.AgentRelationName.size() > 0) {
                    te1.AgentRelationName__c = String.join(LI.AgentRelationName, '，');
                    //add 密文 sushanhu 20220223 start
                    //te1.AgentRelationName_Encrypted__c =String.join(LI.AgentRelationNameEncrypted,'，');      //zhj 新方案改造 2022-12-09
                    //add 密文 sushanhu 20220223 end
                }
                if (String.isNotBlank(LI.bidingEndTime)) {
                    te1.BidingEndTime__c = Datetime.valueOf(LI.bidingEndTime);
                }
                if (LI.WinnerAmount != null && LI.WinnerAmount.size() > 0) {
                    Set < String > UnitSet = new Set < String > ();
                    for (NFM501Controller.AmountItem WAI: LI.WinnerAmount) {
                        UnitSet.add(WAI.Unit);
                    }
                    //如果接收到元，直接存，币种不变
                    //如果接收到美元，将美元转换为人名币
                    //如果接收到美元和元，只存元
                    //如果接受到其他，直接存
                    if (UnitSet.contains('元')) {
                        NFM501FutureController.CurrencySort(LI.WinnerAmount, te1, 'WinnerAmount');
                        te1.WinnerUnit__c = '元';
                    } else if ((UnitSet.contains('美元') || UnitSet.contains('$'))) {
                        NFM501FutureController.USACurrency(LI.WinnerAmount, te1, 'WinnerAmount');
                        te1.WinnerUnit__c = '元';
                    } else if (UnitSet.size() > 0) {
                        NFM501FutureController.OtherCurrency(LI.WinnerAmount, te1, 'Winner');
                    }
                    if (LI.WinnerAmount.size() > 5) {
                        te1.Other_units__c = true;
                    }
                }
                if (LI.ZhongRelationWay != null && LI.ZhongRelationWay.size() > 0) {
                    te1.ZhongRelationWay__c = String.join(LI.ZhongRelationWay, '，');
                    //add 密文 sushanhu 20220223 start
                    //te1.ZhongRelationWay_Encrypted__c =String.join(LI.ZhongRelationWayEncrypted,'，');        //zhj 新方案改造 2022-12-09
                    //add 密文 sushanhu 20220223 end
                }
                if (String.isNotBlank(LI.bidingAcquireTime)) {
                    te1.BidingAcquireTime__c = Datetime.valueOf(LI.bidingAcquireTime);
                }
                if (String.isNotBlank(LI.tenderBeginTime)) {
                    te1.TenderBeginTime__c = Datetime.valueOf(LI.tenderBeginTime);
                }
                // te1.ProjectId__c = LI.projectId == null ? te1.ProjectId__c : LI.projectId;
                // System.debug('-------------------------------');
                NFM501Controller.Target TG = LI.Target;
                if (LI.Target != null) {
                    // System.debug('+++++++3+++++++'+TG);
                    if (TG.Sum != null && TG.Sum != '') {
                        te1.Sum__c = TG.Sum;
                    }
                    te1.SumUnit__c = TG.SumUnit;
                    //招标信息详情
                    if (TG.TargetDetails != null) {
                        if (TG.TargetDetails.size() > 0) {
                            TarDetailSet.add(LI.projectId);
                        }
                        for (NFM501Controller.TargetDetailsItem TDI: TG.TargetDetails) {
                            // Tender_information__c te1 = new Tender_information__c();
                            Tender_information_details__c te = new Tender_information_details__c();
                            // te.Tender_information__c = te1.ID;
                            // System.debug('------1-------');
                            te.Model__c = String.isBlank(TDI.model) ? te.Model__c : TDI.model;
                            //del 数量不要了统一到数量（计量单位）中 2021、9、15 fxk Star
                            // if (TDI.number1 != null && TDI.number1 != '') {
                            // 	te.Number__c = Decimal.valueOf(TDI.number1);
                            // }
                            te.NumberUnit__c = String.isBlank(TDI.number1) ? te.NumberUnit__c : TDI.number1;
                            //del 数量不要了统一到数量（计量单位）中 2021、9、15 fxk End
                            te.Brand__c = String.isBlank(TDI.brand) ? te.Brand__c : TDI.brand;
                            if (String.isNotBlank(TDI.totalPrice)) {
                                te.TotalPrice__c = TDI.totalPrice;
                            }
                            if (String.isNotBlank(TDI.price)) {
                                te.Price__c = TDI.price;
                            }
                            te.PriceUnit__c = String.isBlank(TDI.priceUnit) ? te.PriceUnit__c : TDI.priceUnit;
                            te.TotalPriceUnit__c = String.isBlank(TDI.totalPriceUnit) ? te.TotalPriceUnit__c : TDI.totalPriceUnit;
                            // if (String.isNotBlank(TDI.name) ) {
                            // 	if (TDI.name.length() >= 255) {
                            // 		te.Name__c = TDI.name.subString(0, 254);
                            // 	} else {
                            // 		te.Name__c = TDI.name;
                            // 	}
                            // }
                            // te.Brand__c.replaceAll('null','');
                            // te.Model__c.replaceAll('null','');
                            if (String.isBlank(TDI.name)) {
                                System.debug('----------99999');
                                String brand = String.isBlank(TDI.brand) ? '' : TDI.brand;
                                String model = String.isBlank(TDI.model) ? '' : TDI.model;
                                te.Name__c = brand + ':' + model;
                                te.Name = brand + ':' + model;
                            } else {
                                te.Name__c = String.isBlank(TDI.name) ? te.Name__c : TDI.name;
                            }
                            if (String.isNotBlank(te.Name__c)) {
                                if (te.Name__c.length() >= 80) {
                                    te.Name = te.Name__c.subString(0, 79);
                                } else {
                                    te.Name = te.Name__c;
                                }
                            }
                            te.Keywords__c = String.isBlank(TDI.tarKeyword) ? te.Keywords__c : TDI.tarKeyword;
                            if (tempList1.containsKey(te1.ProjectId__c)) {
                                tempList1.get(te1.ProjectId__c).add(te);
                            } else {
                                tempList1.put(te1.ProjectId__c, new List < Tender_information_details__c > ());
                                tempList1.get(te1.ProjectId__c).add(te);
                            }
                            te.ProjectId__c = te1.ProjectId__c;
                            //tempList1.put(te1.InfoId__c, te);
                            //tempList1.add(te);
                            // 如果更新的数据阶段为3.结果且补充说明为3-5：中标通知，设置最终标的物为true
                            te.Is_Final__c = String.isNotBlank(LI.infoType) && '3'.equals(LI.infoType) && String.isNotBlank(LI.infoTypeSegment) && '11'.equals(LI.infoTypeSegment) ? true : false;

                        }
                    }
                }
                if (String.isBlank(LI.areaCity) || (te1.status__c != null && !te1.status__c.equals('01.待确认'))) {
                    te1.AreaCity__c = te1.AreaCity__c;
                } else {
                    te1.AreaCity__c = LI.areaCity;
                }
                if (String.isBlank(LI.areaCountry) || (te1.status__c != null && !te1.status__c.equals('01.待确认'))) {
                    te1.AreaCountry__c = te1.AreaCountry__c;
                } else {
                    te1.AreaCountry__c = LI.areaCountry;
                }
                //只存前五个，有关键字的提前，无关键字的按顺序排，排到第五个
                if (LI.AgentUnit != null && LI.AgentUnit.size() > 0) {
                    List < String > NewStringList = new List < String > ();
                    NFM501FutureController.ZBU(LI.AgentUnit, NewStringList);
                    //如果接口有数据传过来，就全覆盖
                    //如果接口没有数据穿过来，不覆盖
                    //如果接口有数据且不够五个，全覆盖
                    for (Integer i = 0; i < NewStringList.size(); i++) {
                        Integer b = i + 1;
                        te1.put('AgentUnit' + b + '__c', NewStringList.get(i));
                    }
                    if (LI.AgentUnit.size() > 5) {
                        te1.Other_units__c = true;
                    }
                }
                if (LI.ZhaoRelationName != null && LI.ZhaoRelationName.size() > 0) {
                    te1.ZhaoRelationName__c = String.join(LI.ZhaoRelationName, '，');
                    //add 密文 sushanhu 20220223 start
                    //te1.ZhaoRelationName_Encrypted__c =String.join(LI.ZhaoRelationNameEncrypted,'，');        //zhj 新方案改造 2022-12-09
                    //add 密文 sushanhu 20220223 end
                }
                if (LI.ZhongRelationName != null && LI.ZhongRelationName.size() > 0) {
                    te1.ZhongRelationName__c = String.join(LI.ZhaoRelationName, '，');
                     //add 密文 sushanhu 20220223 start
                     //te1.ZhongRelationName_Encrypted__c =String.join(LI.ZhongRelationNameEncrypted,'，');     //zhj 新方案改造 2022-12-09
                     //add 密文 sushanhu 20220223 end
                }
                
                te1.QLMGetDataTime__c = Date.today();  //20231018 lt add DB202308327700

                System.debug('te1-----'+json.serialize(te1));
                //精琢科技   zxk   2021-11-11  SWAG-C637NF   start
                // 如果第一次项目阶段就传来变更状态的话，那么就不生成招投标项目（由于变更阶段项目名称传来为空，为了不让项目名自动赋值为Id）
                if (String.isNotBlank(te1.InfoType__c) && String.isNotBlank(LI.projectId)) {
                    String tenderinformation = TenMap01.get(LI.projectId + 'infoType');
                    String tenderinformation01 = TenMap01.get(LI.projectId + 'subInfoType');
                    if (TIList.size() <= 0) {
                        updateTenderMap.put(LI.projectId, te1);
                    } else {
                        if ((tenderinformation == '2：公告' && te1.InfoType__c == '1：预告') || (tenderinformation == '3：结果' && te1.InfoType__c == '2：公告') || (tenderinformation == '3：结果' && te1.InfoType__c == '1：预告')) {
                            if ((tenderinformation01 == '2-2：重新招标') || (tenderinformation01 == '3-1：废标公告' || tenderinformation01 == '3-2：流标公告')) {
                                updateTenderMap.put(LI.projectId, te1);
                            }
                        } else {
                            updateTenderMap.put(LI.projectId, te1);
                        }
                    }
                }
                //精琢科技   zxk   2021-11-11  SWAG-C637NF   end
            }
            // System.debug('12345678!!!!!'+updateTenderMap.values());
            //3、通过list查招标明细，删除所以查出的明细
            // 2022-06-06 中标通知的标的物为最终标的物，不再修改，其他阶段的标的物可删除
            List < Tender_information_details__c > DetlList = [Select Id, Name, Name__c, ProjectId__c, Brand__c, Model__c, Keywords__c, 
                    NumberUnit__c, TotalPrice__c, Price__c, PriceUnit__c, TotalPriceUnit__c, Is_Final__c  
                FROM Tender_information_details__c
                Where ProjectId__c in : TarDetailSet and source__c in ('千里马', '手工录入')
            ];
            // if (DetlList.size() > 0) {
            //     delete DetlList;
            // }
            system.debug('updateTenderMap---'+json.serialize(updateTenderMap));
            if (updateTenderMap.values().size() > 0) {
                upsert updateTenderMap.values();
            }
            System.debug('123456789123456789:' + updateTenderMap);
            //将招标信息和招标信息详情关联起来（通过ProjectId这一唯一标识）
            Map < string, Tender_information__c > TenderMap = new map < string, Tender_information__c > ();
            
            for (Tender_information__c TMap: updateTenderMap.values()) {
                system.debug('TMap---'+JSON.serialize(TMap));
                TenderMap.put(TMap.ProjectId__c, TMap);
                PIHelper.IdList il= new PIHelper.IdList();
/*//迁移ali sushanhu 20231019
                // add for pipl  sushanhu 20220310 start
                il.awsId =TMap.AWS_Data_Id__c;
                il.sfRecordId=TMap.Id;
                idList.add(il);
                // add for pipl  sushanhu 20220310 end
*/
            }
            System.debug('12345678!!!!!' + TenderMap.values());
            List < Tender_information_details__c > TenList = new List < Tender_information_details__c > ();
            // 新的标的物内容不为空时进入以下逻辑
            if (tempList1.size() > 0) {
                // 先循环现有标的物，判断哪些删除，哪些保留
                Map<String, String> undelete_projects = new Map<String, String>();
                List<Tender_information_details__c> delete_list = new List<Tender_information_details__c>();
                for (Tender_information_details__c det : DetlList) {
                    // 判断最终标的物标记是否为true或新标的物里不包含project
                    // 2023-12-02 逻辑调整 3-5的标的物可以覆盖自己的标的物数据
                    // if (det.Is_Final__c || !tempList1.containsKey(det.ProjectId__c)) {
                    if (!tempList1.containsKey(det.ProjectId__c) || 
                        (det.Is_Final__c && 
                        tempList1.containsKey(det.ProjectId__c) && 
                        tempList1.get(det.ProjectId__c) != null && 
                        tempList1.get(det.ProjectId__c).size() > 0 && 
                        tempList1.get(det.ProjectId__c).get(0).Is_Final__c == false) ) {
                        undelete_projects.put(det.ProjectId__c, det.ProjectId__c);
                    } else {
                        delete_list.add(det);
                    }
                }
                if (delete_list != null && delete_list.size() > 0) {
                    delete delete_list;
                }
                for (String projectId: tempList1.keySet()) {
                    for (Tender_information_details__c vma: tempList1.get(projectId)) {
                        // 2022-06-06 增加判断 projectId不再undelete的列表里
                        if (vma != null && TenderMap.containskey(projectId) && !undelete_projects.containsKey(projectId)) {
                            vma.Tender_information__c = TenderMap.get(projectId).id;
                            TenList.add(vma);
                        }
                    }
                }
                insert TenList;
            }
            // infoFile(附件)将改附件存入招投标项目子对象中
            List < bidInfoFile__c > insertbidInfoFileList = new List < bidInfoFile__c > ();
            if (createbidInfoFileMap.size() > 0) {
                for (String infoFileprojectId: createbidInfoFileMap.keySet()) {
                    for (bidInfoFile__c insertbidInfoFile: createbidInfoFileMap.get(infoFileprojectId)) {
                        if (insertbidInfoFile != null && TenderMap.containskey(infoFileprojectId)) {
                            insertbidInfoFile.Tender_information__c = TenderMap.get(infoFileprojectId).id;
                            insertbidInfoFileList.add(insertbidInfoFile);
                        }
                    }
                }
                insert insertbidInfoFileList;
            }
            if (!Manual_execution501future) {
                //测试 Open the comment by Li Jun 20220404
                System.enqueueJob(new NFM502Controller(rowData.id));
            }
            // logstr += '\nend';
            rowData.NFM501Future_Count__c = 0;
            System.debug('+++++++4+++++++' + rowData.NFM501Future_Count__c);
            if (System.Test.isRunningTest()) {
                throw new ControllerUtil.myException('aaa');
            }
            //确认事务 add for pi sushanhu 20220310 start
            // PIHelper.confirmTrans('NFM501',1,null,txId,NFM501AWS.token,NFM501AWS.transactionURL,idList);
            //PIHelper.insertConfirmTrans('NFM501',1,null,txId,1,NFM501AWS.transactionURL,idList);//迁移ali sushanhu 20231019
            //确认事务 add for pi sushanhu 20220310 end
        } catch (Exception ex) {
            // 如果数据获取过程中，有错误（同一游标，如果报错，是他重新获取一遍，如果三次都没能获取到，就发送邮件报错信息，然后手动进行获取）
            Database.rollback(sp);
/* //迁移ali sushanhu 20231019
            //确认事务 add for pi sushanhu 20220310 start
            // PIHelper.confirmTrans('NFM501',0,null,txId,NFM501AWS.token,NFM501AWS.transactionURL,idList);
            Integer rowDataStr = Integer.valueOf(rowData.get('NFM501Future_Count__c'));
            if (rowDataStr == null) {
                rowDataStr = 0;
            }
            System.debug('rowDataStr' + rowDataStr);
            if (rowDataStr >= batch_retry_max_cnt) {
            	PIHelper.insertConfirmTrans('NFM501',0,null,txId,1,NFM501AWS.transactionURL,idList);
            }
            //PIHelper.insertConfirmTrans('NFM501',0,null,txId,1,NFM501AWS.transactionURL,idList);
            //确认事务 add for pi sushanhu 20220310 end
*/
            System.debug(Logginglevel.ERROR, 'QLMData_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'QLMData_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
            // logstr += '\n' + ex.getMessage();
            iflog501Future.ErrorLog__c = '501Future抛出异常：' + ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog501Future.ErrorLog__c;
            if (!Manual_execution501future) {
                NFM501Controller.againSendExceptionRequest(iflog501Future, 'NFM501Future_Count__c', rowData, '501Future抛出异常：' + ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '错误次数已经超过自动收信设定的最大次数，请手动收信');
            }
            //System.debug(ANY o);
        }
        update rowData;
        System.debug('+++++++5+++++++' + rowData);
        System.debug('+++++++3+++++++' + iflog501Future.Log__c);
        System.debug('+++++++2+++++++' + iflog501Future.ErrorLog__c);
        //如果存入信息超出限制，用省略号代替
        if (iflog501Future.Log__c.length() > 131072) {
            iflog501Future.Log__c = iflog501Future.Log__c.subString(0, 131065) + ' ...';
        }
        if (iflog501Future.ErrorLog__c.length() > 32768) {
            iflog501Future.ErrorLog__c = iflog501Future.ErrorLog__c.subString(0, 32760) + ' ...';
        }
        upsert iflog501Future;
    }
    public static void CurrencySort(List < NFM501Controller.AmountItem > AmountList, Tender_information__c te1, String AmountStr) {
        //如果接收到元，直接存，币种不变
        //如果接收到美元，将美元转换为人名币
        //如果接收到美元和元，只存元
        //如果接受到其他，直接存
        for (Integer i = 0; i < 5; i++) {
            Integer size = i + 1;
            string WAmount = '';
            for (Integer j = 0; j < AmountList.size(); j++) {
                NFM501Controller.AmountItem AmountData = AmountList.get(j);
                if (AmountData.Unit != '') {
                    if (AmountData.Unit.equals('元')) {
                        WAmount = AmountData.Amount;
                        AmountList.remove(j);
                        j--;
                        break;
                    }
                }
            }
            te1.put(AmountStr + size + '__c', WAmount);
        }
    }
    public static void USACurrency(List < NFM501Controller.AmountItem > AmountList, Tender_information__c te1, String AmountStr) {
        //如果接收到元，直接存，币种不变
        //如果接收到美元，将美元转换为人名币
        //如果接收到美元和元，只存元
        //如果接受到其他，直接存
        for (Integer i = 0; i < 5; i++) {
            Integer size = i + 1;
            string WAmount = '';
            for (Integer j = 0; j < AmountList.size(); j++) {
                NFM501Controller.AmountItem AmountData = AmountList.get(j);
                if (AmountData.Unit != '') {
                    if (AmountData.Unit.equals('美元') || AmountData.Unit.equals('$')) {
                        if (AmountData.Amount != null && AmountData.Amount.contains('%')) {
                            WAmount = AmountData.Amount;
                        } else if (AmountData.Amount != null) {
                            WAmount = Decimal.valueOf(AmountData.Amount) * Decimal.valueOf(Label.Account_Exc) + '';
                        }
                        AmountList.remove(j);
                        j--;
                        break;
                    }
                }
            }
            te1.put(AmountStr + size + '__c', WAmount);
        }
    }
    public static void OtherCurrency(List < NFM501Controller.AmountItem > AmountList, Tender_information__c te1, String AmountStr) {
        //如果接收到元，直接存，币种不变
        //如果接收到美元，将美元转换为人名币
        //如果接收到美元和元，只存元
        //如果接受到其他，直接存
        // String UnitStr = String.valueOf(te1.get(unit));
        String WUnit = null;
        for (Integer i = 0; i < 5; i++) {
            Integer size = i + 1;
            string WAmount = '';
            for (Integer j = 0; j < AmountList.size(); j++) {
                NFM501Controller.AmountItem AmountData = AmountList.get(j);
                if (AmountData.Unit != '') {
                    WAmount = AmountData.Amount;
                    WUnit = WUnit == null ? AmountData.Unit : WUnit;
                    AmountList.remove(j);
                    j--;
                    break;
                }
            }
            te1.put(AmountStr + 'Amount' + size + '__c', WAmount);
        }
        te1.put(AmountStr + 'Unit__c', WUnit);
    }
    //只存前五个，有关键字的提前，无关键字的按顺序排，排到第五个（中标单位、招标单位、代理机构）
    public static List < String > ZBU(List < String > Ser, List < String > NewStringList) {
        //1、排序
        for (Integer i = 0; i < 5; i++) {
            for (Integer j = 0; j < Ser.size(); j++) {
                String ZBUData = Ser.get(j);
                if (ZBUData.contains('OCSM') || ZBUData.contains('奥林巴斯') || ZBUData.contains('Olympus')) {
                    NewStringList.add(ZBUData);
                    Ser.remove(j);
                    j--;
                    break;
                }
            }
        }
        System.debug('--------14------' + NewStringList.size());
        System.debug('--------13------' + NewStringList);
        //5个数据中，除关键字外的其余数据
        //(1)如果接口有数据且数据不足五个，则赋接口数据为空
        Integer remainsize = 5 - NewStringList.size();
        for (Integer i = 0; i < remainsize; i++) {
            String ZBData1 = '';
            for (Integer j = 0; j < Ser.size(); j++) {
                string ZBUData = Ser.get(j);
                if (!ZBUData.contains('OCSM') || !ZBUData.contains('奥林巴斯') || !ZBUData.contains('Olympus')) {
                    ZBData1 = ZBUData;
                    Ser.remove(j);
                    j--;
                    break;
                }
            }
            NewStringList.add(ZBData1);
        }
        System.debug('---------12--------' + NewStringList.size());
        System.debug('---------11--------' + NewStringList);
        return NewStringList;
    }
}