package com.dev.swms.client.ui.page;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.TextAlign;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.MemoryProxy;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.ToolbarButton;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.NumberField;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.EditorGridPanel;
import com.gwtext.client.widgets.grid.GridEditor;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.RowSelectionModel;
import com.gwtext.client.widgets.grid.event.GridRowListener;
import com.gwtext.client.widgets.layout.HorizontalLayout;
import com.gwtext.client.widgets.layout.RowLayout;
import com.gwtext.client.widgets.layout.RowLayoutData;
import com.dev.swms.client.ui.data.Page_PA_DataAccessor;
import com.dev.swms.client.ui.javabean.PT_AVAILABLE;
import com.dev.energy.client.message.IMessagePage;
import com.dev.energy.client.ui.page.IPage;
import com.dev.energy.client.ui.panel.AbstractSupportPanel;
import com.dev.energy.client.utils.LocaleUtils;


public class Sub_AvailableTable_Panel extends AbstractSupportPanel {

	protected final static String DEFAULT_NAME = "pickTicketAvailable_Panel";
	transient EditorGridPanel availableTable;
	private RecordDef recordDef;
	private ColumnModel columnModel;
	private Store store;
	private MemoryProxy proxy;
	private ArrayReader reader;
	transient ToolbarButton manualAllocateButton;
	private String flag;
    private static final DateTimeFormat dateFormater = DateTimeFormat.getFormat("yyyy-MM-dd");
	

	public Sub_AvailableTable_Panel(IMessagePage page) {
		super(page, DEFAULT_NAME);
		this.drawWidget();
	}

	private void drawWidget() {
		flag = curPADataAccessor().getFlag();
		recordDef = new RecordDef(new FieldDef[] { 
				 new IntegerFieldDef("inventory.id"), 
				 new StringFieldDef("location.code"), 			 			 			 		
				 new StringFieldDef("item.code"), 
				 new StringFieldDef("item.name"), 
				 new StringFieldDef("packageUnit.unit"), 
				 new IntegerFieldDef("packageUnit.convertFigure"), 
				 new IntegerFieldDef("inventory.quantity"),
				 new IntegerFieldDef("inventory.availableQuantity"), 
				 new IntegerFieldDef("inventory.manualQuantity"),
				 new StringFieldDef("itemKey.lot"), 
				 new StringFieldDef("lotInfor"),
				 new StringFieldDef("inventory.storageDate"),
				 new StringFieldDef("inventory.SOI")				 
				 }); 			
		 
			ColumnConfig iiColumn = new ColumnConfig(LocaleUtils.getText("inventory.id"), "inventory.id"); 
			iiColumn.setHidden(true);
		 
		 
			ColumnConfig lcColumn = new ColumnConfig(LocaleUtils.getText("location.code"), "location.code", 80); 
			lcColumn.setAlign(TextAlign.CENTER);
			lcColumn.setSortable(true);
		 
			ColumnConfig icColumn = new ColumnConfig(LocaleUtils.getText("item.code"), "item.code", 100); 
			icColumn.setAlign(TextAlign.CENTER); 

			ColumnConfig inColumn = new ColumnConfig(LocaleUtils.getText("item.name"), "item.name", 200); 
			inColumn.setAlign(TextAlign.CENTER); 

			ColumnConfig puColumn = new ColumnConfig(LocaleUtils.getText("packageUnit.unit"), "packageUnit.unit", 80); 
			puColumn.setAlign(TextAlign.CENTER); 

			ColumnConfig pcColumn = new ColumnConfig(LocaleUtils.getText("packageUnit.convertFigure"), "packageUnit.convertFigure", 80); 
			pcColumn.setAlign(TextAlign.CENTER); 

			ColumnConfig iqColumn = new ColumnConfig(LocaleUtils.getText("inventory.quantity"), "inventory.quantity", 80); 
			iqColumn.setAlign(TextAlign.CENTER); 
		 
			ColumnConfig iaColumn = new ColumnConfig(LocaleUtils.getText("inventory.availableQuantity"), "inventory.availableQuantity", 80); 
			iaColumn.setAlign(TextAlign.CENTER); 
		 
            NumberField numberField = new NumberField();
            numberField.setAllowBlank(false);
            numberField.setAllowNegative(false);
			
			ColumnConfig imColumn = new ColumnConfig(LocaleUtils.getText("inventory.manualQuantity"), "inventory.manualQuantity", 80); 
			imColumn.setAlign(TextAlign.CENTER);
			imColumn.setEditor(new GridEditor(numberField));

			ColumnConfig ilColumn = new ColumnConfig(LocaleUtils.getText("itemKey.lot"), "itemKey.lot", 100); 
			ilColumn.setAlign(TextAlign.CENTER); 

			ColumnConfig lColumn = new ColumnConfig(LocaleUtils.getText("lotInfor"), "lotInfor", 150); 
			lColumn.setAlign(TextAlign.CENTER);
			
			ColumnConfig isColumn = new ColumnConfig(LocaleUtils.getText("inventory.storageDate"), "inventory.storageDate", 150); 
			isColumn.setAlign(TextAlign.CENTER);
			isColumn.setSortable(true);
			
		 
			ColumnConfig iSColumn = new ColumnConfig(LocaleUtils.getText("inventory.SOI"),"inventory.SOI", 100); 
			iSColumn.setAlign(TextAlign.CENTER);
		 
		
		 
		 	columnModel = new ColumnModel(new ColumnConfig[]{ 
				 iiColumn,lcColumn,icColumn,inColumn,puColumn,pcColumn,
				 iqColumn,iaColumn,imColumn,ilColumn,lColumn,isColumn,iSColumn
				 });
		 	
			proxy = new MemoryProxy(new String[][]{}); 
			reader = new ArrayReader(recordDef); 
			store = new Store(proxy, reader);
			store.load();
			availableTable = new EditorGridPanel();
			availableTable.setAutoScroll(true);
			availableTable.setStore(store); 							 		 		 			 	
			availableTable.setColumnModel(columnModel);
			
			availableTable.setClicksToEdit(1);
			availableTable.setSelectionModel(new RowSelectionModel(false));
			
            ButtonListenerAdapter listener = new ButtonListenerAdapter() {
                public void onClick(Button button, EventObject e) {
//部分分配
                	manualAllocate();
                }
            };
			
            manualAllocateButton = new ToolbarButton("部分分配",listener);
            manualAllocateButton.setDisabled(true);
			
			availableTable.addGridRowListener(new GridRowListener(){
				public void onRowClick(GridPanel grid, int rowIndex,
						EventObject e) {
					manualAllocateButton.setDisabled(false);
				}

				public void onRowContextMenu(GridPanel grid, int rowIndex,
						EventObject e) {
					// TODO Auto-generated method stub
					
				}

				public void onRowDblClick(GridPanel grid, int rowIndex,
						EventObject e) {
					// TODO Auto-generated method stub
					
				}
			});
			Panel panel = new Panel();
			panel.add(manualAllocateButton);
			this.setLayout(new RowLayout());
			this.add(availableTable,new RowLayoutData("88%"));
			this.add(panel,new RowLayoutData("12%"));
	}
	
//部分分配	

	@SuppressWarnings("unchecked")
	private void manualAllocate() {
		final Map param = new HashMap();
		if(flag == "pickTicketPage"){
			//存放发货单明细ID，以便部分分配后刷新信息
			Long pickTicketDetailId = this.curPADataAccessor().getPtdId();
			param.put("pickTicketDetailId", pickTicketDetailId);
		}else if(flag == "waveDocPage"){
			//存放波次明细ID，以便部分分配后刷新信息
			Long waveDocDetailId = this.curPADataAccessor().getWddId();
			param.put("waveDocDetailId", waveDocDetailId);
		}
		
		final Map subParam = new HashMap();

		for(int i=0; i<availableTable.getStore().getCount();i++){ 
			if(availableTable.getSelectionModel().isSelected(i)){
				Long inventoryId = Long.valueOf(availableTable.getStore().getAt(i).getAsString("inventory.id"));
				Double availableQuantity = Double.valueOf(availableTable.getStore().getAt(i).getAsString("inventory.availableQuantity"));
				Double manualQuantity = Double.valueOf(availableTable.getStore().getAt(i).getAsString("inventory.manualQuantity"));
				if(manualQuantity.doubleValue() > availableQuantity.doubleValue()){
					Window.alert(LocaleUtils.getText("availableQuantity.not.enough"));
					return;
				}
				subParam.put(inventoryId, manualQuantity);

			}
		}
		param.put(IPage.TABLE_INPUT_VALUES, subParam);
		if(flag == "pickTicketPage"){
			//发货单部分分配
			this.curPADataAccessor().manualAllocate(param);
		}else if(flag == "waveDocPage"){
			//波次部分分配
			this.curPADataAccessor().manualWaveDocAllocate(param);
		}		
	}	
	
	public Page_PA_DataAccessor curPADataAccessor() {
		return (Page_PA_DataAccessor)super.getData();
	}	
	
	public void doDispath(String message){
		super.doDispath(message);
//		System.out.print("还进入这个doDispath()方法了！");
		if(Page_PA_DataAccessor.INIT_AVAILABLE_INFO.equals(message) || Page_PA_DataAccessor.INIT_WD_AVAILABLE_INFO.equals(message)){
			Object[][] data = new Object[this.curPADataAccessor().all_PTAS().size()][];
				for (int i=0;i<this.curPADataAccessor().all_PTAS().size();i++){
					data[i] = toArray(this.curPADataAccessor().all_PTAS().get(i));
				}
		
		
				proxy = new MemoryProxy(data);
				store.setDataProxy(proxy);
				store.reload();
				availableTable.reconfigure(store, columnModel);
		}else if(Page_PA_DataAccessor.AUTO_ALLOCATE_INFO.equals(message) || Page_PA_DataAccessor.AUTO_WD_ALLOCATE_INFO.equals(message)
				|| Page_PA_DataAccessor.CANCELL_ALLOCATE_INFO.equals(message) || Page_PA_DataAccessor.CANCELL_WD_ALLOCATE_INFO.equals(message)
				|| Page_PA_DataAccessor.MANUAL_ALLOCATE_INFO.equals(message) || Page_PA_DataAccessor.MANUAL_WD_ALLOCATE_INFO.equals(message)){
			proxy = new MemoryProxy(new String[][]{});
			store.setDataProxy(proxy);
			store.reload();
			availableTable.reconfigure(store, columnModel);
		}
	}
	
	public Object[] toArray(PT_AVAILABLE available){
		return new Object[]{available.getInventoryId() ,
				available.getLocationCode() ,
				available.getItemCode() ,
				available.getItemName() ,
				available.getPackageUnit() ,
				available.getPackageUnitConvertFigure() ,
				available.getInventoryQuantity() ,
				available.getInventoryAvailableQuantity() ,
				available.getInventoryManualQuantity() ,
				available.getItemKeyLot() ,
				available.getLotInfor() ,
				dateFormater.format(available.getInventoryStorageDate()).toString() ,
				available.getInventorySOI() };

	}

}
