package com.gx.obe.management.composite;

import java.text.MessageFormat;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.core.utils.WidgetUtils;
import org.eclipse.swt.core.widgets.EButton;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;

import com.gx.obe.action.bean.Action;
import com.gx.obe.action.listener.ActionListener;
import com.gx.obe.action.utils.ActionUtil;
import com.gx.obe.common.dialog.TenderProjectDialog;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.common.widget.button.Loading;
import com.gx.obe.common.widget.composite.PageFoodComposite;
import com.gx.obe.common.widget.composite.PageFoodComposite.PageListener;
import com.gx.obe.common.widget.composite.TitleComposite;
import com.gx.obe.common.widget.thread.SyncThread;
import com.gx.obe.common.widget.utils.MenuFunctionUtils;
import com.gx.obe.components.core.Constants;
import com.gx.obe.components.core.I18NEnum;
import com.gx.obe.components.core.enumeration.TenderProjectEnum;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.web.entity.Page;
import com.gx.obe.web.entity.auth.Menu;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.listener.TenderProjectListener;
import com.gx.obe.web.service.TenderProjectService;
import com.gx.obe.web.vo.TenderProjectVo;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

public class SubPackageListComposite extends Composite{

	private ScrolledComposite scrolledComposite;
	private Composite contentComposite;
	private PageFoodComposite pageFoodComposite;
	private TenderProjectEntity parentProject;
	private Menu menu;
	private MenuFunctionUtils menuFunctionUtils = new MenuFunctionUtils();
	private EButton addNowPackage;
	private Composite topComposite;
	private ActionListener topActionListener;
	private PackageOpListener packageOpListener;
	private String packageName;
	private TitleComposite titleComposite;
	public int PAGE_SIZE = 0;
	public static int CUR_PAGE_NO = 1;
	private TenderProjectService tenderProjectService;
	private Action projectAction;
	private GridLayout gl_contentComposite;
	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public SubPackageListComposite(Composite parent, Action projectAction, int style) {
		super(parent, style);
		
		this.projectAction = projectAction;
		setBackground(SWTResourceManager.getColor(240, 240, 240));
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.verticalSpacing = 0;
		gridLayout.horizontalSpacing = 0;
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 0;
		setLayout(gridLayout);
		
		titleComposite = new TitleComposite(this, SWT.NONE);
		titleComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		addNowPackage = titleComposite.addEButton("CREATE_PACKAGE");
		addNowPackage.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				createOrUpdateTenderProject(parentProject);
			}
		});
		addNowPackage.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/add.png"));
		addNowPackage.setText(Messages.Button_add);
			
		scrolledComposite = new ScrolledComposite(this, SWT.NONE | SWT.H_SCROLL | SWT.V_SCROLL);
		scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		scrolledComposite.setExpandHorizontal(true);
		scrolledComposite.setExpandVertical(true);
		
		contentComposite = new Composite(scrolledComposite, SWT.NONE);
		gl_contentComposite = new GridLayout(1, false);
		gl_contentComposite.marginWidth = 10;
		gl_contentComposite.marginHeight = 10;
		gl_contentComposite.verticalSpacing = 15;
		contentComposite.setLayout(gl_contentComposite);
		
		CLabel loading = new Loading(contentComposite, SWT.NONE);
		loading.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 1));
		
		scrolledComposite.setContent(contentComposite);
		scrolledComposite.setMinSize(contentComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
		
		pageFoodComposite = new PageFoodComposite(this, SWT.NONE);
		pageFoodComposite.setBackgroundMode(SWT.INHERIT_FORCE);
		pageFoodComposite.setBackground(SWTResourceManager.getColor(255, 255, 255));
		pageFoodComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		init();
	}
	
	/**
	 * @Description: 初始化
	 * @author guoyr
	 */
	private void init(){
		this.menu = projectAction.getMenu();
		parentProject = projectAction.getParentProject();
		packageName = com.gx.obe.components.core.I18N.getString(I18NEnum.SUBPACKAGE, this.parentProject.getTenderType());
		addNowPackage.setText(MessageFormat.format(Messages.Button_addToFormat, packageName));
		titleComposite.setTitle(MessageFormat.format(Messages.Title_list, packageName));
		packageOpListener = new PackageOpListener() {
			
			public void enterPackage(TenderProjectEntity tenderProjectEntity) {
				enterPackageAction(tenderProjectEntity);
			}
			public void deletePackage(TenderProjectEntity tenderProjectEntity) {
				deletePackageAction(tenderProjectEntity);
			}
			public void configPageSize() {
			}
			public void addPackage(TenderProjectEntity tenderProjectEntity) {
			}
		};
		pageFoodComposite.addPageListener(new PageListener(){
			public void changed(int pageNo, int pageSize) {
				queryProjectPage(pageNo);
			}
		});
		queryProjectPage(CUR_PAGE_NO);
		scrolledComposite.getVerticalBar().setIncrement(15);
		scrolledComposite.forceFocus();
		scrolledComposite.addListener(SWT.Activate, new Listener() {
	        public void handleEvent(Event e) {
	            scrolledComposite.forceFocus();
	        }
	    });
		if(TenderProjectEnum.REMOTE.equals(this.parentProject.getRemoteStatus())){
			WidgetUtils.setControlVisible(addNowPackage, false);
		}else if(TenderProjectEnum.LOCAL.equals(this.parentProject.getRemoteStatus())){
			WidgetUtils.setControlVisible(addNowPackage, true);
		}
		menuFunctionUtils.initFunctionAuthority(menu, titleComposite.getFunctionComposite());
	}

	
	/**
	 * @Description: 进入分包
	 * @author guoyr
	 * @param subPackage
	 */
	private void enterPackageAction( TenderProjectEntity tenderProjectEntity){
		// 进入项目的事件
		Action enterPackageAction = (Action)ActionUtil.getAction(com.gx.obe.management.action.EnterSubPackageAction.class.getName());
		enterPackageAction.setParentProject(parentProject);
		enterPackageAction.setTenderProject(tenderProjectEntity);
		enterPackageAction.setMenu(menu);
		enterPackageAction.addActionListener(topActionListener);
		enterPackageAction.run();
	}

	/**
	 * @Description: 刷新投标项目列表
	 * @author guoyr
	 */
	private void queryProjectPage(int pageNo) {
		CUR_PAGE_NO = pageNo;
		
//		Page<Map<String, Object>> projectPage = tenderProjectService.getSubPackagePageList(parentProject.getId(), CUR_PAGE_NO, PAGE_SIZE);
// 		Page<Map<String, Object>> projectPage = tenderProjectService.getSubPackagePageList(this.tenderProjectEntity.getTenderId(), CUR_PAGE_NO, PAGE_SIZE);
		if(tenderProjectService == null){
			tenderProjectService = new TenderProjectService();
		}
		
		SyncThread syncThread = new SyncThread(new SyncThread.Runnable(){
			public void run() {
				computerPageSize();
				final Page<TenderProjectVo> tenderPcakPage = tenderProjectService.getTenderPackPageList(parentProject.getId(), null, null, CUR_PAGE_NO, PAGE_SIZE);
				Display.getDefault().syncExec(new Runnable(){
					public void run(){
						if(contentComposite.isDisposed())return;
						for(Control control : contentComposite.getChildren()){
							control.dispose();
						}
						if(null != tenderPcakPage && null != tenderPcakPage.getRecords()){
							int index = 1;
							for(TenderProjectVo tenderPcakVo : tenderPcakPage.getRecords()){
								contentComposite.setData("topComposite",topComposite);
								SubPackageItemComposite trComposite = new SubPackageItemComposite(contentComposite, menuFunctionUtils, SWT.NONE);
								trComposite.refresh(index ++, parentProject, tenderPcakVo);
								GridData gd_trComposite = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
								trComposite.addPackageOpListener(packageOpListener);
								trComposite.setLayoutData(gd_trComposite);
							}
							pageFoodComposite.refreshPages(tenderPcakPage);
						}
						contentComposite.layout();
						scrolledComposite.setMinSize(contentComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
						scrolledComposite.forceFocus();
					}
				});
			}
		});
		syncThread.start();
		
	}
	
	private void computerPageSize() {
		if(PAGE_SIZE == 0) {
			Display.getDefault().syncExec(new Runnable() {
				public void run() {
					if(!contentComposite.isDisposed()) {
						int contentHeight = contentComposite.getBounds().height;
						SubPackageItemComposite trComposite = new SubPackageItemComposite(contentComposite, menuFunctionUtils, SWT.NONE);
						int rowHeight = trComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
						contentHeight = contentHeight - gl_contentComposite.marginHeight * 2 - gl_contentComposite.verticalSpacing;
						PAGE_SIZE = contentHeight/(rowHeight + gl_contentComposite.verticalSpacing);
						PAGE_SIZE = Math.max(PAGE_SIZE, 5);
//						if(contentHeight % (rowHeight + gl_contentComposite.verticalSpacing) != 0) {
//							gl_contentComposite.verticalSpacing += (rowHeight/(PAGE_SIZE-1));
//						}
					}
				}
			});
		}
	}
	
	/**
	 * @Description: 新建或修改项目
	 * @author guoyr
	 * @param tenderId
	 */
	private void createOrUpdateTenderProject(TenderProjectEntity parentTenderProject){
		if(!addNowPackage.getEnabled())return;
//		if(null == tenderProjectEntity){
		TenderProjectEntity tenderProject = new TenderProjectEntity();
		tenderProject.setUserId(Constants.USER.getId());
		tenderProject.setManagerName(Constants.USER.getUserName());
		tenderProject.setParentId(parentTenderProject.getId());
		tenderProject.setTenderType(StringUtils.isNotEmpty(parentTenderProject.getId()) ? parentTenderProject.getTenderType() : null);
//		}
		TenderProjectDialog projectDialog = new TenderProjectDialog(getShell(), tenderProject);
		projectDialog.addTenderProjectListener(new TenderProjectListener(){
			public void updateTenderProject(TenderProjectEntity _tenderProject) {
				if(null != _tenderProject){
					queryProjectPage(CUR_PAGE_NO);
				}
			}
		});
		projectDialog.open();
	}
	
	/**
	 * @Description: 删除项目或包件
	 * @author guoyr
	 */
	private void deletePackageAction(TenderProjectEntity tenderProjectEntity) {
		if(null != tenderProjectEntity){
			if (MessageDialog.openConfirm(null, MessageFormat.format(Messages.Tips_deleteObj, new Object[]{tenderProjectEntity.getTenderNo(), tenderProjectEntity.getTenderName()}))) {
 				tenderProjectService.removeTenderProject(tenderProjectEntity.getId());
				init();
//				tenderProjectList.remove(tenderProjectEntity);	
//				refreshProjectGrid(null);
			}
		}
	}
	
	public void addTopActionListener(ActionListener actionListener){
		this.topActionListener = actionListener;
	}
	public interface PackageOpListener{
		public void enterPackage(TenderProjectEntity tenderProjectEntity);
		public void addPackage(TenderProjectEntity tenderProjectEntity);
		public void deletePackage(TenderProjectEntity tenderProjectEntity);
		public void configPageSize();
	}
	@Override
	protected void checkSubclass() {
	}
}
