//NFM511 新建众成数据 更新到 招标项目和标的物
//招标项目：bid-projectId(bid为创建招标项目的唯一标记)  没有insert(记录类型:众成)  有update
//标 的 物：insert
public without sharing class ZCTenderHandler extends Oly_TriggerHandler {
    private Map<Id, ZCData__c> newMap;
    private Map<Id, ZCData__c> oldMap;
    private List<ZCData__c> newList;
    private List<ZCData__c> oldList;

    public ZCTenderHandler() {
        this.newMap = (Map<Id, ZCData__c>) Trigger.newMap;
        this.oldMap = (Map<Id, ZCData__c>) Trigger.oldMap;
        this.newList = (List<ZCData__c>) Trigger.new;
        this.oldList = (List<ZCData__c>) Trigger.old;
    }

    protected override void afterInsert() {
        updateTender();  
        // updateFA();
    }

    Map<String,String> tendMap = new Map<String,String>();

    //新建(更新)招标项目  
    private void updateTender(){
        List<String> tenproIdList = new List<String>();  //bid
        List<String> tenproIdList1 = new List<String>(); //sfdc code  ...TenderManageCode__c
        List<String> tennumList = new List<String>();    //项目编号projectNo__c - XmNumber__c
        List<Tender_information__c> tenderList = new List<Tender_information__c>();
        

        //新建(更新)招标项目 
        for(ZCData__c zc : newList){
            if(Date.valueOf(zc.modifyTime__c) < Date.today()){
                continue;
            }
            if(String.isBlank(zc.bid__c) == false){
                tenproIdList.add(zc.bid__c);
            }
            if(String.isBlank(zc.sfdcCode__c) == false){
                tenproIdList1.add(zc.sfdcCode__c);
            }
            if(String.isBlank(zc.projectNo__c) == false){
                tennumList.add(zc.projectNo__c);
            }
            
            Tender_information__c ten = new Tender_information__c();
            ten.RecordTypeId = System.Label.ZCrecordTypeId;
            // ten.ProjectId__c        = zc.bid__c;  //20231016
            ten.ZCProjectId__c      = zc.bid__c;   //20231016
            ten.ZCInfoId__c         = zc.winningDetailId__c + ''; //20231017
            ten.TenderManageCode__c = zc.sfdcCode__c;
            ten.InfoTitle__c        = zc.title__c;
            ten.name                = zc.title__c.length() >75 ? zc.title__c.substring(0, 75) : zc.title__c;
            ten.XmNumber__c         = zc.projectNo__c;
            ten.original_url__c     = zc.originalUrl__c;
            ten.ZhaoBiaoUnit1__c    = zc.tenderee__c;
            ten.AreaProvince__c     = zc.province__c;
            ten.AreaCity__c         = zc.city__c;
            ten.AreaCountry__c      = zc.district__c;
            ten.ZhongBiaoUnit1__c   = zc.supplier__c;
            ten.WinnerAmount1__c    = zc.projectTotalPrice__c;
            // ten.Bid_Winning_Date__c = Date.valueOf(zc.publishTime__c);
            ten.Bid_Winning_Date__c = String.isBlank(zc.publishTime__c) ? Date.valueOf(zc.modifyTime__c).addDays(-1) : Date.valueOf(zc.publishTime__c); //20240104
            ten.host_if__c          = zc.hostIf__c;
            ten.funding_source__c   = zc.fundingSource__c;
            ten.url__c              = zc.url__c;
            // ten.InfoQianlimaUrl__c  = zc.url__c; //源网址
            //20240105 lt start 
            if (!String.isBlank(zc.project_judge_id__c)){
                ten.project_judge_id__c = zc.project_judge_id__c;
            }
            //20240105 lt end
            ten.ZCUpdateDate__c     = Date.today();

            //项目阶段，阶段补充说明 BatchIF転送表
            BatchIF_Log__c iflog = new BatchIF_Log__c();
            iflog.Type__c = '511ZCHandler';
            iflog.Log__c = 'upsert tender start\n';
            iflog.ErrorLog__c = '';
            insert iflog;

            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);
            }

            ten.InfoType__c = NFMUtil.getMapValue(transferMap, 'InfoType__c', zc.noticeType__c, iflog);
            ten.subInfoType__c = NFMUtil.getMapValue(transferMap, 'subInfoType__c', zc.progress__c, iflog);
            
            if(zc.noticeType__c == '中标结果' && (zc.progress__c == '单一来源' ||zc.progress__c == '变更')){
                ten.subInfoType__c = '3-5：中标通知';
            }
            if(zc.noticeType__c == '合同验收' && (zc.progress__c == '单一来源' ||zc.progress__c == '变更')){
                ten.subInfoType__c = '3-6：合同公告';
            }

            //20240104 优化 start
            // if(ten.subInfoType__c == '3-5：中标通知' || ten.subInfoType__c == '3-6：合同公告'){
            //     ten.ResultDate__c = String.isBlank(zc.publishTime__c) ? Date.valueOf(zc.modifyTime__c) : Date.valueOf(zc.publishTime__c);
            // }

            if(ten.subInfoType__c != '3-1：废标公告' && ten.subInfoType__c != '3-2：流标公告'){
                ten.ResultDate__c = String.isBlank(zc.publishTime__c) ? Date.valueOf(zc.modifyTime__c).addDays(-1) : Date.valueOf(zc.publishTime__c);
            }
            //20240104 优化 end
            
            // if(ten.subInfoType__c == '2-1：招标公告'){
            //     ten.InfoType__c = '2：公告';
            // }
            // if(ten.subInfoType__c == '4-1：信息变更'){
            //     ten.InfoType__c = '4：变更';
            // }
            //项目阶段，阶段补充说明 BatchIF転送表

            // //项目阶段
            // if(zc.noticeType__c == '合同验收' || zc.noticeType__c == '中标结果'){
            //     ten.InfoType__c = '3：结果';
            // }
            // //阶段补充说明
            // if(zc.progress__c == '单一来源'){
            //     ten.subInfoType__c = '2-1：招标公告';
            // }
            // if(zc.progress__c == '流标'){
            //     ten.subInfoType__c = '3-2：流标公告';
            // }
            // if(zc.progress__c == '中标' || zc.progress__c == '中标候选'){
            //     ten.subInfoType__c = '3-5：中标通知';
            // }
            // if(zc.progress__c == '验收' || zc.progress__c == '合同' || zc.progress__c == '成交'){
            //     ten.subInfoType__c = '3-6：合同公告';
            // }
            // if(zc.progress__c == '变更'){
            //     ten.subInfoType__c = '4-1：信息变更';
            // }
            

            tenderList.add(ten);
            
        }

        List<Tender_information__c> UpdateTenderList = [
            //InfoType__c 项目阶段，对应关系需进一步确认(,url__c,original_url__c暂时不要)
            Select id,name,ZCProjectId__c,InfoTitle__c,XmNumber__c,
                   ZhaoBiaoUnit1__c,AreaProvince__c,AreaCity__c,AreaCountry__c,
                   ZhongBiaoUnit1__c,WinnerAmount1__c,Bid_Winning_Date__c,
                   funding_source__c,url__c,RecordTypeId,TenderManageCode__c,AWS_Data_Id__c,
                   ZCDataUpdate__c,ResultDate__c  
            From Tender_information__c 
            Where ZCProjectId__c in :tenproIdList 
            OR TenderManageCode__c in :tenproIdList1
            // OR (XmNumber__c in :tennumList AND ZCDataUpdate__c = false)  //20240122 
        ];

        String QLMrecordId = Schema.SObjectType.Tender_information__c.getRecordTypeInfosByDeveloperName().get('QLM').getRecordTypeId();

        System.debug('---lt12345---UpdateTenderList:'+UpdateTenderList);
        System.debug('---lt12345---tenderList:'+tenderList);
        if(tenderList.size() > 0){
            if(UpdateTenderList.size() > 0 ){
                for(Tender_information__c uten: UpdateTenderList){
                    for(Tender_information__c ten :tenderList){
                        //20231016 ProjectId__c--ZCProjectId__c
                        //20240122 lt delete || uten.XmNumber__c == ten.XmNumber__c
                        if(uten.ZCProjectId__c == ten.ZCProjectId__c || uten.TenderManageCode__c == ten.TenderManageCode__c){
                            System.debug('---lt12345-2---');
                            ten.Id = uten.Id;
                            ten.AWS_Data_Id__c = uten.AWS_Data_Id__c;
                            ten.TenderManageCode__c = uten.TenderManageCode__c;
                            ten.AreaProvince__c = String.isBlank(uten.AreaProvince__c) ? ten.AreaProvince__c : uten.AreaProvince__c;
                            ten.AreaCity__c = String.isBlank(uten.AreaCity__c) ? ten.AreaCity__c : uten.AreaCity__c;
                            ten.AreaCountry__c = String.isBlank(uten.AreaCountry__c) ? ten.AreaCountry__c : uten.AreaCountry__c;
                            ten.ResultDate__c = String.isBlank(String.valueOf(uten.ResultDate__c)) ? ten.ResultDate__c : uten.ResultDate__c;
                            ten.Bid_Winning_Date__c = String.isBlank(String.valueOf(uten.Bid_Winning_Date__c)) ? ten.Bid_Winning_Date__c : uten.Bid_Winning_Date__c;
                            System.debug('---lt12345-3---QLMrecordId:'+QLMrecordId);
                            System.debug('---lt12345-3---uten.RecordTypeId：'+uten.RecordTypeId);
                            if(uten.RecordTypeId == QLMrecordId){
                                System.debug('---lt12345-3---');
                                ten.ZCDataUpdate__c = true;
                                ten.RecordTypeId = QLMrecordId;
                            }
                        }
                    }
                }
            }
            System.debug('---lt12345---tenderList111:'+tenderList);
            StaticParameter.EscapeZCUpdateTender = true;
            upsert tenderList;
            StaticParameter.EscapeZCUpdateTender = false;
        }

        

        //新建标的物
        List<Tender_information_details__c> tenderDetList = new List<Tender_information_details__c>();

        if(tenderList.size() > 0){
            for(Tender_information__c ten :tenderList){
                tendMap.put(ten.ZCProjectId__c,ten.Id);  //20231016 ProjectId__c--ZCProjectId__c
            }
        }
        System.debug('---20231010---tendMap:'+tendMap);
        //删除招标项目下原来的标的物
        Date today = Date.today();
        List<String> TenIdList = tendMap.values();
        System.debug('---20231010---TenIdList:'+TenIdList);
        //1.创建日不等于今天  or   2.来源不是众成
        List<Tender_information_details__c> delTenderDetList = [
            Select id,name,CreatedDate,source__c,Tender_information__c 
            From Tender_information_details__c 
            Where Tender_information__c in :TenIdList
            And (CreatedDate != LAST_N_DAYS:0 Or source__c != '众成')
        ];

        System.debug('---20231010---delTenderDetList:'+delTenderDetList);
        if(delTenderDetList.Size()>0){
            delete delTenderDetList;
        }
        //删除招标项目下原来的标的物

        for(ZCData__c zc : newList){
            if(Date.valueOf(zc.modifyTime__c) < Date.today()){
                continue;
            }
            Tender_information_details__c tends = new Tender_information_details__c();
            
            if(tendMap.containsKey(zc.bid__c)){
                tends.Tender_information__c =  tendMap.get(zc.bid__c);
            }
            tends.name                 = zc.contractObject__c.length() > 75 ? zc.contractObject__c.substring(0, 75) : zc.contractObject__c;
            tends.Name__c              = zc.contractObject__c;
            tends.Brand__c             = zc.brand__c;
            tends.brand_type__c        = zc.brandType__c;
            tends.Model__c             = zc.speci__c;
            tends.Price__c             = String.valueOf(zc.bidUnitPrice__c);
            tends.Number__c            = zc.bidQuantity__c;
            tends.TotalPriceUnit__c    = String.valueOf(zc.bidTotalPrice__c);
            tends.one_class__c         = zc.oneClass__c;
            tends.two_class__c         = zc.twoClass__c;
            tends.three_class__c       = zc.threeClass__c;
            tends.source__c            = '众成';
            tends.winning_detail_id__c = String.valueOf(zc.winningDetailId__c); //20231018
            //  + ''; 

            tenderDetList.add(tends);
        }

        if(tenderDetList.Size() > 0){
            insert tenderDetList;
        }
    }

    // private void updateFA(){
    //     //新建 文件地址
    //     List<FileAddress__c> faList = new List<FileAddress__c>();
    //     List<FileAddress__c> faList1 = new List<FileAddress__c>();
        
    //     for(ZCData__c zc : newList){
    //         FileAddress__c fa = new FileAddress__c();
    //         FileAddress__c fa1 = new FileAddress__c();
    //         if(tendMap.containsKey(zc.bid__c)){
    //             fa.ParentRecordId__c =  tendMap.get(zc.bid__c);
    //             fa1.ParentRecordId__c =  tendMap.get(zc.bid__c);
    //         }
    //         // fa.ViewLink__c = zc.url__c;
    //         // fa.DownloadLink__c = zc.url__c;
    //         faList.add(fa);

    //         fa1.ViewLink__c = zc.originalUrl__c;
    //         fa1.DownloadLink__c = zc.originalUrl__c;
    //         faList1.add(fa1);
    //     }

    //     if(faList.Size() > 0){
    //         insert faList;
    //     }
    //     if(faList1.Size() > 0){
    //         insert faList1;
    //     }
    // }


}