/**
 * 招标项目-标的物更新规则修改
 * 历史数据处理用Batch
 * 
 * Created By ssm 2022-06-26
 */
global class NFM501TIDetailHistoryDataBatch implements Database.Batchable<sObject>, Database.Stateful {
    
    private String start_date;

    private String end_date;

    private String batch_if_log_id;

    private List<BatchIF_Log__c> batchlogs;

    global NFM501TIDetailHistoryDataBatch() {
        this.start_date = '2022-04-01';
    }

    global NFM501TIDetailHistoryDataBatch(String startat, String endat) {
        this.start_date = startat;
        this.end_date = endat;
    }

    global NFM501TIDetailHistoryDataBatch(String logid) {
        this.batch_if_log_id = logid;
    }

    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = '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 Type__c = \'NFM501\' and RowDataFlg__c = true and OwnerId = \''+System.label.account_web_1+'\' ';
        if (String.isNotBlank(this.start_date)) {
            query += ' and CreatedDate >= ' + this.start_date + 'T00:00:00.000+0800'; 
        }
        if (String.isNotBlank(this.end_date)) {
            query += ' and CreatedDate <= ' + this.end_date + 'T00:00:00.000+0800'; 
        }
        if (String.isNotBlank(this.batch_if_log_id)) {
            query += ' and Id = \'' + this.batch_if_log_id + '\'';
        }
        query += ' order by CreatedDate';
        System.debug('query is [' + query + ']');
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<BatchIF_Log__c> loglist){
        this.batchlogs = new List<BatchIF_Log__c>();

        // 循环log，获取中标通知的信息
        for (BatchIF_Log__c rowData : loglist) {
            // 创建一个新的日志
            BatchIF_Log__c batch_log = new BatchIF_Log__c();
            batch_log.Type__c = 'NFM501TIDetailHistory';
            batch_log.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
            this.batchlogs.add(batch_log);

            // 处理千里马数据
            try {
                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) {
                    continue;
                }
                // 遍历
                List < String > projectIdList = new List <String>();
                for (NFM501Controller.ListItem project: getQLMData1.data.list1) {
                    if (String.isNotBlank(project.projectId) && '3'.equals(project.infoType) && '11'.equals(project.infoTypeSegment)) {
                        projectIdList.add(project.projectId);
                    }
                }
                // 记录项目Id信息
                batch_log.Log__c = 'get ' + projectIdList.size() + ' products.' + '\n';
                for (String projectId : projectIdList) {
                    batch_log.Log__c += projectId + '\n';
                }
                // 取招标信息
                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 20231017 sushanhu
                    FROM Tender_information__c Where ProjectId__c in :projectIdList
                ];
                Map < String, Tender_information__c > TenMap = new Map < String, Tender_information__c > ();
                for (Tender_information__c Ten: TIList) {
                    TenMap.put(Ten.ProjectId__c, Ten);
                }
                System.debug('tenMap' + TenMap.keySet());
                List<Tender_information_details__c> newTempList = new List<Tender_information_details__c>();
                Map<String, String> updateProjects = new Map<String, String>();
                for (NFM501Controller.ListItem LI: getQLMData1.data.list1) {
                    Tender_information__c te1 = new Tender_information__c();
                    //确定每条数据对应的每个招投标(原来的数据)
                    if (TenMap.containsKey(LI.projectId)) {
                        te1 = TenMap.get(LI.projectId);
                    }
                    System.debug('projectId from log: ' + LI.projectId);
                    System.debug('tender from map: ' + te1);
                    if (String.isBlank(te1.Id)) {
                        continue;
                    }
                    NFM501Controller.Target TG = LI.Target;
                    if (LI.Target != null) {
                        if (TG.Sum != null && TG.Sum != '') {
                            te1.Sum__c = TG.Sum;
                        }
                        te1.SumUnit__c = TG.SumUnit;
                        //招标信息详情
                        if (TG.TargetDetails != null && TG.TargetDetails.size() > 0) {
                            updateProjects.put(LI.projectId, LI.projectId);
                            for (NFM501Controller.TargetDetailsItem TDI: TG.TargetDetails) {
                                Tender_information_details__c te = new Tender_information_details__c();
                                te.Tender_information__c = te1.ID;
                                te.Model__c = String.isBlank(TDI.model) ? te.Model__c : TDI.model;
                                te.NumberUnit__c = String.isBlank(TDI.number1) ? te.NumberUnit__c : TDI.number1;
                                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.isBlank(TDI.name)) {
                                    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;
                                te.ProjectId__c = te1.ProjectId__c;
                                te.Is_Final__c = true;

                                newTempList.add(te);
                            }
                        }
                    }
                }
                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 :updateProjects.keySet()];
                if (DetlList.size() > 0) {
                    delete DetlList;
                }
                if (newTempList.size() > 0) {
                    insert newTempList;
                }
            } catch (Exception e) {
                batch_log.ErrorLog__c = e.getMessage();
            }   
        }
    }

    global void finish(Database.BatchableContext BC) {
        if (this.batchlogs != null && this.batchlogs.size() > 0) {
            insert this.batchlogs;
        }
    }

                     
}