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.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.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_ALLOCATED;
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_AllocatedTable_Panel extends AbstractSupportPanel {

	protected final static String DEFAULT_NAME = "pickTicketAllocated_Panel";
	transient EditorGridPanel allocatedTable;
	private RecordDef recordDef;
	private ColumnModel columnModel;
	private Store store1;
	private MemoryProxy proxy1;
	private ArrayReader reader;
	transient Button cancellAllocateButton;
	private String flag;
    private static final DateTimeFormat dateFormater = DateTimeFormat.getFormat("yyyy-MM-dd");
	
	public Sub_AllocatedTable_Panel(IMessagePage page) {
		super(page, DEFAULT_NAME);
		this.drawWidget();
	}
	
	private void drawWidget() {	
		flag = curPADataAccessor().getFlag();
		recordDef = new RecordDef(new FieldDef[] { 
				 new IntegerFieldDef("task.id"), 
				 new StringFieldDef("location.code"), 			 			 			 		
				 new StringFieldDef("item.code"), 
				 new StringFieldDef("item.name"), 
				 new StringFieldDef("task.packageUnit"),
				 new IntegerFieldDef("task.planQuantity"), 
				 new IntegerFieldDef("task.planQuantityMU"),
				 new IntegerFieldDef("pickedRecord.manualQuantity"), 
				 new StringFieldDef("lotInfor"),
				 new StringFieldDef("task.storageDate"), 
				 new StringFieldDef("task.SOI")				 
				 }); 			
		 
			ColumnConfig tiColumn = new ColumnConfig(LocaleUtils.getText("task.id"), "task.id"); 
			tiColumn.setHidden(true);
		 
		 
			ColumnConfig lcColumn = new ColumnConfig(LocaleUtils.getText("location.code"), "location.code", 150); 
			lcColumn.setAlign(TextAlign.CENTER);
			lcColumn.setSortable(true);
		 
			ColumnConfig icColumn = new ColumnConfig(LocaleUtils.getText("item.code"), "item.code", 150); 
			icColumn.setAlign(TextAlign.CENTER);
			icColumn.setSortable(true);

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

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

			ColumnConfig tp1Column = new ColumnConfig(LocaleUtils.getText("task.planQuantity"), "task.planQuantity", 100); 
			tp1Column.setAlign(TextAlign.CENTER); 
			
			ColumnConfig tp2Column = new ColumnConfig(LocaleUtils.getText("task.planQuantityMU"), "task.planQuantityMU", 150); 
			tp2Column.setAlign(TextAlign.CENTER);

            NumberField numberField = new NumberField();
            numberField.setAllowBlank(false);
            numberField.setAllowNegative(false);
			
			ColumnConfig pmColumn = new ColumnConfig(LocaleUtils.getText("pickedRecord.manualQuantity"), "pickedRecord.manualQuantity", 100); 
			pmColumn.setAlign(TextAlign.CENTER);
			pmColumn.setEditor(new GridEditor(numberField));

			ColumnConfig lColumn = new ColumnConfig(LocaleUtils.getText("lotInfor"), "lotInfor", 150); 
			lColumn.setAlign(TextAlign.CENTER);
			
			ColumnConfig tsColumn = new ColumnConfig(LocaleUtils.getText("task.storageDate"), "task.storageDate", 150); 
			tsColumn.setAlign(TextAlign.CENTER);
			tsColumn.setSortable(true);

		 
			ColumnConfig tSColumn = new ColumnConfig(LocaleUtils.getText("task.SOI"),"task.SOI", 100); 
			tSColumn.setAlign(TextAlign.CENTER);
		 
		
		 
		 	columnModel = new ColumnModel(new ColumnConfig[]{ 
		 			tiColumn,lcColumn,icColumn,inColumn,tpColumn,tp1Column,
		 			tp2Column,pmColumn,lColumn,tsColumn,tSColumn
				 });
		 	
			proxy1 = new MemoryProxy(new String[][]{}); 
			reader = new ArrayReader(recordDef); 
			store1 = new Store(proxy1, reader);
			store1.load();
			allocatedTable = new EditorGridPanel();
            allocatedTable.setLayout(new RowLayout());
			allocatedTable.setAutoScroll(true);
			allocatedTable.setStore(store1);
			
			allocatedTable.setClicksToEdit(1);
			allocatedTable.setSelectionModel(new RowSelectionModel(false));
			
			allocatedTable.setColumnModel(columnModel);			

            ButtonListenerAdapter listener = new ButtonListenerAdapter() {
                public void onClick(Button button, EventObject e) {
//取消分配
                	cancellAllocate();
                }
            };			
            cancellAllocateButton = new Button("取消分配",listener);
            cancellAllocateButton.setDisabled(true);
			
			allocatedTable.addGridRowListener(new GridRowListener(){
				public void onRowClick(GridPanel grid, int rowIndex,
						EventObject e) {
					cancellAllocateButton.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(cancellAllocateButton);
		 	this.setLayout(new RowLayout());
			this.add(allocatedTable,new RowLayoutData("94%"));
			this.add(panel,new RowLayoutData("6%"));
		
	}
	
//取消分配	

	@SuppressWarnings("unchecked")
	private void cancellAllocate() {
		final Map param = new HashMap();
		if(flag == "pickTicketPage"){
			//存放发货单ID，以便取消分配后刷新信息
			Long pickTicketId = this.curPADataAccessor().currentPickTicket().getId();
			param.put("pickTicketId", pickTicketId);
		}else if(flag == "waveDocPage"){
			//存放波次ID，以便取消分配后刷新信息
			Long waveDocId = this.curPADataAccessor().currentPickTicket().getId();
			param.put("waveDocId", waveDocId);
		}
		final Map subParam = new HashMap();

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

			}
		}
		param.put(IPage.TABLE_INPUT_VALUES, subParam);
		if(flag == "pickTicketPage"){
			//发货单取消分配
			this.curPADataAccessor().cancellAllocate(param);
		}else if(flag == "waveDocPage"){
			//波次取消分配
			this.curPADataAccessor().cancellWaveDocAllocate(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_ALLOCATED_INFO.equals(message) || Page_PA_DataAccessor.INIT_WD_ALLOCATED_INFO.equals(message)){
			Object[][] data = new Object[this.curPADataAccessor().all_PTAD().size()][];
				for (int i=0;i<this.curPADataAccessor().all_PTAD().size();i++){
					data[i] = toArray(this.curPADataAccessor().all_PTAD().get(i));
				}
		
		
				proxy1 = new MemoryProxy(data);
				store1.setDataProxy(proxy1);
				store1.reload();
				allocatedTable.reconfigure(store1, columnModel);
		}
	
	}
	public Object[] toArray(PT_ALLOCATED allocated){
		return new Object[]{allocated.getTaskId() ,
				allocated.getLocationCode() ,
				allocated.getItemCode() ,
				allocated.getItemName() ,
				allocated.getPackageUnit() ,
				allocated.getPlanQuantity() ,
				allocated.getPlanQuantityMU() ,
				allocated.getManualQuantity() ,
				allocated.getLotInfor() ,
				dateFormater.format(allocated.getInventoryStorageDate()).toString() ,
				allocated.getInventorySOI() };		
	}
}

	
	


