public without sharing class OrderPdf2Controller {
    public HeaderInfo header { get; set; }
    public List<List<DetailInfo>> pageDetails { get; set; }
    public String productSegment { get; set; }

    public List<DetailInfo> inputDetails { get; set; }

    public Order order { get; set; }
    // 买方
    public Account buyer { get; set; }
    // 收货方
    public Account delivery { get; set; }
    public Contact delivery_contact { get; set; }
    // 最终用户
    public Account user { get; set; }
    public Contact contact { get; set; }

    public String id;
    public String baseUrl { get; set; }
    public String strToday { get; set; }
    public boolean is_parts_direct { get; set; }
    public boolean is_ie_direct { get; set; }

    public Integer pageCnt { get; set; }
    public boolean fistPageBreak { get; set; }
    public boolean lastPageBreak { get; set; }

    private Integer firstCnt = 10;
    private Integer firstMaxCnt = 24;
    private Integer eachCnt = 48;
    private Integer lastMaxCnt = 35;

    private Integer iRfirstCnt = 9;
    private Integer iRfirstMaxCnt = 23;
    private Integer iReachCnt = 48;
    private Integer iRlastMaxCnt = 30;

    private Integer nAfirstCnt = 9;
    private Integer nAfirstMaxCnt = 23;
    private Integer nAeachCnt = 48;
    private Integer nAlastMaxCnt = 30;

    public String seller_name1 { get; set; }
    public String seller_address1 { get; set; }
    public String seller_city1 { get; set; }
    public String seller_province1 { get; set; }
    public String seller_phone1 { get; set; }

    public String seller_name2 { get; set; }
    public String seller_address2 { get; set; }
    public String seller_city2 { get; set; }
    public String seller_province2 { get; set; }
    public String seller_phone2 { get; set; }

    public boolean is_hidden_user { get; set; }
    public boolean is_dealer_user { get; set; }

    public Decimal dis {get;set;}

    public String ndt_name{get;set;}
    public String ndt_email{get;set;}
    public String ndt_number{get;set;}
    public String ndt_fax{get;set;}

    public Boolean notSpecialDealer { get; set; }

    public OrderPdf2Controller() {
        id = ApexPages.currentPage().getParameters().get('id');

        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        String path = URL.getCurrentRequestUrl().getPath();
        if (path.indexOf('/apex') > 0) {
            baseUrl += path.substring(0,path.indexOf('/apex'));
        } else if (path.indexOf('production/') > 0) {
            baseUrl += '/production';
        }

        Date today = Date.today();
        strToday = today.format();
    }

    public PageReference init() {
        notSpecialDealer = true;
        if (id == null || id.length() == 0) {
            return null;
        }

        is_hidden_user = false;
        // String profileid = UserInfo.getProfileId().subString(0,15);

        //新的获取简档ID  calendarUtil.getMemberProfileID  这里用到的人员ID 和获取到的简档ID都是15位的
        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));

        if (new_profileId.substring(0, 15) == System.Label.RT_BS_No_Price) {
            is_hidden_user = true;
        }
        is_dealer_user = false;
        if (UserInfo.getUserType() == 'PowerPartner') {
            is_dealer_user = true;
        }

        order = new Order();
        List<Order> orderList = [select Id, AccountId, OpportunityId, Opportunity.Dealer__c, Opportunity.SpecialDeliveryAddress__c, Opportunity.SpecialDeliveryContact__c,Opportunity.InquiryNumber__c,
                                        PDF_S_Name__c, PDF_S_Address__c, PDF_S_City__c, PDF_S_Province__c, PDF_S_Phone__c,Opportunity.CreatedBy.ContactId,CreatedBy.ContactId,
                                        Name, Opportunity.ExpectedDeliveryDate__c, PDF_Sap_No__c, OrderNumber, Opportunity.SubDealer__c,
                                        PDF_Property__c, Opportunity.Name, PDF_No__c, Description, PDF_Order_No__c,CrossCooperativeProject__c,
                                        Olympus_Price_BeforeDiscount_D__c, Discount_D__c, OlympusContractPricesD__c, CustomerContractPriceD__c,
                                        Opportunity.ProductSegment__c, Opportunity.SalesChannel__c, Opportunity.Machine_Parts__c,
                                        SpecialDeliveryAccount__c, SpecialDeliveryAccount_D__c, SpecialDeliveryContact2__c, SpecialDeliveryContact2_D__c
                                   from Order where Id = :id];
        if (orderList.size() == 0) {
            return null;
        }
        order = orderList[0];
        dis = order.Discount_D__c;
        productSegment = order.Opportunity.ProductSegment__c;
        is_parts_direct = false;
        is_ie_direct = false;
        if (order.Opportunity.ProductSegment__c == 'IE' && order.Opportunity.SalesChannel__c == 'direct') {
            is_ie_direct = true;
        }
        system.debug(is_ie_direct);
        if (order.Opportunity.SalesChannel__c == 'direct' && order.Opportunity.Machine_Parts__c == 'Parts') {
            is_parts_direct = true;
        }
        /*Contact dealerContact = new Contact();
        if(order.Opportunity.ProductSegment__c == 'NDT' || order.Opportunity.ProductSegment__c == 'ANI'){
            String id = UserInfo.getUserId();
            User user = [select id,ContactID from User where id =: id];
            String conid = user.ContactId;
            dealerContact = [select id, Name,Phone,MobilePhone,Fax,Email from Contact where id =:conid];
        }*/
        buyer = new Account();
        if (order.Opportunity.Dealer__c != null) {
             /*if (order.CrossCooperativeProject__c) {
                buyer = [select Id, Name, Address1__c,Business_license__c, City__c, Province__c, Phone from Account where Id = :order.Dealer_A__c];
            }else{
                buyer = [select Id, Name, Address1__c,Business_license__c, City__c, Province__c, Phone from Account where Id = :order.Opportunity.Dealer__c];
            }*/
            buyer = [select Id, Name, Address1__c,Business_license__c, City__c, Province__c, Phone from Account where Id = :order.Opportunity.Dealer__c];
        }
        notSpecialDealer = !StaticParameter.specialDealerMap.containsKey(((String)order.Opportunity.Dealer__c));
        system.debug('order.Opportunity.Dealer__c' + order.Opportunity.Dealer__c);
        String ndtID = order.CreatedBy.ContactId;
        if(ndtID != null){
            Contact ndtcon =  [select Id, Department, Name, Phone, MobilePhone,Fax,Email from Contact where Id = :ndtID];
            ndt_name = ndtcon.Name;
            ndt_email = ndtcon.Email;
            ndt_number = ndtcon.Phone;
            ndt_fax = ndtcon.Fax;
        }

        delivery = new Account();
        if (order.SpecialDeliveryAccount_D__c != null) {
            delivery = [select Id, Name, Address1__c, City__c, Province__c, Sub_Use__c from Account where Id = :order.SpecialDeliveryAccount_D__c];
        }

        delivery_contact = new Contact();
        if (order.SpecialDeliveryContact2_D__c != null) {
            delivery_contact = [select Id, Department, Name, Phone, MobilePhone,Address1__c from Contact where Id = :order.SpecialDeliveryContact2_D__c];
        }

        user = new Account();
        if (order.AccountId != null) {
            user = [select Id, Name, ManagementCode_F__c, Address1__c,Business_license__c, City__c, Province__c, Sub_Use__c, Phone from Account where Id = :order.AccountId];
        }

        List<OpportunityContactRole> ocrList = [select Id, OpportunityId, IsPrimary, ContactId
                                                  from OpportunityContactRole
                                                 where OpportunityId = :order.OpportunityId
                                                 order by IsPrimary desc];
        String contactid = null;
        if (ocrList.size() > 0) {
            contactid = ocrList[0].ContactId;
        }
        contact = new Contact();
        if (contactid != null && contactid.length() > 0) {
            contact = [select Id, Department, Name, Phone, MobilePhone,Fax,Email from Contact where Id = :contactid];
        }

        List<OrderItem> oiList = [select Id, PriceBookEntry.Product2.ProductCode, PriceBookEntry.Product2.Product_ECCode__c,PriceBookEntry.Product2.Name,PriceBookEntry.Product2.registrationCode__c,
                                         Quantity, UnitPrice, Factory__c, PriceBookEntry.Hidden_flag__c,PriceBookEntry.Product2.Product_CCode__c
                                    from OrderItem
                                   where OrderId = :id
                                   order by QuoteLineItemId,Id];

        if (is_parts_direct == true || is_ie_direct == true) {
            header = new HeaderInfo(order, user, delivery, delivery_contact, user, contact);
        } else {
            header = new HeaderInfo(order, buyer, delivery, delivery_contact, user, contact);
        }
        
        fistPageBreak = false;
        lastPageBreak = false;
        pageCnt = 0;
        pageDetails = new List<List<DetailInfo>>();
        Integer  count = 0;
       
        for (OrderItem oi : oiList) {
            count += getRow(oi);
        }

        if(productSegment == 'IE' || productSegment == 'RVI'){
            if (count <= iRfirstCnt) {
                pageCnt = 1;
            } else if (count > iRfirstCnt && count <= iRfirstMaxCnt) {
                fistPageBreak = true;
                pageCnt = 2;
            } else {
                pageCnt = 1 + (count - iRfirstMaxCnt) / iReachCnt;
                Integer mod = Math.mod(count - iRfirstMaxCnt, iReachCnt);
                if (mod > 0 && mod <= iRlastMaxCnt) {
                    pageCnt += 1;
                } else if (mod > iRlastMaxCnt) {
                    lastPageBreak = true;
                    pageCnt += 2;
                }
            }
        }else if (productSegment == 'NDT' || productSegment == 'ANI') {
            if (count <= nAfirstCnt) {
                pageCnt = 1;
            } else if (count > nAfirstCnt && count <= nAfirstMaxCnt) {
                fistPageBreak = true;
                pageCnt = 2;
            } else {
                pageCnt = 1 + (count - nAfirstMaxCnt) / nAeachCnt;
                Integer mod = Math.mod(count - nAfirstMaxCnt, nAeachCnt);
                if (mod > 0 && mod <= nAlastMaxCnt) {
                    pageCnt += 1;
                } else if (mod > nAlastMaxCnt) {
                    lastPageBreak = true;
                    pageCnt += 2;
                }
            }
        }else {
            if (count <= firstCnt) {
                pageCnt = 1;
            } else if (count > firstCnt && count <= firstMaxCnt) {
                fistPageBreak = true;
                pageCnt = 2;
            } else {
                pageCnt = 1 + (count - firstMaxCnt) / eachCnt;
                Integer mod = Math.mod(count - firstMaxCnt, eachCnt);
                if (mod > 0 && mod <= lastMaxCnt) {
                    pageCnt += 1;
                } else if (mod > lastMaxCnt) {
                    lastPageBreak = true;
                    pageCnt += 2;
                }
            }
        }

        

        Integer nowPage = 1;
        Integer nowLine = 0;
        Integer line = 0;
        List<DetailInfo> details = new List<DetailInfo>();
        for (OrderItem oi : oiList) {
            if (productSegment == 'IE' || productSegment == 'RVI') {
                line += 1;
                nowLine += getRow(oi);
                if (count <= iRfirstMaxCnt) {
                    DetailInfo di = new DetailInfo(line, oi,dis);
                    if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                        di.price = 0;
                        di.totalprice = 0;
                    }
                    details.add(di);
                } else if (nowPage == 1) {
                    if (nowLine <= iRfirstMaxCnt) {
                        DetailInfo di = new DetailInfo(line, oi,dis);
                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                            di.price = 0;
                            di.totalprice = 0;
                        }
                        details.add(di);
                    } else {
                        nowPage += 1;
                        nowLine = 0;
                        pageDetails.add(details);
                        details = new List<DetailInfo>();
                        DetailInfo di = new DetailInfo(line, oi,dis);
                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                            di.price = 0;
                            di.totalprice = 0;
                        }
                        details.add(di);
                    }
                } else {
                    if (nowLine <= iReachCnt) {
                        DetailInfo di = new DetailInfo(line, oi,dis);
                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                            di.price = 0;
                            di.totalprice = 0;
                        }
                        details.add(di);
                    } else {
                        nowPage += 1;
                        nowLine = 0;
                        pageDetails.add(details);
                        details = new List<DetailInfo>();
                        DetailInfo di = new DetailInfo(line, oi,dis);
                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                            di.price = 0;
                            di.totalprice = 0;
                        }
                        details.add(di);
                    }
                }
            }else if (productSegment == 'NDT' || productSegment == 'ANI') {
                line += 1;
                nowLine += getRow(oi);
                if (count <= nAfirstMaxCnt) {
                    DetailInfo di = new DetailInfo(line, oi,dis);
                    if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                        di.price = 0;
                        di.totalprice = 0;
                    }
                    details.add(di);
                } else if (nowPage == 1) {
                    if (nowLine <= nAfirstMaxCnt) {
                        DetailInfo di = new DetailInfo(line, oi,dis);
                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                            di.price = 0;
                            di.totalprice = 0;
                        }
                        details.add(di);
                    } else {
                        nowPage += 1;
                        nowLine = 0;
                        pageDetails.add(details);
                        details = new List<DetailInfo>();
                        DetailInfo di = new DetailInfo(line, oi,dis);
                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                            di.price = 0;
                            di.totalprice = 0;
                        }
                        details.add(di);
                    }
                } else {
                    if (nowLine <= nAeachCnt) {
                        DetailInfo di = new DetailInfo(line, oi,dis);
                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                            di.price = 0;
                            di.totalprice = 0;
                        }
                        details.add(di);
                    } else {
                        nowPage += 1;
                        nowLine = 0;
                        pageDetails.add(details);
                        details = new List<DetailInfo>();
                        DetailInfo di = new DetailInfo(line, oi,dis);
                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                            di.price = 0;
                            di.totalprice = 0;
                        }
                        details.add(di);
                    }
                }
            }else {
                line += 1;
                nowLine += getRow(oi);
                if (count <= firstMaxCnt) {
                    DetailInfo di = new DetailInfo(line, oi,dis);
                    if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                        di.price = 0;
                        di.totalprice = 0;
                    }
                    details.add(di);
                } else if (nowPage == 1) {
                    if (nowLine <= firstMaxCnt) {
                        DetailInfo di = new DetailInfo(line, oi,dis);
                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                            di.price = 0;
                            di.totalprice = 0;
                        }
                        details.add(di);
                    } else {
                        nowPage += 1;
                        nowLine = 0;
                        pageDetails.add(details);
                        details = new List<DetailInfo>();
                        DetailInfo di = new DetailInfo(line, oi,dis);
                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                            di.price = 0;
                            di.totalprice = 0;
                        }
                        details.add(di);
                    }
                } else {
                    if (nowLine <= eachCnt) {
                        DetailInfo di = new DetailInfo(line, oi,dis);
                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                            di.price = 0;
                            di.totalprice = 0;
                        }
                        details.add(di);
                    } else {
                        nowPage += 1;
                        nowLine = 0;
                        pageDetails.add(details);
                        details = new List<DetailInfo>();
                        DetailInfo di = new DetailInfo(line, oi,dis);
                        if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                            di.price = 0;
                            di.totalprice = 0;
                        }
                        details.add(di);
                    }
                }
            }

            


        }

        /*if (oiList.size() <= firstCnt) {
            pageCnt = 1;
        } else if (oiList.size() > firstCnt && oiList.size() <= firstMaxCnt) {
            fistPageBreak = true;
            pageCnt = 2;
        } else {
            pageCnt = 1 + (oiList.size() - firstMaxCnt) / eachCnt;
            Integer mod = Math.mod(oiList.size() - firstMaxCnt, eachCnt);
            if (mod > 0 && mod <= lastMaxCnt) {
                pageCnt += 1;
            } else if (mod > lastMaxCnt) {
                lastPageBreak = true;
                pageCnt += 2;
            }
        }*/
       /* Integer nowPage = 1;
        Integer nowLine = 0;
        Integer line = 0;
        List<DetailInfo> details = new List<DetailInfo>();
        for (OrderItem oi : oiList) {
            line += 1;
            nowLine += 1;
            if (oiList.size() <= firstMaxCnt) {
                DetailInfo di = new DetailInfo(line, oi);
                if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                    di.price = 0;
                    di.totalprice = 0;
                }
                details.add(di);
            } else if (nowPage == 1) {
                if (nowLine <= firstMaxCnt) {
                    DetailInfo di = new DetailInfo(line, oi);
                    if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                        di.price = 0;
                        di.totalprice = 0;
                    }
                    details.add(di);
                } else {
                    nowPage += 1;
                    nowLine = 0;
                    pageDetails.add(details);
                    details = new List<DetailInfo>();
                    DetailInfo di = new DetailInfo(line, oi);
                    if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                        di.price = 0;
                        di.totalprice = 0;
                    }
                    details.add(di);
                }
            } else {
                if (nowLine <= eachCnt) {
                    DetailInfo di = new DetailInfo(line, oi);
                    if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                        di.price = 0;
                        di.totalprice = 0;
                    }
                    details.add(di);
                } else {
                    nowPage += 1;
                    nowLine = 0;
                    pageDetails.add(details);
                    details = new List<DetailInfo>();
                    DetailInfo di = new DetailInfo(line, oi);
                    if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                        di.price = 0;
                        di.totalprice = 0;
                    }
                    details.add(di);
                }
            }
        }*/

        if (fistPageBreak == true) {
            for (Integer i = nowLine + 1; i <= firstMaxCnt; i++) {
                line += 1;
                DetailInfo di = new DetailInfo(line);
                details.add(di);
            }
        } else if (lastPageBreak == true) {
            for (Integer i = nowLine + 1; i <= eachCnt; i++) {
                line += 1;
                DetailInfo di = new DetailInfo(line);
                details.add(di);
            }
        }

        pageDetails.add(details);

        Decimal sum = 0;
        for(List<DetailInfo> difList : pageDetails){
            for (DetailInfo  dif: difList ) {
                if(dif.price_d != null){
                    sum+=dif.price_d;
                }
            }
        }
        if(sum != 0){
            for(List<DetailInfo> difList : pageDetails){
                for (DetailInfo  dif: difList ) {
                    system.debug(header.order_totalprice+'-----'+sum);
                    dif.price_d = dif.price_d + (header.order_totalprice - sum);
                    break;
                }
                break;
            }
        }

        return null;
    }

    private Integer getRow(OrderItem oi){
        Integer row = 1;
        if(oi.PriceBookEntry.Product2.Product_ECCode__c != null){
            if (productSegment == 'ANI' || productSegment == 'NDT'){
                row = oi.PriceBookEntry.Product2.Product_ECCode__c.length()/27 +1 > row ? oi.PriceBookEntry.Product2.Product_ECCode__c.length() == 24 ?1:oi.PriceBookEntry.Product2.Product_ECCode__c.length()/24  +1: row;
            } else if (productSegment == 'IE' || productSegment == 'RVI'){
                row = oi.PriceBookEntry.Product2.Product_ECCode__c.length()/17 +1 > row ? oi.PriceBookEntry.Product2.Product_ECCode__c.length() == 17 ?1:oi.PriceBookEntry.Product2.Product_ECCode__c.length()/17  +1: row;
            } else{
                row = oi.PriceBookEntry.Product2.Product_ECCode__c.length()/11 +1 > row ? oi.PriceBookEntry.Product2.Product_ECCode__c.length() == 11 ?1:oi.PriceBookEntry.Product2.Product_ECCode__c.length()/11  +1: row;
            }
        }
        if(oi.PriceBookEntry.Product2.Product_CCode__c != null){
            row = oi.PriceBookEntry.Product2.Product_CCode__c.length()/12 +1> row ? oi.PriceBookEntry.Product2.Product_CCode__c.length() == 12?1:oi.PriceBookEntry.Product2.Product_CCode__c.length()/12 +1: row;
        }
        if(oi.PriceBookEntry.Product2.Name != null){
            if (productSegment == 'BS') {
                row = oi.PriceBookEntry.Product2.Name.length()/9 +1> row ? oi.PriceBookEntry.Product2.Name.length() == 9 ? 1 : oi.PriceBookEntry.Product2.Name.length()/9 +1: row;
            }else if (productSegment == 'NDT' || productSegment == 'ANI') {
                row = oi.PriceBookEntry.Product2.Name.length()/12 +1> row ? oi.PriceBookEntry.Product2.Name.length() == 12 ? 1 : oi.PriceBookEntry.Product2.Name.length()/12 +1: row;
            }
        }
        if(productSegment == 'BS' && oi.PriceBookEntry.Product2.registrationCode__c != null){
            row = oi.PriceBookEntry.Product2.registrationCode__c.length()/17 +1>row? oi.PriceBookEntry.Product2.registrationCode__c.length() == 15 ? 1 : oi.PriceBookEntry.Product2.registrationCode__c.length()/17 +1 : row;
            system.debug('======'+row+'++++++++++'+oi.PriceBookEntry.Product2.registrationCode__c.length() +'-------'+oi.PriceBookEntry.Product2.registrationCode__c);
        }
        system.debug(oi.PriceBookEntry.Product2.Name+'***********'+row+'***'+oi.PriceBookEntry.Product2.Name.length()+'***'+ (oi.PriceBookEntry.Product2.Name.length()/9 +1));
        
        return row;
    }

    public PageReference init2() {
        notSpecialDealer = true;
        is_hidden_user = false;
        // String profileid = UserInfo.getProfileId().subString(0,15);

        //新的获取简档ID  calendarUtil.getMemberProfileID  这里用到的人员ID 和获取到的简档ID都是15位的
        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
        
        if (new_profileId.substring(0, 15) == System.Label.RT_BS_No_Price) {
            is_hidden_user = true;
        }
        is_dealer_user = false;
        if (UserInfo.getUserType() == 'PowerPartner') {
            is_dealer_user = true;  
        }

        seller_name1 = '奥林巴斯(中国)有限公司';
        seller_address1 = '北京市朝阳区新源南路1-3号平安国际金融中心A座8楼';
        seller_city1 = '北京';
        seller_province1 = '北京';
        seller_phone1 = '010-58199000';

        seller_name2 = '仪景通光学科技（上海）有限公司';
        seller_address2 = '中国（上海）自由贸易试验区日樱北路199-9号102及302部位';
        seller_city2 = '上海';
        seller_province2 = '上海';
        seller_phone2 = '021-58881300';

        header = new HeaderInfo();
        inputDetails = new List<DetailInfo>();
        order = new Order();

        List<Order> orderList = [select Id, AccountId, OpportunityId, Opportunity.Dealer__c, Opportunity.SpecialDeliveryAddress__c, Opportunity.SpecialDeliveryContact__c,
                                        PDF_S_Name__c, PDF_S_Address__c, PDF_S_City__c, PDF_S_Province__c, PDF_S_Phone__c,
                                        Name, Opportunity.ExpectedDeliveryDate__c, PDF_Sap_No__c, OrderNumber, Opportunity.SubDealer__c,
                                        PDF_Property__c, Opportunity.Name, PDF_No__c, Description, PDF_Order_No__c,
                                        Olympus_Price_BeforeDiscount_D__c, Discount_D__c, OlympusContractPricesD__c, CustomerContractPriceD__c,
                                        Opportunity.ProductSegment__c
                                   from Order where Id = :id];
        if (orderList.size() == 0) {
            return null;
        }

        order = orderList[0];
        dis = order.Discount_D__c;
        header.seller_name = order.PDF_S_Name__c;
        header.seller_address = order.PDF_S_Address__c;
        header.seller_city = order.PDF_S_City__c;
        header.seller_province = order.PDF_S_Province__c;
        header.seller_phone = order.PDF_S_Phone__c;
        header.order_sap_no = order.PDF_Sap_No__c;
        //header.user_property_IE = order.PDF_Property__c;
        header.order_no = order.PDF_No__c;
        header.pdf_order_no = order.PDF_Order_No__c;
        //dealerid = order.Opportunity.Dealer__c.subString(0,15)
        notSpecialDealer = !StaticParameter.specialDealerMap.containsKey(((String)order.Opportunity.Dealer__c));
        system.debug('order.Opportunity.Dealer__c' + StaticParameter.specialDealerMap.containsKey(((String)order.Opportunity.Dealer__c)));
        system.debug(!StaticParameter.specialDealerMap.containsKey(((String)order.Opportunity.Dealer__c)));
        productSegment = order.Opportunity.ProductSegment__c;

        //2019-5-20
        if(productSegment == 'IE' && (order.PDF_Property__c == '' || order.PDF_Property__c == null)){
            List<Account> accList = [select id,UserType__c from Account where id = :order.AccountId];
            if(accList.size() > 0 ){
                order.PDF_Property__c = accList[0].UserType__c;
            }
        }

        List<OrderItem> oiList = [select Id, PriceBookEntry.Product2.ProductCode, PriceBookEntry.Product2.Product_ECCode__c,PriceBookEntry.Product2.Name,PriceBookEntry.Product2.Factory__c,Discount__c,
                                         Quantity, UnitPrice, Factory__c, PriceBookEntry.Hidden_flag__c,PriceBookEntry.Product2.Product_CCode__c,PriceBookEntry.Product2.registrationCode__c
                                    from OrderItem
                                   where OrderId = :id
                                   order by QuoteLineItemId, Id];
        Integer line = 0;
        for (OrderItem oi : oiList) {
            line += 1;
            DetailInfo di = new DetailInfo(line, oi,dis);
            if (is_hidden_user == true || is_dealer_user == true && oi.PriceBookEntry.Hidden_flag__c == true) {
                di.price = 0;
                di.totalprice = 0;
            }
            di.factory = oi.PriceBookEntry.Product2.Factory__c;
            inputDetails.add(di);
        }

        //notSpecialDealer = !StaticParameter.specialDealerMap.containsKey(order.Opportunity.Dealer__c);
        return null;
    }

    public PageReference printBtn() {
        PageReference ref = null;
        if (saveFunction() == true) {
            if(productSegment == 'NDT' || productSegment == 'ANI'){
                ref = new Pagereference(baseUrl + '/apex/OrderPdf3?id=' + order.id);
                ref.setRedirect(true);
            }else{
                ref = new Pagereference(baseUrl + '/apex/OrderPdf2?id=' + order.id);
                ref.setRedirect(true);
            }
        }
        return ref;
    }

    public PageReference saveBtn() {
        PageReference ref = null;
        if (saveFunction() == true) {
            ref = new Pagereference(baseUrl + '/apex/OrderContract2?id=' + order.id);
            ref.setRedirect(true);
        }
        return ref;
    }

    public boolean saveFunction() {
        boolean rt = false;

        Order upd_order = new Order();
        upd_order.Id = order.Id;
        upd_order.Name = order.Name;
        upd_order.PDF_S_Name__c = header.seller_name;
        upd_order.PDF_S_Address__c = header.seller_address;
        upd_order.PDF_S_City__c = header.seller_city;
        upd_order.PDF_S_Province__c = header.seller_province;
        upd_order.PDF_S_Phone__c = header.seller_phone;
        upd_order.PDF_Sap_No__c = header.order_sap_no;
        //upd_order.PDF_Property__c = header.user_property_IE;
        upd_order.PDF_Property__c = order.PDF_Property__c;
        upd_order.PDF_No__c = header.order_no;
        upd_order.PDF_Order_No__c = header.pdf_order_no;

        List<OrderItem> upd_oiList = new List<OrderItem>();
        for (DetailInfo inputDetail : inputDetails) {
            OrderItem oi = new OrderItem();
            oi.Id = inputDetail.orderItem.Id;
            oi.Factory__c = inputDetail.factory;
            upd_oiList.add(oi);
        }

        Savepoint sp = Database.setSavepoint();
        try {
            update upd_order;
            update upd_oiList;
           
            rt = true;
        } catch (Exception ex) {
            system.debug('=====' + ex.getMessage());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
            Database.rollback(sp);
            return false;
        }

        return rt;
    }

    public class HeaderInfo {
        // 买方信息
        public String buyer_name { get; set; }
        public String buyer_address { get; set; }
        public String buyer_city { get; set; }
        public String buyer_province { get; set; }
        public String buyer_phone { get; set; }
        public String buyer_code {get; set;}
        // 卖方信息
        public String seller_name { get; set; }
        public String seller_address { get; set; }
        public String seller_city { get; set; }
        public String seller_province { get; set; }
        public String seller_phone { get; set; }
        public String seller_code {get; set;}
        // 订单信息1
        public String order_number { get; set; }
        public String order_require_date { get; set; }
        public String order_sap_no { get; set; }
        public String order_crm_no { get; set; }
        public String order_subdealer { get; set; }
        // 收货信息
        public String delivery_name { get; set; }
        public String delivery_department { get; set; }
        public String delivery_address { get; set; }
        public String delivery_city { get; set; }
        public String delivery_province { get; set; }
        public String delivery_user { get; set; }
        public String delivery_phone { get; set; }
        public String delivery_tel { get; set; }
        // 最终用户信息
        public String user_name { get; set; }
        public String user_no { get; set; }
        public String user_department { get; set; }
        public String user_address { get; set; }
        public String user_city { get; set; }
        public String user_province { get; set; }
        public String user_name2 { get; set; }
        public String user_phone { get; set; }
        public String user_fax {get; set;}
        public String user_email {get;set;}
        public String user_tel { get; set; }
        public String user_property_IE { get; set; }
        public String user_product_IE { get; set; }
        public String user_market_RVI { get; set; }
        // 订单信息2
        public Decimal order_subtotal { get; set; }
        public Decimal order_discount_rate { get; set; }
        public Decimal order_discount_value { get; set; }
        public Decimal order_totalprice { get; set; }
        public Decimal order_dealer_profit { get; set; }
        public Decimal order_dealer_price { get; set; }
        public boolean order_print_dealer { get; set; }
        // 订单信息3
        public String order_inquiry_no { get; set; }
        public String order_no { get; set; }
        public String order_comment { get; set; }
        public String pdf_order_no { get; set; }

        public HeaderInfo() {

        }

        public HeaderInfo(Order order, Account buyer, Account delivery, Contact delivery_contact, Account user, Contact contact) {
            buyer_name = buyer.Name;
            buyer_address = buyer.Address1__c;
            buyer_city = buyer.City__c;
            buyer_province = buyer.Province__c;
            buyer_phone = buyer.Phone;
            buyer_code = buyer.Business_license__c;

            seller_name = order.PDF_S_Name__c;
            seller_address = order.PDF_S_Address__c;
            seller_city = order.PDF_S_City__c;
            seller_province = order.PDF_S_Province__c;
            seller_phone = order.PDF_S_Phone__c;

            order_number = order.Name;
            Date dt = order.Opportunity.ExpectedDeliveryDate__c;
            order_require_date = dt == null ? '' : dt.format();
            order_sap_no =  order.PDF_Sap_No__c;
            order_crm_no = order.OrderNumber;
            order_subdealer = order.Opportunity.SubDealer__c;

            delivery_name = delivery.Name;
            delivery_department = delivery_contact.Department;
            delivery_address = delivery_contact.Address1__c;
            delivery_city = delivery.City__c;
            delivery_province = delivery.Province__c;
            delivery_user = delivery_contact.Name;
            delivery_phone = delivery_contact.Phone;
            delivery_tel = delivery_contact.MobilePhone;

            user_name = user.Name;
            user_no = user.ManagementCode_F__c;
            user_department = contact.Department;
            user_address = user.Address1__c;
            user_city = user.City__c;
            user_province = user.Province__c;
            user_name2 = contact.Name;
            user_phone = contact.Phone;
            user_fax = contact.Fax;
            user_email = Contact.Email;
            user_tel = contact.MobilePhone;
            user_property_IE = order.PDF_Property__c;
            user_product_IE = user.Sub_Use__c == 'Automotive' ? '汽车' : user.Sub_Use__c;
            user_market_RVI = user.Sub_Use__c;

            order_subtotal = order.Olympus_Price_BeforeDiscount_D__c;
            order_discount_rate = order.Discount_D__c;
            order_totalprice = order.OlympusContractPricesD__c;
            order_discount_value = (order_subtotal == null ? 0 : order_subtotal) - (order_totalprice == null ? 0 : order_totalprice);
            order_dealer_price = order.CustomerContractPriceD__c;
            order_dealer_profit = (order_dealer_price == null ? 0 : order_dealer_price) - (order_totalprice == null ? 0 : order_totalprice);
            order_print_dealer = true;
            if (order_dealer_price == null || order_dealer_price == 0) {
                order_print_dealer = false;
            }

            order_inquiry_no = order.Opportunity.Name;
            if(order.Opportunity.ProductSegment__c == 'NDT' || order.Opportunity.ProductSegment__c == 'ANI'){
                order_inquiry_no = order.Opportunity.InquiryNumber__c;
            }
            order_no = order.PDF_No__c;
            order_comment = order.Description;
            pdf_order_no = order.PDF_Order_No__c;
        }
    }

    public class DetailInfo {
        public OrderItem orderItem { get; set; }
        public Integer lineno { get; set; }
        public String otcode { get; set; }
        public String eccode { get; set; }
        public Integer quantity { get; set; }
        public Decimal price { get; set; }
        public Decimal totalprice { get; set; }
        public String factory { get; set; }
        public String ccode { get; set; }
        public String name {get; set;}
        public String registrationCode {get; set;}
        public Decimal price_d {get;set;}
        public String discount {get;set;}

        public DetailInfo(Integer line) {
            orderItem = new OrderItem();
            lineno = line;
            otcode = null;
            eccode = null;
            quantity = null;
            price = null;
            totalprice = null;
            factory = null;
            ccode = null;
            name = null;
            registrationCode = null;
            discount = null;
        }

        public DetailInfo(Integer line, OrderItem oi,Decimal dis) {
            discount = dis + '%';
            orderItem = oi;
            lineno = line;
            otcode = oi.PriceBookEntry.Product2.ProductCode;
            otcode = otcode.startsWith('00000000000') ? otcode.substring(11) : otcode;
            eccode = oi.PriceBookEntry.Product2.Product_ECCode__c;
            //eccode = eccode.startsWith('00000000000') ? eccode.substring(11) : eccode;
            Decimal qty = oi.Quantity;
            quantity = qty.intValue();
            price = oi.UnitPrice;
            price = price.setScale(2, System.RoundingMode.HALF_UP);
            totalprice = qty * price;
            totalprice = totalprice.setScale(2, System.RoundingMode.HALF_UP);
            factory = oi.Factory__c;
            ccode = oi.PriceBookEntry.Product2.Product_CCode__c;
            name = oi.PriceBookEntry.Product2.Name;
            if (oi.PriceBookEntry.Product2.registrationCode__c !=null && oi.PriceBookEntry.Product2.registrationCode__c != '') {
                registrationCode = oi.PriceBookEntry.Product2.registrationCode__c + 'LS内贸';
            }else{
                registrationCode = oi.PriceBookEntry.Product2.registrationCode__c;
            }
            
            system.debug('registrationCode='+registrationCode);
            if(dis != null ){
                price_d =totalprice * (1-(dis/100));
                price_d = price_d.setScale(2, System.RoundingMode.HALF_UP);
            }
        }
    }

































































    public static void asd() {
        Integer i = 1;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
    }
}