public with sharing class ConInvoicedetailsController {

	//出库单使用
	public Consumable_order__c coc { get; set; }

	//发票使用
	public Consumable_order__c invoicecode { get; set; }

	//价格计算结果
    public Decimal sumPrice {get;set;}

	//出库单ID
	private String orderId {get;set;}
	//发票单ID
	private String invoiceId {get;set;}
    //出库单明细1，画面显示使用
	public List<ConsumableorderdetailsInfo> consumableorderdetails1Records { get; set; }
	//明细数量
    public Integer invoiceOrderRecoedsCount {
        get {
            return consumableorderdetails1Records == null ? 0 : consumableorderdetails1Records.size();
        }
    }

	public ConInvoicedetailsController() {
		orderId = ApexPages.currentPage().getParameters().get('orderId');
        invoiceId = ApexPages.currentPage().getParameters().get('invoiceId');
		consumableorderdetails1Records = new List<ConsumableorderdetailsInfo>();
		sumPrice = 0;
	}

	//页面初始化
	public void init() {

        coc = new Consumable_order__c();
        //出库单信息
        coc = [SELECT Id,Name,Outbound_Date__c,
        				Order_ForDealerText__c,
                        Dealer_Info__c
                    FROM Consumable_order__c
                    WHERE Id =:orderId];
        //发票信息
        invoicecode = [SELECT Id,Name,
                    ShipmentAccount__c,
                    Order_ForCustomerText__c,
                    Order_ForDealerText__c,
                    Dealer_Info__c
                FROM Consumable_order__c
                WHERE Id =:invoiceId];
        //发票明细1
        Map<String,Consumable_Orderdetails__c> invoiceorderdet1CountMap = new Map<String,Consumable_Orderdetails__c>();
        List<Consumable_Orderdetails__c> invoiceorderdetails1 = [
                        SELECT Id,
                                Name,
                                Consumable_order__c,
                                Asset_Model_No__c,
                                Consumable_Product__r.Asset_Model_No__c,
                                Consumable_Count__c,
                                Shipment_Count__c,
                                RrturnPro_count__c,
                                Delivery_List_RMB__c,
                                InvoicedProCost_RMB__c,
                                Invoiced_Procount__c,
                                Invoiced_Count__c,
                                Invoice_Unitprice__c,
                                InvoiceProNot_count__c,
                                Invoice_Cost_RMB__c,
                                Invoice_No__c,
                                Invoice_Unit__c,
                                Invoicedet1_OD_link__c
                            FROM Consumable_Orderdetails__c
                            WHERE Consumable_order__c = :invoiceId
                            and Invoicedet1_OD_link__c = :orderId];
        for (Integer i = 0; i < invoiceorderdetails1.size(); i++) {
            invoiceorderdet1CountMap.put(invoiceorderdetails1[i].Asset_Model_No__c, invoiceorderdetails1[i]);
        }
        //出库单明细1，画面显示使用
        List<Consumable_Orderdetails__c> consumableorderdetails1 = [
					SELECT Id,
                            Name,
                            Consumable_order__c,
                            Asset_Model_No__c,
                            Consumable_Product__r.Asset_Model_No__c,
                            Consumable_Count__c,
                            Shipment_Count__c,
                            RrturnPro_count__c,
                            Delivery_List_RMB__c,
                            InvoicedProCost_RMB__c,
                            Invoiced_Procount__c,
                            Invoiced_Count__c,
                            Invoice_Unitprice__c,
                            InvoiceProNot_count__c,
                            Invoice_Cost_RMB__c,
                            Invoice_No__c,
                            Consumable_Product__c,
                            Intra_Trade_List_RMB__c,
                            Dealer_Custom_Price__c,
                            Sum_of_money__c,
                            Used_date__c,
                            Send_date__c,
                            Box_Piece__c,
                            Invoice_Unit__c,
                            Consumable_Product__r.Packing_list_manual__c,
                            ProductPacking_list_manual__c
                        FROM Consumable_Orderdetails__c
                        WHERE Consumable_order__c = :orderId];
        for (Integer i = 0; i < consumableorderdetails1.size(); i++) {
            consumableorderdetails1Records.add(new ConsumableorderdetailsInfo(consumableorderdetails1[i]));
        }
        for (ConsumableorderdetailsInfo ass : consumableorderdetails1Records)  {
            if(invoiceorderdet1CountMap.containsKey(ass.esd.Asset_Model_No__c)){
                ass.check = true;
                
                if(invoiceorderdet1CountMap.get(ass.esd.Asset_Model_No__c).Invoice_Unit__c ==null || invoiceorderdet1CountMap.get(ass.esd.Asset_Model_No__c).Invoice_Unit__c ==''){
                    ass.esd.Invoice_Unit__c = ass.esd.Box_Piece__c;
                }else{
                    ass.esd.Invoice_Unit__c = invoiceorderdet1CountMap.get(ass.esd.Asset_Model_No__c).Invoice_Unit__c;
                }
                if(invoiceorderdet1CountMap.get(ass.esd.Asset_Model_No__c).Invoiced_Count__c == null || invoiceorderdet1CountMap.get(ass.esd.Asset_Model_No__c).Invoiced_Count__c == 0){
                    ass.invoiceCount = ass.esd.Invoiced_Count__c;
                }else{
                    ass.invoiceCount = invoiceorderdet1CountMap.get(ass.esd.Asset_Model_No__c).Invoiced_Count__c;
                }
                
                if(ass.esd.Box_Piece__c =='盒' && ass.esd.Invoice_Unit__c =='个'){
                    ass.esd.Invoice_Unitprice__c = ass.esd.Delivery_List_RMB__c/ass.Packing_list_manual;
                }else{
                    ass.esd.Invoice_Unitprice__c = ass.esd.Delivery_List_RMB__c;
                }
                Decimal invoiceAllprice = 0.00;
                invoiceAllprice = (ass.invoiceCount * ass.esd.Invoice_Unitprice__c).setScale(2);
                ass.invoiceAllprice = invoiceAllprice;
            }else{
                ass.invoiceCount = ass.esd.InvoiceProNot_count__c;
                ass.esd.Invoice_Unit__c = ass.esd.Box_Piece__c;
                ass.esd.Invoice_Unitprice__c = ass.esd.Delivery_List_RMB__c;
                
            }
            //ass.esd.Invoice_Unitprice__c = ass.esd.Delivery_List_RMB__c;
        }

	}

	//
	public PageReference save() {
		Savepoint sp = Database.setSavepoint();
        //新规发票明细1
        List<Consumable_Orderdetails__c> invoiceorderList1 = New List<Consumable_Orderdetails__c>();
        //更新发票明细1
        List<Consumable_Orderdetails__c> invoiceorderUpList1 = New List<Consumable_Orderdetails__c>();
        //删除发票明细1
        List<Consumable_Orderdetails__c> invoiceorderDeList1 = New List<Consumable_Orderdetails__c>();

        Map<String,Consumable_Orderdetails__c> invoiceordet1Map = new Map<String,Consumable_Orderdetails__c>();

		List<String> consumableorderList = new List<String>();
        List<String> consumableNameList = new List<String>();
        try{
            //更新出库单明细1
            for (ConsumableorderdetailsInfo ass : consumableorderdetails1Records)  {
                consumableorderList.add(ass.esd.Asset_Model_No__c);
            }

            //发票明细1获取
            List<Consumable_Orderdetails__c> invoiceorderdetails1 = [
                        SELECT Id,
                                Name,
                                Consumable_order__c,
                                Asset_Model_No__c,
                                Consumable_Product__r.Asset_Model_No__c,
                                Consumable_Count__c,
                                Shipment_Count__c,
                                RrturnPro_count__c,
                                Delivery_List_RMB__c,
                                InvoicedProCost_RMB__c,
                                Invoiced_Procount__c,
                                Invoiced_Count__c,
                                Invoice_Unitprice__c,
                                InvoiceProNot_count__c,
                                Invoice_Cost_RMB__c,
                                Invoice_No__c,
                                Invoice_Unit__c,
                                Box_Piece__c,
                                Invoicedet1_OD_link__c
                            FROM Consumable_Orderdetails__c
                            WHERE Consumable_order__c = :invoiceId
                            and Invoicedet1_OD_link__c = :orderId
                            and Asset_Model_No__c in :consumableorderList];
            for (Integer i = 0; i < invoiceorderdetails1.size(); i++) {
                invoiceordet1Map.put(invoiceorderdetails1[i].Invoicedet1_OD_link__c + invoiceorderdetails1[i].Asset_Model_No__c, invoiceorderdetails1[i]);
            }
            List<Consumable_Orderdetails__c> invoicedetails1count = [
                        SELECT Id,
                                Name,
                                Consumable_order__c,
                                Invoicedet1_OD_link__c,
                                Asset_Model_No__c,
                                Consumable_Product__r.Asset_Model_No__c,
                                Consumable_Count__c,
                                Shipment_Count__c,
                                RrturnPro_count__c,
                                Delivery_List_RMB__c,
                                InvoicedProCost_RMB__c,
                                Invoiced_Procount__c,
                                Invoiced_Count__c,
                                Sum_of_money__c,
                                Invoice_Unitprice__c,
                                InvoiceProNot_count__c,
                                Invoice_Cost_RMB__c,
                                Invoice_Unit__c,
                                Invoice_No__c
                            FROM Consumable_Orderdetails__c
                            WHERE Consumable_order__c = :invoiceId];
            Integer invoiceRecordscon = invoicedetails1count.size() +1;
            
            
            for (ConsumableorderdetailsInfo ass : consumableorderdetails1Records)  {
                if(ass.check == true && ass.invoiceCount > 0){
                    if(String.isEmpty(String.valueOf(ass.invoiceCount))){
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请输入发票数量！'));
                        return null;
                    }
                    if(ass.esd.Box_Piece__c =='盒' && ass.esd.Invoice_Unit__c =='个'){
                        if(ass.invoiceCount > (ass.esd.InvoiceProNot_count__c * ass.Packing_list_manual).setScale(0)){
                            ass.esd.InvoiceProNot_count__c.addError('发票数量不能超过还没发票数量！');
                            return null;
                        }

                    }else{
                        if(ass.invoiceCount > ass.esd.InvoiceProNot_count__c){
                            ass.esd.InvoiceProNot_count__c.addError('发票数量不能超过还没发票数量！');
                            return null;
                        }
                    }

                    //if(ass.esd.Invoice_Unit__c =='个'){
                        String invoiceCount = String.valueOf(ass.invoiceCount);
                        if(!Pattern.matches('^\\+{0,1}[1-9]\\d*', invoiceCount)){
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'发票数量必须是整数'));
                            return null;
                        }
                    //}
                    
                    if(invoiceordet1Map.containsKey(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c)){
                        invoiceordet1Map.get(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c).Shipment_Count__c = ass.invoiceCount;
                        invoiceordet1Map.get(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c).Invoiced_Count__c = ass.invoiceCount;
                        //invoiceordet1Map.get(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c).InvoicedProCost_RMB__c = invoiceordet1Map.get(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c).Delivery_List_RMB__c * ass.invoiceCount;
                        invoiceordet1Map.get(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c).Invoice_Unit__c = ass.esd.Invoice_Unit__c;
                        invoiceordet1Map.get(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c).Box_Piece__c = ass.esd.Box_Piece__c;
                        if(ass.esd.Box_Piece__c =='盒' && ass.esd.Invoice_Unit__c =='个'){
                            invoiceordet1Map.get(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c).InvoicedProCost_RMB__c = (ass.esd.Delivery_List_RMB__c/ass.Packing_list_manual) * ass.invoiceCount;
                            invoiceordet1Map.get(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c).Invoice_Unitprice__c = ass.esd.Delivery_List_RMB__c/ass.Packing_list_manual;
                        }else{
                            invoiceordet1Map.get(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c).InvoicedProCost_RMB__c = ass.esd.Delivery_List_RMB__c * ass.invoiceCount;
                            invoiceordet1Map.get(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c).Invoice_Unitprice__c = ass.esd.Delivery_List_RMB__c;
                        }

                        invoiceorderUpList1.add(invoiceordet1Map.get(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c));
                        invoiceRecordscon ++;
                    }else{
                        String str = string.valueOf(invoiceRecordscon);
                        if(str.length() == 1){
                            str = '0' + str;
                        }
                        Consumable_Orderdetails__c invoiceInsert1 = new Consumable_Orderdetails__c();
                        invoiceInsert1.Used_date__c = ass.esd.Used_date__c;
                        invoiceInsert1.Send_date__c = ass.esd.Send_date__c;
                        invoiceInsert1.Name = invoicecode.Name + '-'+ ass.esd.Name.substring(ass.esd.Name.length() - 7,ass.esd.Name.length());
                        invoiceInsert1.Shipment_Count__c = ass.invoiceCount;
                        invoiceInsert1.Consumable_Product__c = ass.esd.Consumable_Product__c;
                        invoiceInsert1.Intra_Trade_List_RMB__c = ass.esd.Intra_Trade_List_RMB__c;
                        invoiceInsert1.Delivery_List_RMB__c = ass.esd.Delivery_List_RMB__c;
                        invoiceInsert1.Dealer_Custom_Price__c = ass.esd.Dealer_Custom_Price__c;
                        invoiceInsert1.RecordTypeId = System.Label.RT_ConOrderDetail1_Invoice;
                        if(ass.esd.Box_Piece__c =='盒' && ass.esd.Invoice_Unit__c =='个'){
                            invoiceInsert1.Invoice_Unitprice__c = ass.esd.Delivery_List_RMB__c/ass.Packing_list_manual;
                        }else{
                            invoiceInsert1.Invoice_Unitprice__c = ass.esd.Delivery_List_RMB__c;
                        }
                        //invoiceInsert1.Invoice_Unitprice__c = ass.esd.Invoice_Unitprice__c;
                        invoiceInsert1.Invoice_Unit__c = ass.esd.Invoice_Unit__c;
                        invoiceInsert1.Box_Piece__c = ass.esd.Box_Piece__c;
                        if (ass.esd.Invoiced_Procount__c == null) ass.esd.Invoiced_Procount__c = 0;
                        invoiceInsert1.Invoiced_Count__c = ass.invoiceCount;
                        if (ass.esd.InvoicedProCost_RMB__c == null) ass.esd.InvoicedProCost_RMB__c = 0;
                        invoiceInsert1.InvoicedProCost_RMB__c = ass.invoiceCount * invoiceInsert1.Invoice_Unitprice__c;
                        invoiceInsert1.Consumable_order__c = invoiceId;
                        invoiceInsert1.Invoicedet1_OD_link__c = orderId;
                        invoiceRecordscon ++;
                        invoiceorderList1.add(invoiceInsert1);
                    }
                }else{
                    if(invoiceordet1Map.containsKey(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c)){
                        invoiceorderDeList1.add(invoiceordet1Map.get(ass.esd.Consumable_order__c + ass.esd.Asset_Model_No__c));
                    }
                }
            }
            
            if(invoiceorderList1.size() > 0){
                insert invoiceorderList1;
            }
            if(invoiceorderUpList1.size() > 0){
                update invoiceorderUpList1;
            }
            if(invoiceorderDeList1.size() > 0){
                delete invoiceorderDeList1;
            }
        }catch(Exception e){
            ApexPages.addmessages(e);
            Database.rollback(sp);
            return null;
        }
		return returnToinvoice();
	}

	// 返回不可编辑状态
    public PageReference returnToinvoice(){
        PageReference ref = new Pagereference('/ConInvoiceView?invoiceId='+invoiceId);
        ref.setRedirect(true);
        return ref;
    }

	// Data Bean
    class ConsumableorderdetailsInfo  {
        public Boolean check { get; set; }
        public Boolean oldCheck { get; set; }
        public Consumable_Orderdetails__c esd { get; set; }
        public Product2__c Prod { get; set; }
        public Decimal invoiceCount { get; set; }
        public Decimal invoiceAllprice { get; set; }
        public Decimal Packing_list_manual { get; set; }
        public List<SelectOption> Invoice_UnitOpts  { get; set; }
		// 消耗品产品明细
        public ConsumableorderdetailsInfo(Consumable_Orderdetails__c e) {
            check = false;
            oldCheck = false;
            esd = e;
            Prod = e.Consumable_Product__r;
            invoiceAllprice = 0;

            Packing_list_manual = e.Consumable_Product__r.Packing_list_manual__c;
            
            Invoice_UnitOpts = new List<SelectOption>();
            Invoice_UnitOpts.add(new SelectOption('盒', '盒'));
            Invoice_UnitOpts.add(new SelectOption('个', '个'));
        }
       
    }
}