public without sharing class OrderPdfController {

    public Order od { get; set; }
    public Order odpdf { get; set; }
    public Contract contra { get; set; }

    public Integer pageCnt {get; private set;}
    public Decimal TotalMoney {get; private set;}
    public Decimal TotalMoney2 {get; private set;}
    public Decimal TrAndPre {get; set;}
    public List<SetInfo> printRecords {get; private set;}
    public List<Order_Print_SetInfo__c> ndtdelList {get; set;}

    public List<Order_Print_SetInfo__c> printSetInfo { get; set; }

    public Opportunity Opp {get; private set;}
    public Boolean saveBtnDisabled { get; private set; }
    public String Id;

    public String baseUrl { get; set; }

    public Account specialDeliveryAddress { get; private set; }
    public Contact specialDeliveryContact { get; private set; }

    public String PDF_N_NotifyParty1 { get; private set; }
    public String PDF_NOTIFY_PARTY1 { get; private set; }
    public String PDF_N_Address1 { get; private set; }
    public String PDF_N_Add1 { get; private set; }
    public String PDF_N_TEL1 { get; private set; }
    public String PDF_N_FAX1 { get; private set; }
    public String PDF_N_CONTACT1 { get; private set; }
    public String PDF_N_CONTACTPERSON1 { get; private set; }

    public String PDF_N_NotifyParty2 { get; private set; }
    public String PDF_NOTIFY_PARTY2 { get; private set; }
    public String PDF_N_Address2 { get; private set; }
    public String PDF_N_Add2 { get; private set; }
    public String PDF_N_TEL2 { get; private set; }
    public String PDF_N_FAX2 { get; private set; }
    public String PDF_N_CONTACT2 { get; private set; }
    public String PDF_N_CONTACTPERSON2 { get; private set; }

    public String PDF_Forwarder1 { get; private set; }
    public String PDF_F_Add1 { get; private set; }
    public String PDF_F_TEL1 { get; private set; }
    public String PDF_F_FAX1 { get; private set; }
    public String PDF_F_ContactPerson1 { get; private set; }

    public String PDF_Forwarder2 { get; private set; }
    public String PDF_F_Add2 { get; private set; }
    public String PDF_F_TEL2 { get; private set; }
    public String PDF_F_FAX2 { get; private set; }
    public String PDF_F_ContactPerson2 { get; private set; }

    public List<NDT_Produce__c> ndtList {get; set;}
    public Decimal dis {get; set;}
    public List<DetailInfo> detaList {get; set;}

    public Boolean isNull {get; set;}
    public Boolean isVer {get; set;}
    public Boolean isPtf {get; set;}

    public List<OrderItem> oiList {get; set;}

    // The extension constructor initializes the private member
    // variable mysObject by using the getRecord method from the standard
    // controller.
    public OrderPdfController() {
        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';
        }
    }
    public PageReference init() {
        od = new Order();
        List<Order> oList = new List<Order>();

        printSetInfo = new List<Order_Print_SetInfo__c>();
        //ndtdelList = new List<Order_Print_SetInfo__c>();
        saveBtnDisabled = false;
        String saveflg = ApexPages.currentPage().getParameters().get('save');
        if (saveflg == '1') {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '保存成功。'));
        }
        isNull = false;
        if (Id != null) {
            oList = [select id, Discount_D__c, ServiceFee_D__c, ShippingHandling_Tax__c, /*B_Address__c, B_contactperson__c, */ApproveStatus__c, ProductSegment__c, Name, AccountId, OrderNumber, OpportunityId, PaymentCondition__c, PaymentCondition_D__c, DeliveryDate__c, EndUser__r.Name, PDF_SignatureDate__c, PDF_SignaturePlace__c, PDF_B_Add__c,
                     PDF_B_contactperson__c, PDF_SELLER__c, PDF_THE_SELLER__c, PDF_S_Adds__c, PDF_S_Address__c, PDF_S_TEL__c, PDF_S_FAX__c, PDF_B_Department__c,
                     PDF_S_Bank_Name__c, PDF_S_Bank_Address__c, PDF_S_Branch__c, PDF_QA__c, PDF_QA2__c, PDF_S_Account_No__c, PDF_S_Swift_Code__c, PDF_S_Account_Name__c, PDF_C_Add__c, CustomerContractPrice__c, CustomerContractPriceD__c,
                     PDF_C_contactperson__c, PDF_NotifyFlag__c, PDF_N_NotifyParty__c, PDF_NOTIFY_PARTY__c, PDF_N_Address__c, PDF_N_Add__c, PDF_B_Attri__c,
                     PDF_N_TEL__c, PDF_N_FAX__c, PDF_N_CONTACT__c, PDF_N_CONTACTPERSON__c, PDF_Sp_Shipment_Term__c, PDF_Sp_DestinationPort__c, PDF_Sp_DestinationPort_E__c, PDF_G_SpecNo__c,
                     PDF_Sp_ShippingTerms__c, PDF_Sp_Freight__c, PDF_Sp_insurance__c, PDF_Sp_SHIPPINGMARK__c, PDF_Bi_AllBill__c, PDF_I_Report__c, PDF_G_TrAndPre__c,
                     PDF_Bi_manufacturers__c, PDF_Bi_manufacturersEn__c, PDF_Bi_q1__c, PDF_Bi_airway__c, PDF_Bi_copyairway__c, PDF_Bi_invoice__c, PDF_Bi_Insurance__c, PDF_ForwarFlag__c,
                     PDF_Bi_Packing__c, PDF_Bi_Quality__c, PDF_Bi_Origin__c, PDF_Bi_Non_Wooden__c, PDF_Co_Contract__c, PDF_Co_Contract_E__c, PDF_Co_BContra__c, PDF_Co_BContra_E__c, PDF_SignaturePlaces__c,
                     PDF_Co_SContra__c, PDF_Co_SContra_E__c, PDF_C_Consignee__c, PDF_C_THECONSIGNE__c, PDF_C_Address__c, PDF_C_TEL__c, PDF_C_FAX__c, PDF_C_CONTACT__c,
                     PDF_BusyerCompany__c, PDF_By_Add__c, PDF_By_Tel__c, PDF_Forwarder__c, PDF_F_Add__c, PDF_F_TEL__c, PDF_F_FAX__c, PDF_F_ContactPerson__c,
                     Opportunity.SpecialDeliveryAddress__c, Opportunity.SpecialDeliveryContact__c, DeliveryTimeText__c, DeliveryTimeTextEn__c,
                     SpecialDeliveryAccount__c, SpecialDeliveryAccount_D__c, SpecialDeliveryContact2__c, SpecialDeliveryContact2_D__c, PDF_Order_No__c, Total_price_E__c, ContractPriceTotal__c,
                     PDF_Shipment_Term2_Text__c, PDF_PaymentTerms__c, PDF_PaymentTerms_E__c, PDF_Sign_Name__c, PDF_Sign_Title__c, org_order__c, Is_Already_Splited__c, PDF_Is_True__c 
                     from Order where id = :Id];
            ndtList = [select id, U8_Code__c, Quantity__c, Part_Number__c, Name_of_Goods__c from NDT_Produce__c where NDTOrder__c = :Id order by Id];
            printSetInfo = [select id, Order__c, No__c, Goods__c, Unit__c, Qty__c , UnitPrice__c, Total_Amount__c, U8__c, discount__c, discountprice__c, PriceNDT__c, Total_AmountNDT__c, Remark__c, NameOfGood__c from Order_Print_SetInfo__c where Order__c = :Id order by No__c];
            system.debug('printSetInfo.size = ' + printSetInfo.size());
            //ndtdelList = printSetInfo;

            List<OpportunityLineItem> oliList = [select Id, TotalPrice, Subtotal, Quantity, Product2Id, Product2.ProductCode, Product2.Name,
                                                 Product2.Description, Description, OpportunityId, Product2.Product_ECCode__c
                                                 from OpportunityLineItem
                                                 where OpportunityId = :oList[0].OpportunityId
                                                         order by Id];
            //isNull = printSetInfo.size() == 0 ? true : false;
            //先做合同的打印pdf没有保存或者打印就拆分,再而是已经打印或保存了,再拆分的情况。
            isPtf = oList[0].PDF_Is_True__c == true ? true : false;
            isVer = (oList[0].ApproveStatus__c == 'OrderPass' && oList[0].Is_Already_Splited__c == true) ? true : false;
            //**isNull和上面两个标志有联系，请以后修改isNull的时候，把isPtf和isVer也带上，isNull用到的地方请也给这俩算上。
            isNull = (oList[0].ApproveStatus__c == 'OrderDraft' || oList[0].ApproveStatus__c == 'OrderReject' ) ? true : false;
            system.debug('@@@@@@@@'+oList[0].ApproveStatus__c);
            system.debug(oList[0].ProductSegment__c);
            if (oList[0].ProductSegment__c != 'NDT' && oList[0].ProductSegment__c != 'ANI') {
                if (printSetInfo.size() < 15) {
                    for (Integer i = printSetInfo.size(); i < 15; i++) {
                        printSetInfo.add(new Order_Print_SetInfo__c(No__c = i + 1, Order__c = Id, CurrencyIsoCode = 'USD'));
                    }
                }
            } else {
                if (isNull || (isVer == true && isPtf == false)) {
                    //delete printSetInfo;
                    printSetInfo.clear();
                    if (printSetInfo.size() < 15 && oliList.size() < 15) {
                        for (Integer i = printSetInfo.size(); i < 15; i++) {
                            printSetInfo.add(new Order_Print_SetInfo__c(No__c = i + 1, Order__c = Id, CurrencyIsoCode = 'USD'));
                        }
                    } else {
                        for (Integer i = printSetInfo.size(); i < oliList.size(); i++) {
                            printSetInfo.add(new Order_Print_SetInfo__c(No__c = i + 1, Order__c = Id, CurrencyIsoCode = 'USD'));
                        }
                    }
                } else {
                    if (printSetInfo.size() < 15 && oliList.size() < 15) {
                        for (Integer i = printSetInfo.size(); i < 15; i++) {
                            printSetInfo.add(new Order_Print_SetInfo__c(No__c = i + 1, Order__c = Id, CurrencyIsoCode = 'USD'));
                        }
                    } else {
                        for (Integer i = printSetInfo.size(); i < oliList.size(); i++) {
                            printSetInfo.add(new Order_Print_SetInfo__c(No__c = i + 1, Order__c = Id, CurrencyIsoCode = 'USD'));
                        }
                    }
                }
            }



            if (ndtList.size() < oliList.size()) {
                for (Integer i = ndtList.size(); i < oliList.size(); i++) {
                    ndtList.add(new NDT_Produce__c(NDTOrder__c = Id));
                }
            }

            if (oList.size() > 0) {
                od = oList[0];
                dis = od.Discount_D__c;
                Opp = [select id, Name, Amount, ProductSegment__c, TradeType__c, SyncedQuoteId, Quote_TotalPrice__c from Opportunity where id = :od.OpportunityId];
               /* if (od.PDF_B_Add__c == null || od.PDF_B_Add__c == '') {
                    od.PDF_B_Add__c = od.B_Address__c;
                }
                if (od.PDF_B_contactperson__c  == null || od.PDF_B_contactperson__c == '') {
                    od.PDF_B_contactperson__c = od.B_contactperson__c;
                }*/
                if (od.PDF_SELLER__c == null || od.PDF_SELLER__c == '') {

                    od.PDF_Bi_q1__c = '2';
                    od.PDF_Bi_airway__c = '1';
                    od.PDF_Bi_copyairway__c = '1';
                    od.PDF_Bi_invoice__c = '2';
                    od.PDF_Bi_Insurance__c = '1';
                    od.PDF_Bi_Packing__c = '2';
                    od.PDF_Bi_Quality__c = '2';
                    od.PDF_Bi_Origin__c = '2';
                    od.PDF_Bi_Non_Wooden__c = '1';

                    od.PDF_Co_Contract__c = '2';
                    od.PDF_Co_BContra__c = '1';
                    od.PDF_Co_SContra__c = '1';

                    od.PDF_Co_Contract_E__c = 'two';
                    od.PDF_Co_BContra_E__c = 'one';
                    od.PDF_Co_SContra_E__c = 'one';
                }
                if ((Opp.ProductSegment__c == 'IE'  || Opp.ProductSegment__c == 'RVI' || Opp.ProductSegment__c == 'BS') && Opp.TradeType__c == 'Tax Exemption') {
                    od.PDF_SELLER__c = '仪景通光学科技（上海）有限公司';
                    od.PDF_THE_SELLER__c = 'Evident (Shanghai) Co., Ltd';
                    od.PDF_S_Adds__c = '中国（上海）自由贸易试验区日樱北路199-9号102及302部位';
                    od.PDF_S_Address__c = 'PART 302&102,NO.199-9,NORTH RIYING ROAD,CHINA (SHANGHAI) PILOT FREE TRADE ZONE';
                    od.PDF_S_TEL__c = '021-58881300';
                    od.PDF_S_FAX__c = '';
                    od.PDF_S_Bank_Name__c = 'SUMITOMO MITSUI BANKING CORPORATION（CHINA）LIMITED';
                    od.PDF_S_Branch__c = '';
                    od.PDF_S_Bank_Address__c = '11F, SHANGHAI WORLD FINANCIAL CENTER, 100 CENTURY AVENUE, PUDONG NEW AREA ,SHANGHAI 200120, PEOPLE\'S REPUBLIC OF CHINA';
                    od.PDF_S_Account_No__c = '40453301';
                    od.PDF_S_Swift_Code__c = 'SMBCCNSH';
                    od.PDF_S_Account_Name__c = 'Evident(Shanghai)CO.,LTD';
                } else if (( Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI') && Opp.TradeType__c == 'Tax Exemption') {
                    od.PDF_SELLER__c = '仪景通光学科技（上海）有限公司';
                    od.PDF_THE_SELLER__c = 'Evident (Shanghai) Co., Ltd';
                    od.PDF_S_Adds__c = '中国（上海）自由贸易试验区日樱北路199-9号102及302部位';
                    od.PDF_S_Address__c = 'PART 302&102,NO.199-9,NORTH RIYING ROAD,CHINA (SHANGHAI) PILOT FREE TRADE ZONE';
                    od.PDF_S_TEL__c = '021-58881300';
                    od.PDF_S_FAX__c = '';
                    od.PDF_S_Bank_Name__c = 'SUMITOMO MITSUI BANKING CORPORATION（CHINA）LIMITED';
                    od.PDF_S_Branch__c = '';
                    od.PDF_S_Bank_Address__c = '11F, SHANGHAI WORLD FINANCIAL CENTER, 100 CENTURY AVENUE, PUDONG NEW AREA ,SHANGHAI 200120, PEOPLE\'S REPUBLIC OF CHINA';
                    od.PDF_S_Account_No__c = '40453301';
                    od.PDF_S_Swift_Code__c = 'SMBCCNSH';
                    od.PDF_S_Account_Name__c = 'Evident(Shanghai)CO.,LTD';
                    od.DeliveryTimeTextEn__c = 'Please refer to order confirmation';
                    od.DeliveryTimeText__c = '请参考订单确认';
                    od.PDF_Bi_AllBill__c = '不随货';
                    od.PDF_G_TrAndPre__c = String.valueOf(od.ShippingHandling_Tax__c);
                }

                //Decimal TotalMoney = 0;
                TotalMoney = 0;
                TotalMoney2 = 0;
                if (Opp.Amount != null) {
                    TotalMoney = od.ContractPriceTotal__c; //Opp.Quote_TotalPrice__c;
                    if ((Opp.ProductSegment__c == 'BS' || Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI' ) && Opp.TradeType__c == 'Tax Exemption') {
                        TotalMoney = TotalMoney.setScale(2, System.RoundingMode.HALF_UP);
                    } else {
                        TotalMoney = TotalMoney.setScale(0, System.RoundingMode.HALF_UP);
                    }
                }
                if (od.CustomerContractPriceD__c != null) {
                    TotalMoney2 = od.CustomerContractPriceD__c;
                    TotalMoney2 = TotalMoney2.setScale(2, System.RoundingMode.HALF_UP);
                }
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '合同不存在'));
                saveBtnDisabled = true;
                return null;
            }

            specialDeliveryAddress = new Account();
            if (od.SpecialDeliveryAccount_D__c != null) {
                specialDeliveryAddress = [select Id, Name, EnglishName__c, Address1__c, Phone, Fax from Account where Id = :od.SpecialDeliveryAccount_D__c];
            }
            specialDeliveryContact = new Contact();
            if (od.SpecialDeliveryContact2_D__c != null) {
                specialDeliveryContact = [select Id, Name, Email from Contact where Id = :od.SpecialDeliveryContact2_D__c];
            }
        }

        Account acc = [select id, Name, EnglishName__c, Address1__c, Fax, Phone from Account where id = :od.AccountId];

        PDF_N_NotifyParty1 = acc.Name;
        PDF_NOTIFY_PARTY1 = acc.EnglishName__c;
        PDF_N_Address1 = acc.Address1__c;
        PDF_N_Add1 = od.PDF_B_Add__c;
        PDF_N_TEL1 = acc.Phone;
        PDF_N_FAX1 = acc.Fax;
        PDF_N_CONTACT1 = od.EndUser__r.Name;
        PDF_N_CONTACTPERSON1 = od.PDF_B_contactperson__c;

        PDF_N_NotifyParty2 = specialDeliveryAddress.Name;
        PDF_NOTIFY_PARTY2 = od.PDF_C_THECONSIGNE__c;
        PDF_N_Address2 = specialDeliveryAddress.Address1__c;
        PDF_N_Add2 = od.PDF_C_Add__c;
        PDF_N_TEL2 = specialDeliveryAddress.Phone;
        PDF_N_FAX2 = specialDeliveryAddress.Fax;
        PDF_N_CONTACT2 = specialDeliveryContact.Name;
        PDF_N_CONTACTPERSON2 = od.PDF_C_contactperson__c;

        PDF_Forwarder1 = acc.EnglishName__c;
        PDF_F_Add1 = od.PDF_B_Add__c;
        PDF_F_TEL1 = acc.Phone;
        PDF_F_FAX1 = acc.Fax;
        PDF_F_ContactPerson1 = od.EndUser__r.Name;

        PDF_Forwarder2 = od.PDF_C_THECONSIGNE__c;
        PDF_F_Add2 = od.PDF_C_Add__c;
        PDF_F_TEL2 = specialDeliveryAddress.Phone;
        PDF_F_FAX2 = specialDeliveryAddress.Fax;
        PDF_F_ContactPerson2 = od.PDF_C_contactperson__c;
        Decimal sum = 0;
        oiList = [select Id, PDF_Remark__c, Unit__c, 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 = :od.id
                                      order by QuoteLineItemId, Id];
        if ((Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI') && (isNull == true || (isVer == true && isPtf == false))) {
            Integer i = 0;
            /*oiList = [select Id, PDF_Remark__c, Unit__c, 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 = :od.id
                                      order by QuoteLineItemId, Id];*/
            for (Order_Print_SetInfo__c prc : printSetInfo) {
                if (i >= oiList.size()) {
                    prc.U8__c = null;
                    prc.Goods__c = null;

                    prc.Qty__c = null;
                    prc.Unit__c = '';
                    prc.Remark__c = '';
                    prc.UnitPrice__c = null;
                    prc.UnitPrice__c = null;
                    prc.discount__c = null;
                    if (dis != null) {
                        prc.discountprice__c = null;
                        //prc.discountprice__c = prc.discountprice__c * setScale(2, System.RoundingMode.HALF_UP);
                    } else {
                        prc.discountprice__c = null;
                    }
                    prc.Total_AmountNDT__c = null;
                    //Decimal.valueOf(String str)
                    //sum += prc.Total_AmountNDT__c;
                } else {
                    prc.Id = null;
                    prc.U8__c = oiList[i].PriceBookEntry.Product2.ProductCode;
                    prc.Goods__c = oiList[i].PriceBookEntry.Product2.Product_ECCode__c;

                    prc.Qty__c = oiList[i].Quantity.intValue();
                    prc.Unit__c = oiList[i].Unit__c;
                    prc.Remark__c = oiList[i].PDF_Remark__c;
                    prc.UnitPrice__c = oiList[i].UnitPrice;
                    prc.UnitPrice__c = prc.UnitPrice__c.setScale(2, System.RoundingMode.HALF_UP);
                    prc.discount__c = (dis == null ? 0 : dis ) + '';
                    if (dis != null) {
                        prc.discountprice__c = (prc.UnitPrice__c * (1 - (dis / 100))).setScale(2, System.RoundingMode.HALF_UP) + '';
                        //prc.discountprice__c = prc.discountprice__c * setScale(2, System.RoundingMode.HALF_UP);
                    } else {
                        prc.discountprice__c = prc.UnitPrice__c + '';
                    }
                    prc.Total_AmountNDT__c = Decimal.valueOf(prc.discountprice__c) * prc.Qty__c;
                    //Decimal.valueOf(String str)
                    sum += prc.Total_AmountNDT__c;
                    if (isVer == true) {
                        od.PDF_Is_True__c = true;
                    }
                }
                i++;
            }
            if (sum != 0) {
                printSetInfo[0].Total_AmountNDT__c = printSetInfo[0].Total_AmountNDT__c + (TotalMoney - sum - (od.ServiceFee__c == null ? 0 : od.ServiceFee__c) - (od.ShippingHandling_Tax__c == null ? 0 : od.ShippingHandling_Tax__c));
            }
        }

        return null;
    }

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

    public PageReference saveBtn() {
        PageReference ref = null;
        if (saveFunction() == true) {
            ref = new Pagereference(baseUrl + '/apex/OrderContract?id=' + od.id + '&save=1');
            ref.setRedirect(true);
        }
        return ref;
    }

    public boolean saveFunction() {
        /*        Account acc = [select id, Name, EnglishName__c, Address1__c, Fax, Phone from Account where id = :od.AccountId];

                if(od.PDF_NotifyFlag__c == '最终用户'){
                    od.PDF_N_NotifyParty__c = acc.Name;
                    od.PDF_NOTIFY_PARTY__c = acc.EnglishName__c;
                    od.PDF_N_Address__c = acc.Address1__c;
                    od.PDF_N_Add__c = od.PDF_B_Add__c;
                    od.PDF_N_TEL__c = acc.Phone;
                    od.PDF_N_FAX__c = acc.Fax;
                    od.PDF_N_CONTACT__c = od.EndUser__r.Name;
                    od.PDF_N_CONTACTPERSON__c = od.PDF_B_contactperson__c;
                }else if(od.PDF_NotifyFlag__c == '收货人'){
                    od.PDF_N_NotifyParty__c = specialDeliveryAddress.Name;
                    od.PDF_NOTIFY_PARTY__c = od.PDF_C_THECONSIGNE__c;
                    od.PDF_N_Address__c = specialDeliveryAddress.Address1__c;
                    od.PDF_N_Add__c = od.PDF_C_Add__c;
                    od.PDF_N_TEL__c = specialDeliveryAddress.Phone;
                    od.PDF_N_FAX__c = specialDeliveryAddress.Fax;
                    od.PDF_N_CONTACT__c = specialDeliveryContact.Name;
                    od.PDF_N_CONTACTPERSON__c = od.PDF_C_contactperson__c;
                }else if(od.PDF_NotifyFlag__c == '新建填写'){

                }

                if(od.PDF_ForwarFlag__c == '最终用户'){
                    od.PDF_Forwarder__c = acc.EnglishName__c;
                    od.PDF_F_Add__c = od.PDF_B_Add__c;
                    od.PDF_F_TEL__c = acc.Address1__c;
                    od.PDF_F_FAX__c = acc.Phone;
                    od.PDF_F_ContactPerson__c = od.EndUser__r.Name;
                }else if(od.PDF_ForwarFlag__c == '收货人'){
                    od.PDF_Forwarder__c = od.PDF_C_THECONSIGNE__c;
                    od.PDF_F_Add__c = od.PDF_C_Add__c;
                    od.PDF_F_TEL__c = specialDeliveryAddress.Phone;
                    od.PDF_F_FAX__c = specialDeliveryAddress.Fax;
                    od.PDF_F_ContactPerson__c = od.PDF_C_contactperson__c;
                }else if(od.PDF_ForwarFlag__c == '新建填写'){

                }*/

        Savepoint sp = Database.setSavepoint();
        try {
            List<Order_Print_SetInfo__c> updList = new List<Order_Print_SetInfo__c>();
            List<Order_Print_SetInfo__c> delList = new List<Order_Print_SetInfo__c>();

            List<NDT_Produce__c> nupdList = new List<NDT_Produce__c>();
            List<NDT_Produce__c> ndelList = new List<NDT_Produce__c>();

            List<OrderItem> oiupdList = new List<OrderItem>();

            Integer lineNo = 0;
            for (Order_Print_SetInfo__c ops : printSetInfo) {
                if (ops.Goods__c != null && ops.Goods__c != '') {
                    lineNo += 1;
                    ops.No__c = lineNo;
                    updList.add(ops);
                    if (Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI') {
                        if (ops.Unit__c == null || ops.Unit__c == '') {
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请输入全部货物的单位。'));
                            return false;
                        }
                    }
                }
                if (ops.Id != null && (ops.Goods__c == null || ops.Goods__c == '')) {
                    delList.add(ops);
                }
            }

            for (NDT_Produce__c npr : ndtList) {
                if (npr.U8_Code__c != null && npr.U8_Code__c != '') {
                    nupdList.add(npr);
                }
                if (npr.Id != null && (npr.U8_Code__c == null || npr.U8_Code__c == '')) {
                    ndelList.add(npr);
                }
            }
            if (nupdList.size() == 0 && (Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI')) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请输入附件内容'));
                return false;
            } else {
                upsert nupdList;
            }

            if (ndelList.size() > 0 && (Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI')) {
                delete ndelList;
            }

            if ((isNull || (isVer == true && isPtf == false)) && (Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI')) {
                ndtdelList = [select id from Order_Print_SetInfo__c where Order__c = :Id order by No__c];
                system.debug('ndtdelList:'+ndtdelList);
                delete ndtdelList;
            }

            if (updList.size() == 0) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请输入货物名称及规格。'));
                return false;
            } else {
                system.debug('updList:'+updList);
                if (od != null && od.id != null) {
                    update od;
                }
                upsert updList;
            }
            if (delList.size() > 0) {
                system.debug('delList'+delList);
                delete delList;
            }

           

           

            if (Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI') {
                for (OrderItem oi : oiList ) {
                    for ( Order_Print_SetInfo__c ops : printSetInfo ) {
                        if (oi.PriceBookEntry.Product2.ProductCode == ops.U8__c) {
                            OrderItem ordi = new orderItem();
                            ordi.Id = oi.Id;
                            ordi.Unit__c = ops.Unit__c;
                            ordi.PDF_Remark__c = ops.Remark__c;
                            oiupdList.add(ordi);
                            break;
                        }
                    }
                }
                if (oiupdList.size() > 0 ) {
                    update oiupdList;
                }
            }

            return true;
        } catch (Exception ex) {
            system.debug('=====' + ex);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + '( ' + od.id + ' )'));
            Database.rollback(sp);
            return false;
        }

        return true;
    }
    //public String getRecordName() {
    //   return 'Hello ' + (String)mysObject.get('name') + ' (' + (Id)mysObject.get('Id') + ')';
    //}
    public void init2() {
        odpdf = new Order();
        List<Order> opdfList = new List<Order>();

        if (Id != null) {
            opdfList = [select id, Discount_D__c, ShippingHandling_Tax__c, Name, OrderNumber, AccountId, OpportunityId, PaymentCondition__c, PaymentCondition_D__c, DeliveryDate__c, EndUser__r.Email, EndUser__r.Name, PDF_SignatureDate__c, PDF_SignaturePlace__c, PDF_B_Add__c, PDF_B_contactperson__c, PDF_SELLER__c,
                        PDF_THE_SELLER__c, PDF_S_Adds__c, PDF_S_Address__c, PDF_S_TEL__c, PDF_S_FAX__c, PDF_S_Bank_Name__c, PDF_S_Bank_Address__c, PDF_S_Branch__c, PDF_QA__c, PDF_QA2__c, PDF_B_Department__c,
                        PDF_S_Account_No__c, PDF_S_Swift_Code__c, PDF_S_Account_Name__c, PDF_C_Add__c, PDF_C_contactperson__c, PDF_NotifyFlag__c, PDF_B_Attri__c, Dealer__c,
                        PDF_N_NotifyParty__c, PDF_NOTIFY_PARTY__c, PDF_N_Address__c, PDF_N_Add__c, PDF_N_TEL__c, PDF_N_FAX__c, PDF_N_CONTACT__c, PDF_I_Report__c,
                        PDF_N_CONTACTPERSON__c, PDF_Sp_Shipment_Term__c, PDF_Sp_DestinationPort__c, PDF_Sp_DestinationPort_E__c, PDF_Sp_ShippingTerms__c, PDF_Sp_Freight__c, PDF_Forwarder__c,
                        PDF_Sp_insurance__c, PDF_Sp_SHIPPINGMARK__c, PDF_Bi_AllBill__c, PDF_Bi_manufacturers__c, PDF_Bi_manufacturersEn__c, PDF_Bi_q1__c, PDF_Bi_airway__c, PDF_SignaturePlaces__c,
                        PDF_Bi_copyairway__c, PDF_Bi_invoice__c, PDF_Bi_Insurance__c, PDF_Bi_Packing__c, PDF_Bi_Quality__c, PDF_Bi_Origin__c, PDF_F_FAX__c, CustomerContractPrice__c,
                        PDF_Bi_Non_Wooden__c, PDF_Co_Contract__c, PDF_Co_Contract_E__c, PDF_Co_BContra__c, PDF_Co_BContra_E__c, PDF_Co_SContra__c, PDF_Co_SContra_E__c, PDF_C_Consignee__c, PDF_C_THECONSIGNE__c, PDF_F_TEL__c,
                        PDF_C_Address__c, PDF_C_TEL__c, PDF_C_FAX__c, PDF_C_CONTACT__c , PDF_G_TrAndPre__c , PDF_G_SpecNo__c, PDF_F_Add__c, PDF_F_ContactPerson__c,
                        Opportunity.SpecialDeliveryAddress__c, Opportunity.SpecialDeliveryContact__c, Shipment_Term__c, Shipment_Term_D__c, Shipment_Term2__c, Shipment_Term2_D__c,
                        SpecialDeliveryAccount__c, SpecialDeliveryAccount_D__c, SpecialDeliveryContact2__c, SpecialDeliveryContact2_D__c, PDF_Order_No__c, DeliveryTimeText__c, DeliveryTimeTextEn__c, Total_price_E__c, ContractPriceTotal__c,
                        PDF_Shipment_Term2_Text__c, PDF_PaymentTerms__c, PDF_PaymentTerms_E__c, PDF_Sign_Name__c, PDF_Sign_Title__c
                        from Order
                        where id = :Id];
            ndtList = [select id, U8_Code__c, Quantity__c, Part_Number__c, Name_of_Goods__c from NDT_Produce__c where NDTOrder__c = :Id order by Id];
        }
        if (opdfList.size() > 0) {
            odpdf = opdfList[0];
            printSetInfo = [select id, U8__c, discount__c, discountprice__c, PriceNDT__c, Total_AmountNDT__c, Remark__c, Order__c, No__c, Goods__c, Unit__c, Qty__c , UnitPrice__c, Total_Amount__c, NameOfGood__c from Order_Print_SetInfo__c where Order__c = :odpdf.Id order by No__c];
        }
        TrAndPre = Decimal.valueOf(odpdf.PDF_G_TrAndPre__c == null ? '0' : odpdf.PDF_G_TrAndPre__c);
        dis = odpdf.Discount_D__c;
        Account acc = [select id, Name, EnglishName__c, Sub_Use__c, Address1__c, Fax, Phone from Account where id = :odpdf.AccountId];
        Opp = [select id, Name, Amount, ProductSegment__c, SubDealer__c, TradeType__c, SyncedQuoteId, Quote_TotalPrice__c from Opportunity where id = :odpdf.OpportunityId];

        specialDeliveryAddress = new Account();
        if (odpdf.SpecialDeliveryAccount_D__c != null) {
            specialDeliveryAddress = [select Id, Name, EnglishName__c, Address1__c, Phone, Fax from Account where Id = :odpdf.SpecialDeliveryAccount_D__c];
        }
        specialDeliveryContact = new Contact();
        if (odpdf.SpecialDeliveryContact2_D__c != null) {
            specialDeliveryContact = [select Id, Name, Email from Contact where Id = :odpdf.SpecialDeliveryContact2_D__c];
        }

        List<Quote> quoList = [select Id, Name, CreatedDate, OpportunityId, Opportunity.Dealer__c, Opportunity.DealerSalesStaffName__c, AccountId, PrintPrice__c, TotalPrice,
                               DeliveryLeadTime__c, PaymentTerms__c, ExpirationDate, Warranty__c, Opportunity.TradeType__c,
                               SetName1__c, SetQty1__c, SetName2__c, SetQty2__c, SetName3__c, SetQty3__c, SetName4__c, SetQty4__c, SetName5__c, SetQty5__c,
                               SetName6__c, SetQty6__c, SetName7__c, SetQty7__c, SetName8__c, SetQty8__c, SetName9__c, SetQty9__c, SetName10__c, SetQty10__c,
                               SetName11__c, SetQty11__c, SetName12__c, SetQty12__c, SetName13__c, SetQty13__c, SetName14__c, SetQty14__c, SetName15__c, SetQty15__c,
                               SetName16__c, SetQty16__c, SetName17__c, SetQty17__c, SetName18__c, SetQty18__c, SetName19__c, SetQty19__c, SetName20__c, SetQty20__c,
                               SetName21__c, SetQty21__c, SetName22__c, SetQty22__c, SetName23__c, SetQty23__c, SetName24__c, SetQty24__c, SetName25__c, SetQty25__c,
                               SetName26__c, SetQty26__c, SetName27__c, SetQty27__c, SetName28__c, SetQty28__c, SetName29__c, SetQty29__c, SetName30__c, SetQty30__c
                               from Quote
                               where id = :Opp.SyncedQuoteId];

        Quote quo = new Quote();
        printRecords = new List<SetInfo>();
        //Decimal TotalMoney = 0;
        TotalMoney = 0;
        if (Opp.Amount != null) {
            TotalMoney = odpdf.ContractPriceTotal__c; //Opp.Quote_TotalPrice__c;
            if ((Opp.ProductSegment__c == 'BS' || Opp.ProductSegment__c == 'NDT' || Opp.ProductSegment__c == 'ANI' ) && Opp.TradeType__c == 'Tax Exemption') {
                TotalMoney = TotalMoney.setScale(2, System.RoundingMode.HALF_UP);
            } else {
                TotalMoney = TotalMoney.setScale(0, System.RoundingMode.HALF_UP);
            }
        }

        if (quoList.size() > 0) {
            //询价里有同步总的报价，产品使用报价里的产品，
            quo = quoList[0];
            // 报价产品信息
            List<QuoteLineItem> qliList = [select Id, QuoteId, Quantity, UnitPrice, Subtotal, TotalPrice, Description, Set__c,
                                           Product2Id, Product2.ProductCode, Product2.Description, Product2.Name, Product2.Product_ECCode__c
                                           from QuoteLineItem
                                           where QuoteId = :Opp.SyncedQuoteId
                                                   //order by Set__c, LineNumber];
                                                   order by Id];

            //pageCnt = 1;
            String strSetCnt = System.Label.QuoteEntryMaxSet;
            Integer intSetCnt = Integer.valueOf(strSetCnt);
            Integer cnt = 1;
            /*            for (Integer i = 1; i <= intSetCnt; i++) {
                            String sName = (String) quo.get('SetName' + i + '__c');
                            if (sName != null && sName.length() > 0) {
                                String setName = 'set' + (i < 10 ? '0' : '') + i;
                                SetInfo si = new SetInfo(cnt, setName, quo, qliList);
                                printRecords.add(si);
                                //pageCnt += si.pCnt;
                                cnt += 1;
                            }
                        }*/
            SetInfo sio = new SetInfo(1, qliList);
            printRecords.add(sio);

        } else {
            //询价里没有同步中的报价，产品使用询价里的产品，
            List<OpportunityLineItem> oliList = [select Id, TotalPrice, Subtotal, Quantity, Product2Id, Product2.ProductCode, Product2.Name,
                                                 Product2.Description, Description, OpportunityId, Product2.Product_ECCode__c
                                                 from OpportunityLineItem
                                                 where OpportunityId = :odpdf.OpportunityId
                                                         order by Id];
            SetInfo sio = new SetInfo(1, oliList);
            printRecords.add(sio);
        }

        contra = new Contract(odpdf, acc, specialDeliveryAddress.Name, specialDeliveryAddress.Address1__c, specialDeliveryAddress.Phone, specialDeliveryAddress.Fax, specialDeliveryContact.Name);
        //OSSA外贸套装信息自动带出



    }


    private static Map<String, String> QAapiMap = new Map<String, String> {
        '12个月' => 'twelve(12) months',
        '15个月' => 'fifteen(15) months',
        '18个月' => 'eighteen(18) months',
        '21个月' => 'twenty-one(21) months',
        '24个月' => 'twenty-four(24) months',
        '27个月' => 'twenty-seven(27) months',
        '30个月' => 'thirty(30) months',
        '33个月' => 'thirty-three(33) months',
        '36个月' => 'thirty-six(36) months',
        '48个月' => 'forty-eight(48) months',
        '60个月' => 'sixty(60) months',
        '39个月' => 'thirty-nine (39) months',
        '51个月' => 'fifty-one (51) monthss',
        '63个月' => 'sixty-three (63) months'
    };

    public class SetInfo {
        private Integer maxLine = 36;

        public String units {get; private set;}
        public String description {get; private set;}
        public Integer qty {get; private set;}
        public Decimal total {get; private set;}
        public Decimal cost {get; private set;}
        public List<List<LineInfo>> setPage {get; private set;}
        public Integer pCnt {get; private set;}

        /*        public SetInfo(Integer no, String setName, Quote info, List<QuoteLineItem> qliList) {
                    units = String.valueOf(no);
                    String fieldName = setName.substring(3);
                    fieldName = fieldName.indexOf('0') == 0 ? fieldName.substring(1) : fieldName;
                    description = (String) info.get('SetName' + fieldName + '__c');
                    Decimal d_qty = (Decimal) info.get('SetQty' + fieldName + '__c');
                    qty = d_qty == null ? 1 : d_qty.intValue();
                    total = 0;
                    cost = 0;

                    setPage = new List<List<LineInfo>>();
                    //pCnt = 0;
                    Integer i = 0;
                    //Integer tmp = 0;
                    List<LineInfo> sPage = new List<LineInfo>();
                    for (QuoteLineItem qli : qliList) {
                        if (qli.Set__c == setName) {
                            i += 1;
                            LineInfo line = new LineInfo(i,qli, qty);
                            //LineInfo line = new LineInfo(i, qli, 1, isPrintPrice=='true');
                            if (i > 1) {
                                sPage.add(line);
                                //tmp += line.lineCost;
                            } else {
                                //system.debug('====set new page,tmp:' + tmp + '_cost:' + line.lineCost);
                                sPage = new List<LineInfo>();
                                setPage.add(sPage);
                                sPage.add(line);
                                //tmp = line.lineCost;
                                //pCnt += 1;
                            }
                            cost += line.subTotal;
                            total += line.subTotal * qty;
                        }
                    }
                    //system.debug('=====pCnt:' + pCnt);
                }*/

        public SetInfo(Integer no, List<QuoteLineItem> quoLinItemList) {
            units = String.valueOf(no);
            description = '非套装';
            qty = 1;
            total = 0;
            cost = 0;

            setPage = new List<List<LineInfo>>();
            //pCnt = 0;
            Integer i = 0;
            //Integer tmp = 0;
            List<LineInfo> sPage = new List<LineInfo>();
            for (QuoteLineItem qli : quoLinItemList) {
                i += 1;
                LineInfo line = new LineInfo(i, qli);
                if (i > 1) {
                    sPage.add(line);
                    //tmp += line.lineCost;
                } else {
                    //system.debug('====set new page,tmp:' + tmp + '_cost:' + line.lineCost);
                    sPage = new List<LineInfo>();
                    setPage.add(sPage);
                    sPage.add(line);
                    //tmp = line.lineCost;
                    //pCnt += 1;
                }
                cost += line.subTotal;
                total += line.subTotal;
            }

        }

        public SetInfo(Integer no, List<OpportunityLineItem> oppLinItemList) {
            units = String.valueOf(no);
            description = '非套装';
            qty = 1;
            total = 0;
            cost = 0;
            setPage = new List<List<LineInfo>>();
            //pCnt = 0;
            Integer i = 0;
            //Integer tmp = 0;
            List<LineInfo> sPage = new List<LineInfo>();
            for (OpportunityLineItem oli : oppLinItemList) {
                i += 1;
                LineInfo line = new LineInfo(i, oli);
                if (i > 1) {
                    sPage.add(line);
                    //tmp += line.lineCost;
                } else {
                    //system.debug('====set new page,tmp:' + tmp + '_cost:' + line.lineCost);
                    sPage = new List<LineInfo>();
                    setPage.add(sPage);
                    sPage.add(line);
                    //tmp = line.lineCost;
                    //pCnt += 1;
                }
                cost += line.subTotal;
                total += line.subTotal;
            }

        }

    }


    // PDF明细行信息
    public class LineInfo {
        public Integer lineNo {get; private set;}
        public String productName {get; private set;}
        public String productEC {get; private set;}
        public Decimal subTotal {get; private set;}
        public Integer quantity {get; private set;}
        public String U8Code {get; private set;}
        /*public LineInfo(Integer i, QuoteLineItem info, Integer qty) {
            lineNo = i;
            productName = info.Product2.Name;
            productEC = info.Product2.Product_ECCode__c;
            Decimal d_quantity = info.Quantity / qty;
            quantity = d_quantity.intValue();
            subTotal = info.TotalPrice / qty;
        }*/

        public LineInfo(Integer i, QuoteLineItem quoLinItem) {
            lineNo = i;
            productName = quoLinItem.Product2.Name;
            productEC = quoLinItem.Product2.Product_ECCode__c;
            quantity = quoLinItem.Quantity.intValue();
            subTotal = quoLinItem.TotalPrice;
            U8Code = null;
        }

        public LineInfo(Integer i, OpportunityLineItem oppLinItem) {
            lineNo = i;
            productName = oppLinItem.Product2.Name;
            productEC = oppLinItem.Product2.Product_ECCode__c;
            quantity = oppLinItem.Quantity.intValue();
            subTotal = oppLinItem.TotalPrice;
            U8Code  = oppLinItem.Product2.ProductCode;
        }

    }



    class Contract {
        public String SignatureDate { get; private set; } //签订日期中
        public String SignatureDates { get; private set; } //签订日期英
        public Order order { get; private set; }
        public Account account { get; private set; }
        public String AllBills { get; private set; }
        public String QAeng { get; private set; }
        public String QAeng2 { get; private set; }
        public String ShippingTerms { get; private set; }

        public String pdf_c_consignee { get; private set; }
        public String pdf_c_address { get; private set; }
        public String pdf_c_tel { get; private set; }
        public String pdf_c_fax { get; private set; }
        public String pdf_c_contact { get; private set; }

        public Contract(Order o, Account acc, String name, String address, String phone, String fax, String name2) {
            order = o;
            account = acc;
            SignatureDate = o.PDF_SignatureDate__c == null ? '' : o.PDF_SignatureDate__c.format('yyyy年MM月dd日');
            SignatureDates = o.PDF_SignatureDate__c == null ? '' : o.PDF_SignatureDate__c.formatGMT('d-MMM-yyyy');
            if (o.PDF_Bi_AllBill__c == '随货') {
                AllBills = 'with';
            } else if (o.PDF_Bi_AllBill__c == '不随货') {
                AllBills = 'not with';
            }
            QAeng = QAapiMap.get(o.PDF_QA__c);
            QAeng2 = QAapiMap.get(o.PDF_QA2__c);
            if (o.PDF_Sp_ShippingTerms__c == '海运') {
                ShippingTerms = 'by sea';
            } else if (o.PDF_Sp_ShippingTerms__c == '空运') {
                ShippingTerms = 'by air';
            } else if (o.PDF_Sp_ShippingTerms__c == '陆运') {
                ShippingTerms = 'by land';
            }

            pdf_c_consignee = name;
            pdf_c_address = address;
            pdf_c_tel = phone;
            pdf_c_fax = fax;
            pdf_c_contact = name2;
        }
    }

    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;
            registrationCode = oi.PriceBookEntry.Product2.registrationCode__c;
            if (dis != null ) {
                price_d = totalprice * (1 - (dis / 100));
                price_d = price_d.setScale(2, System.RoundingMode.HALF_UP);
            }
        }
    }
}