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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gwt.user.client.ui.HTML;

import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.MemoryProxy;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.event.GridListenerAdapter;
import com.gwtext.client.widgets.menu.BaseItem;
import com.gwtext.client.widgets.menu.Item;
import com.gwtext.client.widgets.menu.Menu;
import com.gwtext.client.widgets.menu.event.BaseItemListenerAdapter;
import com.dev.energy.client.ApplicationWindow;
import com.dev.energy.client.config.page.PageConfig;
import com.dev.energy.client.rpc.CatchPageConfigAsync;
import com.dev.energy.client.rpc.DefineRPCAdapter;
import com.dev.energy.client.ui.page.IPage;
import com.dev.energy.client.ui.page.IPopupPage;
import com.dev.energy.client.utils.StringUtils;

public class ListRuleGridPanel extends GridPanel {
	protected Menu ruleMenu ;
	
	protected BrowseRulePage parentPage;
	
	protected CustomEntity mainNodeObj;
	
	public ListRuleGridPanel(){
		addGridRowListener();
	}
	
	public ListRuleGridPanel(List rules, String pageType, BrowseRulePage rulePage, CustomEntity nodeObj){
		parentPage = rulePage;
		
		mainNodeObj = nodeObj;
		
		init(rules,pageType);
		
		ruleMenu = getMenu(pageType);
		
		addGridRowListener();
	}
	
	private void init(List rules, String pageType){
		RecordDef recordDef = new RecordDef(
                new FieldDef[]{new StringFieldDef("id"),
                        new StringFieldDef("rule")
                }
        );

        Object[][] data = getRuleData(rules,pageType);
        MemoryProxy proxy = new MemoryProxy(data);

        ArrayReader reader = new ArrayReader(recordDef);
        Store store = new Store(proxy, reader);
        store.load();
        this.setStore(store);

        ColumnConfig[] columns = new ColumnConfig[]{
        		new ColumnConfig("id", "id", 0, true, null, "id"),
                new ColumnConfig("策略详情", "rule", 750, true, null, "rule")
        };
        
        columns[0].setHidden(true);
        
        ColumnModel columnModel = new ColumnModel(columns);
        this.setColumnModel(columnModel);
        
        this.setFrame(true);
        this.setStripeRows(true);

        
        this.setHeight(350);
        this.setWidth(750);
        this.setTitle("策略详情");
        
        
        
	}
	
	private void addGridRowListener() {
		this.addGridListener(new GridListenerAdapter() {
			public void onContextMenu(EventObject e) {
				e.stopEvent();
				int count = ListRuleGridPanel.this.getSelectionModel().getCount();
				
				if(count==0){
					ruleMenu.getItems()[0].setDisabled(false);
					ruleMenu.getItems()[1].setDisabled(true);
					ruleMenu.getItems()[2].setDisabled(true);
				}else{
					if(count==1){
						ruleMenu.getItems()[0].setDisabled(false);
						ruleMenu.getItems()[1].setDisabled(false);
						ruleMenu.getItems()[2].setDisabled(false);
					}else{
						ruleMenu.getItems()[0].setDisabled(false);
						ruleMenu.getItems()[1].setDisabled(true);
						ruleMenu.getItems()[2].setDisabled(false);
					}
				}
				ruleMenu.showAt(e.getXY());
			}
		});
	}
	
	private Object[][] getRuleData(List rules, String pageType) {
		int len = rules.size();
		Object[][] objs = new Object[len][];
		for (int i = 0; i < len; i++) {
			DisplayEntity displayEntity = (DisplayEntity)rules.get(i);
			String htmlStr=getNoticePanel(displayEntity,pageType);
			Object[] obj = new Object[]{displayEntity.getId()+"",new HTML(htmlStr)};
			objs[i] = obj;
		}
		return objs;
    }
	
	/**　
	 * 显示策略信息
	 * @return
	 */
	private String getNoticePanel(DisplayEntity displayEntity, String pageType) {
		String html = "";
		html += "<TR>"+
		"<TD style=\" border-bottom:1px solid #a0c8e0;vertical-align:middle;\">"+displayEntity.getLeftDis()+
		"&nbsp;&nbsp;&nbsp;<img src=\"images/rule_arrow.gif\" />&nbsp;&nbsp;&nbsp;";
		
		if(!StringUtils.isEmpty(displayEntity.getDefaultLocation())){
			html +=	"<img src=\"images/rule_location.gif\" />&nbsp;&nbsp;"+displayEntity.getDefaultLocation()+"-"+displayEntity.getMothed();
		}
		if(!StringUtils.isEmpty(displayEntity.getPosition())){
			html +=	"<img src=\"images/rule_position.gif\" />&nbsp;&nbsp;"+displayEntity.getPosition()+"("+displayEntity.getMothed()+")";
		}
		
		html +="</TD></TR>";
		
		return html;
	}
	
	private void createPageForUpdate(final Map params, final String pageId) {
		ApplicationWindow.context.getPageConfig(pageId,
				new CatchPageConfigAsync() {
					public void afterInvotion(PageConfig pageConfig) {
						IPopupPage page = pageConfig.createPage(params, parentPage);
						page.show();
						page.initData();
//						parentPage.displayRule(mainNodeObj);
					}
				});
	}
	
	private Menu getMenu(String pageType){
		Menu menu = new Menu();
		if(pageType.equals("put")){
			Item newPutRuleItem = new Item("新增策略",
					new BaseItemListenerAdapter() {
						public void onClick(BaseItem item, EventObject e) {
							final Map params = new HashMap();
							createPageForUpdate(params,"editPutRackRulePage");
						}
					});
			Item mdfPutRuleItem = new Item("修改策略",
					new BaseItemListenerAdapter() {
						public void onClick(BaseItem item, EventObject e) {
							final Map params = new HashMap();
							Record[] records = ListRuleGridPanel.this.getSelectionModel().getSelections();
							params.put("id",new Long(records[0].getAsInteger("id")));
							params.put(IPage.IS_EDIT_PAGE,true);
							createPageForUpdate(params,"editPutRackRulePage");
						}
					});
			Item delPutRuleItem = new Item("删除策略",
					new BaseItemListenerAdapter() {
						public void onClick(BaseItem item, EventObject e) {
							final Map params = new HashMap();
							params.put("pageType","put");
							Record[] records = ListRuleGridPanel.this.getSelectionModel().getSelections();
							List<Long> ids = new ArrayList<Long>();
							for(int i=0;i<records.length;i++){
								ids.add(new Long(records[i].getAsInteger("id")));
							}
							params.put("ids",ids);
							asyncDeleteRules(params);
						}
					});
			menu.addItem(newPutRuleItem);
			menu.addItem(mdfPutRuleItem);
			menu.addItem(delPutRuleItem);
		}else{
			Item newPickRuleItem = new Item("新增策略",
					new BaseItemListenerAdapter() {
						public void onClick(BaseItem item, EventObject e) {
							final Map params = new HashMap();
							createPageForUpdate(params,"editPickItemRulePage");
						}
					});
			Item mdfPickRuleItem = new Item("修改策略",
					new BaseItemListenerAdapter() {
						public void onClick(BaseItem item, EventObject e) {
							final Map params = new HashMap();
							Record[] records = ListRuleGridPanel.this.getSelectionModel().getSelections();
							params.put("id",new Long(records[0].getAsInteger("id")));
							params.put(IPage.IS_EDIT_PAGE,true);
							createPageForUpdate(params,"editPickItemRulePage");
						}
					});
			Item delPickRuleItem = new Item("删除策略",
					new BaseItemListenerAdapter() {
						public void onClick(BaseItem item, EventObject e) {
							final Map params = new HashMap();
							params.put("pageType","pick");
							Record[] records = ListRuleGridPanel.this.getSelectionModel().getSelections();
							List<Long> ids = new ArrayList<Long>();
							for(int i=0;i<records.length;i++){
								ids.add(new Long(records[i].getAsInteger("id")));
							}
							params.put("ids",ids);
							asyncDeleteRules(params);
						}
					});
			menu.addItem(newPickRuleItem);
			menu.addItem(mdfPickRuleItem);
			menu.addItem(delPickRuleItem);
		}
		return menu;
	}
	
	/**
	 * 费用明细查看
	 */
	private void asyncDeleteRules(final Map params){
		DefineRPCAdapter rcp = new DefineRPCAdapter() {
			public void successProcessor(Map map) {
				parentPage.displayRule(mainNodeObj);
			}
		};
		String pageType = (String)params.get("pageType");
		if(pageType.equals("put")){
			rcp.ajaxRpcCallBackExec("putRackRuleManager","deletePutRackRule",
					params);
		}else{
			rcp.ajaxRpcCallBackExec("pickItemRuleManager","deletePickItemRule",
					params);
		}
	}

}
