global class SendConsumableordertosap {

    WebService static String sendSAP(String orderId) {
        StaticParameter.EscapeConsumableOrderDetail2Trigger = true;
        List<Consumable_order__c> ord = [
            SELECT
                    Id,
                    Name,
                    Dealer_Info__c,
                    Offers_Price__c,
                    CurrencyIsoCode,
                    Contract_application_decision__c,
                    OwnerId,
                    Order_date__c,
                    SalesManager__c,
                    Total_amount__c,
                    SalesManager__r.Province_Text__c,
                    Order_effective_contact__c,
                    Order_ProType__c,
                    Order_effective_contact__r.OSH_Dealer__c, //DB202303088261  安徽两票制 lt 20230314 add
                    IS_Price_Apply__c // 2018/11/05 CHAN-B686DZ  判断是否价格申请
            FROM
                    Consumable_order__c
            WHERE
                    Id = : orderId
            FOR UPDATE
        ];
        if(null == ord || ord.size() == 0) {
            return '没有消耗品订单：' + orderId + '的数据。';
        }
        Map<Id,String> productCampaign = new Map<Id,String>();
        List<Consumable_Orderdetails__c> odrDetails = [
            SELECT
                    Id,
                    Name,
                    Consumable_product__c,
                    Consumable_product__r.Product2__c,
                    Consumable_product__r.Name__c,
                    Consumable_product__r.Estimation_Entry_Possibility__c,
                    Consumable_product__r.SFDA_Status__c,
                    Consumable_product__r.Intra_Trade_List_RMB__c,
                    Consumable_product__r.Product2__r.Important_product__c,
                    Consumable_count__c,
                    Sum_of_money__c,
                    Intra_Trade_List_RMB__c,
                    Special_Campaign_Price__c
            FROM
                    Consumable_Orderdetails__c
            WHERE
                    Consumable_order__c =: orderId
                    ORDER BY Name
        ];

        if(null == odrDetails || odrDetails.size() == 0) {
            return '消耗品订单：' + orderId + '没有明细数据。';
        }
        for(Consumable_Orderdetails__c det1 : odrDetails){
            if(det1.Special_Campaign_Price__c != null){
                productCampaign.put(det1.Consumable_product__c, det1.Consumable_product__r.Name__c);
            }
        }

        List<Account> ordContract =[
            SELECT
                    Id,
                    Name,
                    Contract_Decide_Start_Date__c,
                    Contract_Decide_End_Date__c,
                    Agent_Ref__c,
                    OSH_Dealer__c, //DB202303088261  安徽两票制 lt 20230314 add
                    RecordtypeId
            FROM
                    Account
            WHERE
                    Contract_Decide_Start_Date__c <= :ord[0].Order_date__c AND
                    Contract_Decide_End_Date__c >= :ord[0].Order_date__c AND
                    Agent_Ref__c = :ord[0].Dealer_Info__c AND
                    RecordtypeId = :System.Label.Consumable_Contract AND
                    Id = :ord[0].Order_effective_contact__c
            Order by  Contract_Decide_Start_Date__c desc

        ];
        if(null == ordContract || ordContract.size() == 0){
            return '经销商：' + ord[0].Dealer_Info__c + '没有最新合同。';
        }
        Map<Id,Decimal> productdataMap = new Map<Id,Decimal>();
        //已存在的产品有效促销信息
        List<Dealer_Product__c> dealerProductList = [select Id, Dealer_Product2__c,Dealer_Contact__c,
                                                        Special_Campaign_Price__c,Campaign_StartDate__c,
                                                        Campaign_EndDate__c
                                                    FROM Dealer_Product__c
                                                    WHERE Dealer_Contact__c = :ordContract[0].Id
                                                    AND Campaign_StartDate__c <= :Date.today()
                                                    AND Campaign_EndDate__c >= :Date.today()];
        for(Dealer_Product__c dp :dealerProductList ){
            productdataMap.put(dp.Dealer_Product2__c, dp.Special_Campaign_Price__c);
        }
        for(Id widget : productCampaign.keySet()) {
            if(productdataMap.containsKey(widget)){
                continue;
            }else{
                return '订单产品：' + productCampaign.get(widget) + '促销已经无效。';
            }
        }

        List<Id> product2Ids = new List<Id>();
        List<String> product2EstimationIds = new List<String>();
        for(Consumable_Orderdetails__c detail : odrDetails) {
            product2Ids.add(detail.Consumable_product__r.Product2__c);
            if(detail.Consumable_product__r.Estimation_Entry_Possibility__c != '○'){
                product2EstimationIds.add(detail.Consumable_product__r.Name__c);
            }
        }
        if(product2EstimationIds.size() > 0){
            return '产品：' + product2EstimationIds + '无效，无法执行WIN操作。';
        }

        //String strRet = OpportunityWebService.checkProRegisterDecide(productCampaign, ord[0].Dealer_Info__c, '');
        //if(strRet != 'OK'){
        //    return strRet;
        //}


        // GZW 提交产品无效 出错误消息
        Map<String,String> chkMap = OpportunityWebService.MapCheckProRegisterDecide(productCampaign, ord[0].Dealer_Info__c, '');
        if(chkMap.size() > 0){
            if(chkMap.containsKey('agency')){
                return '第一经销商没有有效的医疗器械经营许可证。';
            }
            for(String proId : productCampaign.keySet()){
                if(chkMap.containsKey(proId)){
                    if(chkMap.get(proId) == '1'){
                        return  '产品 ' + productCampaign.get(proId) + ' 没有有效的注册证。';
                    }else if(chkMap.get(proId) == '2'){
                        return  '产品 ' + productCampaign.get(proId) + ' 超过经销商经营范围。';
                    }
                }
            }
            //return null;
        }

        Savepoint sp = Database.setSavepoint();
        try {
            Opportunity opp = new Opportunity();
                opp.Name                     = ord[0].Name;
                opp.Opportunity_No__c        = ord[0].Name;
                //TODO account
                opp.AccountId                = ordContract[0].Id;
                // TODO 医院
                opp.Agency1__c               = ord[0].Dealer_Info__c;
                opp.Hospital__c              = ordContract[0].Id;

                if(ord[0].Order_ProType__c == 'ET'){
                    opp.Opportunity_Category__c  = 'ET';
                    opp.Opp_order_Type__c        = 'ET';
                    opp.ET_SP_Consumption__c     = true;
                }else{
                    opp.Opportunity_Category__c  = 'GS';
                    opp.Opp_order_Type__c        = 'ENG';
                    //opp.ENG_Consumption__c       = true;
                }
                //opp.Opportunity_Category__c  = 'ET';
                opp.Strategic_department_new__c = '消化科';
                //CHAN-B6QBS8  ET/SP耗材勾选分开，增加ENG耗材勾选
                //opp.ET_SP_Consumption__c     = true;
                opp.Sales_Root__c            = '販売店';
                opp.Fund_Basis__c            = '病院資金';
                opp.StageName                = '引合';
                opp.Purchase_Type__c         = 'ET24時間販売';
                opp.Promise_Class__c         = '内貿';
                opp.Close_Forecasted_Date__c = ord[0].Order_date__c;
                //CHAN-B42D6F 安徽ET特约经销商来的询价  SAP上传省 紧急对应为北京 以后会修改 TODO
                //CHAN-BTF64C 安徽ENG经销商的询价默认SAP上传省修改 update by rentongxiao 2020-09-14 
                // if(ord[0].SalesManager__r.Province_Text__c == '安徽省'){

                //DB202303088261  安徽两票制 lt 20230314 start  ord[0].SalesManager__r.Province_Text__c == '安徽省' && 
                if(ord[0].Order_effective_contact__r.OSH_Dealer__c == TRUE){
                    opp.SAP_Province__c = 'OSH-安徽省';
                    // System.debug('---lt123---SAP上传省1---'+opp.SAP_Province__c);
                }
                else 
                //DB202303088261  安徽两票制 lt 20230314 end
                if(ord[0].SalesManager__r.Province_Text__c == '安徽省' && opp.Opportunity_Category__c == 'ET'){
                    opp.SAP_Province__c = '北京市';
                }else{
                    opp.SAP_Province__c          = ord[0].SalesManager__r.Province_Text__c;
                }
                opp.Purchase_Reason__c       = '新期';
                opp.Estimation_Decision__c   = true;
                // SWAG-C3F59K 20210602 Start
                //opp.Sales_Method__c          = '院内招标';
                opp.Sales_Method__c          = '耗材采购';
                opp.ifOpenBid__c = '非公开招标';
                opp.LeadSource = '经销商';
                // SWAG-C3F59K 20210602 End
                //opp.Opportunity_stage__c     = '还没申请预算';
                opp.Opportunity_stage__c     = '中标签约';
                opp.OwnerId                  = ord[0].SalesManager__c;
                //TODO 报价ID
                opp.Estimation_Id__c         = ord[0].Id;
                opp.CloseDate                = Date.today().addDays(30);
                if(ord[0].Offers_Price__c <= 0  || ord[0].Offers_Price__c == null){
                    opp.Wholesale_Price__c   = ord[0].Total_amount__c;
                    opp.OCM_Agent1_Price__c  = ord[0].Total_amount__c;
                }else{
                    opp.Wholesale_Price__c   = ord[0].Offers_Price__c;
                    opp.OCM_Agent1_Price__c  = ord[0].Offers_Price__c;
                }
                opp.NotesApprovedNo__c       =  ord[0].Contract_application_decision__c;
                //TODO  Authorized_DB_No__c
                opp.Authorized_DB_No__c      = ord[0].Name;
                // 2018/11/05 CHAN-B686DZ  是否价格申请这个标识也请传输到生成的询价中 start
                opp.IS_Price_Apply__c        = ord[0].IS_Price_Apply__c;
                //if(ord[0].Order_ProType__c == 'ENG'){
                //    opp.IS_Price_Apply__c    = '是';
                //}
                // 2018/11/05 CHAN-B686DZ  是否价格申请这个标识也请传输到生成的询价中 end
                System.debug('oppren-----::'+opp);
            insert opp;
            List<PriceBookEntry> priceBookList = [
                SELECT
                        Id,
                        Product2Id, 
                        Product2.Id, 
                        Product2.Name 
                FROM
                        PriceBookEntry 
                WHERE
                        Product2Id IN: product2Ids 
                AND     CurrencyIsoCode = :ord[0].CurrencyIsoCode
                AND     IsActive=true
            ];

            List<OpportunityLineItem> olis = new List<OpportunityLineItem>();
            Integer i=1;
            for(Consumable_Orderdetails__c detail : odrDetails) {
                OpportunityLineItem oli = new OpportunityLineItem();
                oli.OpportunityId = opp.Id;
                oli.Quantity = detail.Consumable_count__c;
                oli.UnitPrice = detail.Intra_Trade_List_RMB__c;
                oli.UnitPrice__c  = detail.Intra_Trade_List_RMB__c;
                oli.OCM_Sales_Forecast__c = detail.Sum_of_money__c;
                //oli.TotalPrice__c = detail.Sum_of_money__c;
                oli.SFDA_Status__c= detail.Consumable_product__r.SFDA_Status__c;
                oli.Name__c       = detail.Consumable_product__r.Name__c;
                oli.ListPrice__c  = detail.Consumable_product__r.Intra_Trade_List_RMB__c;
                oli.Important_Rroduct__c = detail.Consumable_product__r.Product2__r.Important_product__c;
                oli.Item_Order__c = i;
                for(PriceBookEntry pbe: priceBookList) {
                    if(pbe.Product2.Id == detail.Consumable_product__r.Product2__c) {
                        oli.PriceBookEntryId = pbe.Id;
                        break;
                    }
                }
                 i++;
                olis.add(oli);
            }
            insert olis;
            // 2018/11/05 CHAN-B686DZ  如果选择是，生成的询价不直接win， 助理要进行手动WIN操作,设置这条询价是来自追溯系统 start
            // 2019/06/03 CHAN-BCPDGG  紧急重要：能量耗材追溯订单的合同申请控制
            //if(!'是'.equals(ord[0].IS_Price_Apply__c) && !'ENG'.equals(ord[0].Order_ProType__c)){
            if(!'是'.equals(ord[0].IS_Price_Apply__c)){
                 opp.SAP_Send_OK__c = true;
                
            }else{
                opp.Estimation_Decision__c   = true;
            }
            opp.OpportunitySource__c    = '消耗品系统';
            update opp;
            // 2018/11/05 CHAN-B686DZ  如果选择是，生成的询价不直接win， 助理要进行手动WIN操作 end

            List<Opportunity> oppdate = [SELECT Id,Name FROM Opportunity WHERE Name = :ord[0].Name];
            Consumable_order__c cOrder = new Consumable_order__c(Id = orderId);
            cOrder.Opportunity__c = opp.Id;
            cOrder.Approval_Date__c = Date.today();
            update cOrder;

            return '';
        } catch (DmlException de) {
            Database.rollback(sp);
            throw de;
        } catch (Exception e) {
            Database.rollback(sp);
            throw e;
        }
    }
}