package com.gx.obe.management.composite;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.CallBack;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.core.utils.WidgetUtils;
import org.eclipse.swt.core.widgets.EButton;
import org.eclipse.swt.core.widgets.ELink;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.FillLayout;
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 com.gx.obe.ColorConstants;
import com.gx.obe.action.bean.Action;
import com.gx.obe.action.listener.ActionListener;
import com.gx.obe.business.enumeration.ProjectRuleEnum;
import com.gx.obe.business.enumeration.SupplierEnum;
import com.gx.obe.business.vo.ExchangeRate;
import com.gx.obe.common.dialog.BidPriceSubItemDialog;
import com.gx.obe.common.dialog.ExchangeRateDialog;
import com.gx.obe.common.dialog.SupplierBatchOrderDialog;
import com.gx.obe.common.icons.IconsActivator;
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.enumeration.BidPriceEnum;
import com.gx.obe.components.core.enumeration.CommonEnum;
import com.gx.obe.components.core.enumeration.TenderProjectEnum;
import com.gx.obe.config.ConfigConstants;
import com.gx.obe.config.utils.PropertiesUtils;
import com.gx.obe.message.Messages;
import com.gx.obe.message.menu.MenuMessages;
import com.gx.obe.thread.SyncThreadSet;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.util.utils.UuidUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.SupplierOpeningResult;
import com.gx.obe.web.entity.auth.Menu;
import com.gx.obe.web.entity.price.BidPrice;
import com.gx.obe.web.entity.price.BidPriceResult;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.entity.tender.TenderProjectRuleEntity;
import com.gx.obe.web.service.BidPriceResultService;
import com.gx.obe.web.service.BidPriceService;
import com.gx.obe.web.service.ProjectRuleService;
import com.gx.obe.web.service.SupplierService;
import com.gx.obe.web.service.TenderProjectService;
import com.gx.tools.utils.BidPriceUtils;
import com.gx.utils.ExchangeRateUitls;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/**
 * @Description: 投标报价管理
 * @author guoyr
 */
public class BidPriceComposite extends Composite{
 
	
	private TenderProjectEntity tenderProject;
	private TenderProjectRuleEntity projectRule;
	private List<Supplier> supplierList = new ArrayList<Supplier>();
	private IBidPriceResultTable bidPriceResultTable;
	private EButton save_btn;
	private Composite bid_price_composite;
	private ELink addSubbidPriceBtn;
	private ELink editSortNo_btn;
	private ActionListener listener;
//	private ELink import_bidPrice_label;
	private List<BidPrice> bidPriceList;
	private BidPrice defaultBidPrice;
	private TitleComposite titleComposite;
	private Menu menu;
	private MenuFunctionUtils menuFunctionUtils = new MenuFunctionUtils();
	private boolean isAnonymous;
	private TenderProjectService tenderProjectService ;
	private ProjectRuleService projectRuleService;
	private SupplierService supplierService;
	private BidPriceService bidPriceService ;
	private BidPriceResultService bidPriceResultService;
	private Action projectAction;
	List<Supplier> allSupplierList;
	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public BidPriceComposite(Composite parent, Action projectAction, int style) {
		super(parent, style);
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.verticalSpacing = 0;
		gridLayout.horizontalSpacing = 0;
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 0;
		setLayout(gridLayout);
		
		this.projectAction = projectAction;
		
		tenderProject = projectAction.getTenderProject();
		
		titleComposite = new TitleComposite(this, SWT.NONE);
		titleComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		ELink exchange_rate_label = titleComposite.addELink("EXCHANGE_RATE");
		exchange_rate_label.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				ExchangeRateDialog exchangeRateDialog = new ExchangeRateDialog(getShell(), tenderProject, projectRule);
				exchangeRateDialog.setTitle(Messages.SetCurrencyConversionRate);
				exchangeRateDialog.open();
			}
		});
		exchange_rate_label.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/config.png"));
		exchange_rate_label.setText(Messages.SetCurrencyConversionRate);
		
//		import_bidPrice_label = new ELink(composite, SWT.NONE);
//		import_bidPrice_label.addMouseListener(new MouseAdapter() {
//			@Override
//			public void mouseUp(MouseEvent e) {
//				importBidPrice();
//			}
//		});
//		import_bidPrice_label.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/import.png"));
//		import_bidPrice_label.setText("导入投标报价");
		
		editSortNo_btn = titleComposite.addELink("BATCH_SORT");
		editSortNo_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/switch.png"));
		editSortNo_btn.setText(Messages.Button_batchSort);
		editSortNo_btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				editSortNoAction();
			}
		});
		
		addSubbidPriceBtn = titleComposite.addELink("CONFIG_BID_PRICE_TABLE");
		addSubbidPriceBtn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/add.png"));
		addSubbidPriceBtn.setText(Messages.Button_configBidOpiningList);
		addSubbidPriceBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				addSubbidPriceAction();
			}
		});
		
//		ELink importBidPriceBtn = new ELink(composite, SWT.NONE);
//		importBidPriceBtn.addMouseListener(new MouseAdapter() {
//			@Override
//			public void mouseUp(MouseEvent e) {
//				importBidPriceAction();
//			}
//		});
//		importBidPriceBtn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/download.png"));
//		importBidPriceBtn.setText("导入投标报价");
		
		
		bid_price_composite = new Composite(this, SWT.NONE);
		bid_price_composite.setLayout(new FillLayout(SWT.HORIZONTAL));
		bid_price_composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		Composite composite_2 = new Composite(this, SWT.NONE);
		composite_2.setLayout(new GridLayout(1, false));
		composite_2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		save_btn = new EButton(composite_2, SWT.NONE);
		save_btn.setBackground(ColorConstants.SKIN_BG);
		save_btn.setForeground(ColorConstants.SKIN_FOREGROUND);
		save_btn.setActiveBorderColor(ColorConstants.SKIN_ACTIVE_BG);
		save_btn.setActiveBgColor(ColorConstants.SKIN_ACTIVE_BG);
		save_btn.setActiveForeground(ColorConstants.SKIN_ACTIVE_FOREGROUND);
		save_btn.setArcWidth(6);
		save_btn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				saveBidPriceAction();
			}
		});
		save_btn.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
		GridData gd_savebutton_1 = new GridData(SWT.CENTER, SWT.FILL, true, true, 1, 1);
		gd_savebutton_1.heightHint = 35;
		gd_savebutton_1.widthHint = 200;
		save_btn.setLayoutData(gd_savebutton_1);
		save_btn.setText(Messages.Button_save);
		menuFunctionUtils.addFunction(save_btn, "SAVE");

		init();
	}
	
	/**
	 * @Description: 初始化
	 * @author guoyr
	 */
	private void init(){
		
		tenderProjectService = new TenderProjectService();
		projectRuleService = new ProjectRuleService();
		supplierService = new SupplierService();
		bidPriceService = new BidPriceService() ;
		bidPriceResultService = new BidPriceResultService();
		menu = projectAction.getMenu();
		menuFunctionUtils.initFunctionAuthority(menu, titleComposite.getFunctionComposite());
		titleComposite.setTitle(ObjectUtils.getObjString(MenuMessages.getValue(menu.getLanguageCode(), menu.getMenuShortName())));
		if(TenderProjectEnum.LOCAL.equals(tenderProject.getRemoteStatus())) {
			WidgetUtils.setControlVisible(save_btn, true);
		}
		
		supplierList.clear();
		
		SyncThreadSet myThreadSet = new SyncThreadSet(new SyncThreadSet.Runnable() {
			public void run() {
				String bidOpeningStatus = tenderProjectService.getBidOpeningStatusByTenderId(tenderProject.getId());
				tenderProject.setBidOpeningStatus(bidOpeningStatus);
				Display.getDefault().syncExec(new Runnable(){
					public void run(){
						if(!bid_price_composite.isDisposed()){
							// 如果已经完成开标，则不允许修改，不允许添加分项报价
							if(CommonEnum.COMPLETE.equals(tenderProject.getBidOpeningStatus())){
								if(null != save_btn && !save_btn.isDisposed()){
									save_btn.setEnabled(false);								
								}
							}
							refreshBidPrice();
						}
					} 
				});
			}
		});
		
		myThreadSet.addSyncExec(new SyncThread(new SyncThread.Runnable(){
			public void run(){
				projectRule = projectAction.refreshTenderProjectRule();
				isAnonymous  = projectRuleService.isAnonymous(tenderProject.getId());
			}
		} ));
		myThreadSet.addSyncExec(new SyncThread(new SyncThread.Runnable(){
			public void run(){
				if(null != allSupplierList)allSupplierList.clear();
				if(null != bidPriceList)bidPriceList.clear();
				allSupplierList = supplierService.getSupplierOpenBidList(tenderProject.getId());
			}
		} ));
		myThreadSet.start();
	}
	
	
	/**
	 * @Description: 刷新投标报价
	 * @author guoyr 
	 */
	private void refreshBidPrice(){
		if(null == bid_price_composite || bid_price_composite.isDisposed()){
			return;
		}
		for(Control control : bid_price_composite.getChildren()){
			control.dispose();
		}
		if(null != allSupplierList && allSupplierList.size() > 0){
			bidPriceList =bidPriceService.getTenderBidPriceList(tenderProject.getId());
		}
		int index  = 1;
		if(null != allSupplierList){
			for(Supplier supplier : allSupplierList){
				supplier.setAnonymous(isAnonymous,index);
				index++;
			}
			if(PropertiesUtils.getProperty(ConfigConstants.FILTER_NO_SIGN_SUPPLIER, "00").equals("01")){
				supplierList = new ArrayList<Supplier>();
				for(Supplier supplier : allSupplierList){
					if(null != supplier.getSignTime()){
						supplierList.add(supplier);
					}
				}
			}else {
				supplierList = allSupplierList;
			}
		}
		if(null == supplierList){
			supplierList = new ArrayList<Supplier>();
		}
		
		defaultBidPrice = null;
		if(null == bidPriceList || bidPriceList.size() == 0){
			// 如果不存在报价结构，则从招标文件中读取结构
			List<BidPrice> bidPriceTable = BidPriceUtils.getBidPriceTable(tenderProject.getId(), tenderProject.getTenderNo());
			if(null != bidPriceTable && bidPriceTable.size() > 0){
				boolean batchSaveFlag = bidPriceService.batchSaveResolverBidPriceTable(bidPriceTable);
				if(!batchSaveFlag){
					bidPriceList =	bidPriceService.getTenderBidPriceList(tenderProject.getId());
				}
			}
		}
		if(null == bidPriceList || bidPriceList.size() == 0){
			bidPriceList = new ArrayList<BidPrice>();
			defaultBidPrice = new BidPrice();
			defaultBidPrice.setId(UuidUtils.getUUID());
			defaultBidPrice.setTenderId(tenderProject.getId());
			defaultBidPrice.setJoinTotal(BidPriceEnum.JOIN_TOTAL);
			defaultBidPrice.setBidPriceType(BidPriceEnum.IS_PRICE_ITEM);
			defaultBidPrice.setBidPriceName(Messages.BidPrice);
			defaultBidPrice.setBidPriceCode(defaultBidPrice.getId());
			defaultBidPrice.setPriceUnit(projectRule.getPriceUnitUseDefault());
			defaultBidPrice.setSortNo(1);
			bidPriceList.add(defaultBidPrice);
		}
		if(null != bidPriceList && bidPriceList.size() > 0){
			bidPriceResultTable = new SubBidPriceTableComposite(bid_price_composite, SWT.NONE);
		}else {
			bidPriceResultTable = new BidPriceTableComposite(bid_price_composite, SWT.NONE);
		}
		bidPriceResultTable.refreshBidPriceResult(tenderProject, projectRule, supplierList, bidPriceList, save_btn.getVisible() && save_btn.getEnabled());
		bid_price_composite.layout();
	}
	
	/**
	 * @Description: 保存
	 * @author guoyr 
	 */
	private void saveBidPriceAction(){
		if(!save_btn.getEnabled()){
			return;
		}
		// 在保存时，若没有开标一览表结构，则先保存默认的报价项
		if(null != defaultBidPrice){
			if(bidPriceService.insert(defaultBidPrice)){
				defaultBidPrice = null;
			}else {
				MessageDialog.openError(getShell(), Messages.Tips_setBidOpenListError);
				return;
			}
		}
		if(bidPriceResultTable.saveBidPriceResult()){
			refreshBidPrice();
			int bidOpeningSuccessCount = 0;
			if(null != supplierList){
				for(Supplier supplier : supplierList){
					SupplierOpeningResult supplierOpeningResult = supplier.getSupplierOpeningResult();
					if(null != supplierOpeningResult && SupplierEnum.OPENBID_SUCCESS.equals(supplierOpeningResult.getOpeningStatus()) && null != supplierOpeningResult.getBidPrice()){
						bidOpeningSuccessCount ++;
					}
				}
			}
			if(bidOpeningSuccessCount == supplierList.size() && MessageDialog.openConfirm(getShell(), Messages.Button_complateBidOpening, Messages.Tips_bidPriceSavesuccess, Messages.Button_confirm, Messages.Button_cancel)){
				tenderProject.setBidOpeningStatus(CommonEnum.COMPLETE);
				tenderProject.setPriceBidStatus(CommonEnum.COMPLETE);
				tenderProjectService.updateAssignProperty(tenderProject, new String[]{"id" , "bidOpeningStatus", "priceBidStatus"});
				if(null != tenderProject.getParentId()){
					TenderProjectEntity parentTenderProject = new TenderProjectEntity();
					parentTenderProject.setId(tenderProject.getParentId());
					parentTenderProject.setBidOpeningStatus(CommonEnum.COMPLETE);
					tenderProjectService.updateAssignProperty(parentTenderProject, new String[]{"id","bidOpeningStatus"});
				}
				
 				List<BidPriceResult> bidPriceResultList = bidPriceResultService.getBidPriceResultList(tenderProject.getId(), null);
				if(null != bidPriceResultList && bidPriceResultList.size() > 0){
					//进行汇率转换
					ExchangeRateUitls.exchangeRate(tenderProject, bidPriceResultList, (ExchangeRate)projectRule.getParamByKey(ProjectRuleEnum.EXCHANGE_RATE));
				}
				
				if(null != projectAction) {
					projectAction.run();
				}
//				final Action action = ActionUtil.getAction(LoadBidPriceAction.class.getName());
//				action.setTenderProject(tenderProject);
//				action.addActionListener(listener);
//				action.run();
			}else {
				MessageDialog.openShortMessage(Messages.Tips_saveSuccess);
			}
		}else {
			MessageDialog.openError(getShell(), Messages.Dialog_warmTips, Messages.Tips_saveFail);
		}
	}
	
	/**
	 * @Description: 批量编辑
	 * @author guoyr 
	 */
	private void editSortNoAction(){
		SupplierBatchOrderDialog dialog = new SupplierBatchOrderDialog(getShell(),supplierList, new CallBack(){
			public void callBack() {
				refreshBidPrice();
			}
		});
		dialog.open();
	}
	
	/**
	 * @Description: 开标一览表管理
	 * @author guoyr 
	 */
	private void addSubbidPriceAction(){
		if(!addSubbidPriceBtn.getEnabled()){
			return;
		}
 		BidPriceSubItemDialog subBidPriceDialog = new BidPriceSubItemDialog(getShell(), tenderProject, projectRule, menuFunctionUtils);
 		subBidPriceDialog.setTitle(Messages.Button_configBidOpiningList);
 		subBidPriceDialog.open();
 		refreshBidPrice();
	}
	
	public void addActionListener(ActionListener listener){
		this.listener = listener;
	}
	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
	/**
	 * @Description: 导入供应商报价信息
	 * @author guoyr 
	 */
	private void importBidPrice(){
		bidPriceResultTable.importBidPrice();
		refreshBidPrice();
	}
}
