package com.gx.obe.evaluation.step.composite;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.core.utils.WidgetUtils;
import org.eclipse.swt.core.widgets.BigButton;
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.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;

import com.gx.obe.business.entity.BidPriceRound;
import com.gx.obe.common.widget.listener.IRefreshListener;
import com.gx.obe.common.widget.thread.SyncThread;
import com.gx.obe.components.core.enumeration.BidPriceEnum;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.ModelMapper;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.SupplierOpeningResult;
import com.gx.obe.web.entity.price.BidPriceHisResult;
import com.gx.obe.web.entity.price.BidPriceResult;
import com.gx.obe.web.entity.price.Currency;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.entity.tender.TenderProjectRuleEntity;
import com.gx.obe.web.service.BaseDictionaryValueService;
import com.gx.obe.web.service.BidPriceHisResultService;
import com.gx.obe.web.service.BidPriceRoundStatusService;
import com.gx.obe.web.service.SupplierOpeningResultService;
import com.gx.utils.NowTimeUtils;
import com.swtdesigner.SWTResourceManager;

public class HisBidPriceResultComposite extends Composite {

	private Combo currencyCombo;
	private BaseDictionaryValueService dictionaryValueService;
	private SupplierOpeningResultService supplierOpeningResultService;
	private List<BidPriceHisResult> bidPriceResultList;
//	private String unitName;
	private String currencyCode;
	private List<BidPriceHisResultComposite> bidPriceResultCompositeList = new ArrayList<BidPriceHisResultComposite>();
//	private Combo unitCombo;
	private TenderProjectEntity tenderProjectEntity;
	private TenderProjectRuleEntity tenderProjectRuleEntity;
	private Supplier supplier;
	private BidPriceRound curbidPriceRound;
//	private BidPriceResultService bidPriceResultService ;
	private BidPriceHisResultService bidPriceHisResultService ;
	private ScrolledComposite scrolledComposite;
	private Composite bidpriceContent_composite;
	private SupplierOpeningResult supplierOpeningResult;
	private BigButton save_btn;
	private IRefreshListener listener;
	private int maxRound = 1;
	private BidPriceRoundStatusService bidPriceRoundStatusService;
 	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public HisBidPriceResultComposite(Composite parent, int style) {
		super(parent, style);
		setLayout(new GridLayout(1, false));

		
		Composite composite_2 = new Composite(this, SWT.NONE);
		composite_2.setLayoutData(new GridData(SWT.CENTER, SWT.FILL, true, false, 1, 1));
		GridLayout gl_composite_2 = new GridLayout(2, false);
		composite_2.setLayout(gl_composite_2);
		
		CLabel currencyLabel = new CLabel(composite_2, SWT.NONE);
		currencyLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		currencyLabel.setFont(SWTResourceManager.getFont("微软雅黑", 11, SWT.NORMAL));
		currencyLabel.setText(Messages.Currency + "：");
		
		currencyCombo = new Combo(composite_2, SWT.READ_ONLY);
//		currencyCombo.addSelectionListener(new SelectionAdapter() {
//			public void widgetSelected(SelectionEvent e) {
//				currencySelectAction();
//			}
//		});
		GridData gd_currencyCombo = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		gd_currencyCombo.widthHint = 60;
		currencyCombo.setLayoutData(gd_currencyCombo);
		new Label(composite_2, SWT.NONE);
		new Label(composite_2, SWT.NONE);
		
//		CLabel unitLabel = new CLabel(composite_2, SWT.NONE);
//		unitLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
//		unitLabel.setFont(SWTResourceManager.getFont("微软雅黑", 11, SWT.NORMAL));
//		unitLabel.setText(Messages.Unit + "：");
		
//		unitCombo = new Combo(composite_2, SWT.READ_ONLY);
//		GridData gd_combo_1 = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
//		gd_combo_1.widthHint = 50;
//		unitCombo.setLayoutData(gd_combo_1);
//		unitCombo.addSelectionListener(new SelectionAdapter() {
//			public void widgetSelected(SelectionEvent e) {
//				unitSelectAction();
//			}
//		});
		
		scrolledComposite = new ScrolledComposite(this, SWT.H_SCROLL | SWT.V_SCROLL);
		scrolledComposite.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1));
		scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		scrolledComposite.setExpandHorizontal(true);
		scrolledComposite.setExpandVertical(true);
		
		bidpriceContent_composite = new Composite(scrolledComposite, SWT.NONE);
		GridLayout gl_composite_12 = new GridLayout(1, false);
		gl_composite_12.verticalSpacing = 10;
		gl_composite_12.marginWidth = 10;
		bidpriceContent_composite.setLayout(gl_composite_12);
		bidpriceContent_composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		scrolledComposite.setContent(bidpriceContent_composite);
		scrolledComposite.setMinSize(bidpriceContent_composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
		
		save_btn = new BigButton(this, SWT.NONE);
		save_btn.setLayoutData(new GridData(SWT.CENTER, SWT.BOTTOM, true, false, 1, 1));
		save_btn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				saveBidPriceRsultAction();
			}
		});
		save_btn.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
		save_btn.setText(Messages.Button_submit);
		
		init();
	}
	
	private void init(){
		save_btn.setEnabled(false);
		bidPriceRoundStatusService = new BidPriceRoundStatusService();
		dictionaryValueService = new BaseDictionaryValueService();
//		bidPriceResultService = new BidPriceResultService();
		bidPriceHisResultService = new BidPriceHisResultService();
		supplierOpeningResultService = new SupplierOpeningResultService();
	}

	
	/**
	 * @Description: 初始化
	 * @author guoyr
	 */
	public void refresh(TenderProjectEntity tenderProjectEntity, TenderProjectRuleEntity tenderProjectRuleEntity, Supplier supplier, BidPriceRound curbidPriceRound ,int maxRound,IRefreshListener listener){
		this.tenderProjectEntity = tenderProjectEntity;
		this.tenderProjectRuleEntity = tenderProjectRuleEntity;
		this.supplier = supplier;
		this.curbidPriceRound = curbidPriceRound;
		this.listener = listener;
		this.maxRound = maxRound;
//		supplierOpeningResult = supplierOpeningResultService.getSupplierOpeningResult(tenderProjectEntity.getId(), supplier.getId());
//		if(SupplierEnum.OPENBID_SUCCESS.equals(supplierOpeningResult.getBidOpeningStatus()){
//		}else {
//		}
		initCurrencyCombo();
		refreshBidprice();
	}
	
	
	/**
	 * @Description: 初始化币种下拉框
	 * @author chenxw 
	 */
	private void initCurrencyCombo() {
		List<Currency> currencyList = dictionaryValueService.getCurrencyDictionaryList();
		int index = 0;
		for (Currency currency : currencyList) {
			currencyCombo.setData(index + "", currency.getCurrencyCode());
			currencyCombo.add(currency.getCurrencyName(), index);
			currencyCombo.setData(index + "currency", currency);
			if(currency.getCurrencyCode().equals(tenderProjectRuleEntity.getCurrencyCode()) || currency.getCurrencyName().equals(tenderProjectRuleEntity.getCurrencyName())){
				currencyCombo.select(index);
			}
			index++;
		}
		if(currencyCombo.getSelectionIndex() < 0){
			WidgetUtils.setComboSelection(currencyCombo, BidPriceEnum.CNY_CODE);
		}
//		currencySelectAction();
	}
	
	/**
	 * @Description: 币种下拉框选择事件
	 * @author chenxw 
	 */
//	protected void currencySelectAction() {
//		unitCombo.removeAll();
//		Currency currency  = (Currency) currencyCombo.getData(currencyCombo.getSelectionIndex()+"currency");
//		if (null == currency) {
//			return;
//		}
//		List<String> unitList = currency.getPriceUnitList();
//		for(int i = 0; i < unitList.size(); i++){
//			String unit = unitList.get(i);
//			unitCombo.add(unit, i);
//			unitCombo.setData(i+"", unit);
//		}
//		WidgetUtils.setComboSelection(unitCombo, tenderProjectRuleEntity.getPriceUnitUseDefault());
//		if(unitCombo.getSelectionIndex() < 0){
//			unitCombo.select(0);
//		}
//		unitSelectAction();
//	}
	
	/**
	 * @Description: 刷新币种的单位
	 * @author wangxiang 
	 */
//	private void unitSelectAction() {
//		unitName = (String) WidgetUtils.getComboSelection(unitCombo);
//		Currency currency = (Currency) currencyCombo.getData(currencyCombo.getSelectionIndex() + "currency");
//		if(bidPriceResultCompositeList.size() > 0 && null != unitName){
//			for (BidPriceHisResultComposite bidPriceResultComposite : bidPriceResultCompositeList) {
//				if(!bidPriceResultComposite.isDisposed()){
//					bidPriceResultComposite.refreshBidPriceUnit(currency.getCurrencyCode(), currency.getCurrencyName(), unitName);
//					bidPriceResultComposite.layout();
//				}
//			}
//		}
//		bidpriceContent_composite.layout();
//	}
 	private void refreshBidprice(){
		int roundNumber = 0;
		if(curbidPriceRound.getRoundNo() >= 1) {
			roundNumber = curbidPriceRound.getRoundNo();
			if(maxRound == 1 && curbidPriceRound.getRoundNo() == 1) {
				roundNumber = 0;
			}
		}
		bidPriceResultList= bidPriceHisResultService.getSupplierBidPriceHisResultListByRound(tenderProjectEntity.getId(), supplier.getId(),roundNumber) ;
		if(null != bidPriceResultList && bidPriceResultList.size() > 0){
			for (BidPriceHisResult bidPriceResult : bidPriceResultList) {
				if(StringUtils.isEmpty(bidPriceResult.getBidPriceName())){
					continue;
				}
				if(BidPriceEnum.IS_PRICE_ITEM.equals(bidPriceResult.getBidPriceType())){
					currencyCode = bidPriceResult.getCurrencyCode();
//					unitName = bidPriceResult.getPriceUnitCN(tenderProjectRuleEntity.getPriceUnitUseDefault());
					break;
				}
			}
		}
		
		if(StringUtils.isEmpty(currencyCode)){
			currencyCode = BidPriceEnum.CUR_CODE;
		}
		if(StringUtils.hasLength(currencyCode)){
			WidgetUtils.setComboSelection(currencyCombo, currencyCode);
//			currencySelectAction();
			currencyCombo.setEnabled(false);
		}
//		if(StringUtils.hasLength(unitName)){
//			WidgetUtils.setComboSelection(unitCombo, unitName);
//			unitCombo.setEnabled(false);
//		}
		loadBidPriceTable();
	}
	
	/**
	 * @Description: 加载开标一览表结构
	 * @author guoyr 
	 */
	private void loadBidPriceTable(){

		for(Control control : bidpriceContent_composite.getChildren()){
			control.dispose();
		}
		boolean complate =  bidPriceRoundStatusService.isCompletePriceBySupplier(curbidPriceRound.getId(),supplier.getId());
		if(null != bidPriceResultList && bidPriceResultList.size() > 0){	
			for(BidPriceHisResult bidPriceHisResult : bidPriceResultList){
				bidPriceHisResult.setTenderId(tenderProjectEntity.getId());
				bidPriceHisResult.setSupplierId(supplier.getId());
				BidPriceHisResultComposite bidPriceResultComposite = new BidPriceHisResultComposite(bidpriceContent_composite, SWT.NONE);
				bidPriceResultComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
				bidPriceResultComposite.refreshBidPriceHisResult(bidPriceHisResult, tenderProjectRuleEntity.getPriceUnitUseDefault());
				bidPriceResultCompositeList.add(bidPriceResultComposite);
				if(complate){
					complate = true;
					bidPriceResultComposite.setEditable(false);
				}
				if (BidPriceEnum.IS_PRICE_ITEM.equals(bidPriceHisResult.getBidPriceType())) {
					bidPriceResultComposite.setPriceItem();
				}
			}
		}
		bidpriceContent_composite.layout();
		scrolledComposite.setMinSize(bidpriceContent_composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
		scrolledComposite.setMinHeight(bidpriceContent_composite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y + 20);
		if(complate){
			save_btn.setText(Messages.Opening_complated);
			save_btn.setEnabled(false);
		}else {
			save_btn.setEnabled(true);
			save_btn.setText(Messages.Button_submit);
		}
		layout();
	}
	
	/**
	 * @Description: 保存
	 * @author guoyr 
	 */
	private void saveBidPriceRsultAction(){
		if(!save_btn.getEnabled())return;
		if(!MessageDialog.openConfirm(getShell(), Messages.Dialog_warmTips, "确认提交报价结果吗？", new String[]{Messages.Button_confirm,Messages.Button_cancel})) {
			return ;
		}
		
		final Currency currency  = (Currency) currencyCombo.getData(currencyCombo.getSelectionIndex()+"currency");
		if(null == currency){
			MessageDialog.openShortMessage(MessageFormat.format(Messages.Tips_pleaseSelect, Messages.Currency));
			return;
		}
//		if(StringUtils.isEmpty(unitName)){
//			MessageDialog.openShortMessage(MessageFormat.format(Messages.Tips_pleaseSelect, Messages.Unit));
//			return;
//		}
		SyncThread syncThread = new SyncThread(new SyncThread.Runnable(){
			public void run() {	
				Display.getDefault().syncExec(new Runnable(){public void run(){
					if(saveBidPriceRsult(currency)){
						listener.refresh(curbidPriceRound);
						loadBidPriceTable();			
					}else{
						MessageDialog.openWarning(getShell(), Messages.Tips_saveFail);
					}
					
				}});
			}
		});
		syncThread.setMessage(Messages.Tips_requesting);
		syncThread.start();
	}
	
	private boolean saveBidPriceRsult(Currency currency ){
		List<BidPriceHisResult> bidPriceResultList = new ArrayList<BidPriceHisResult>();
		for(BidPriceHisResultComposite bidPriceResultComposite : bidPriceResultCompositeList){
			if(!bidPriceResultComposite.isDisposed()){
				BidPriceResult bidPriceResult = bidPriceResultComposite.getBidPriceResult();
				BidPriceHisResult bidPriceHisResult = ModelMapper.map(bidPriceResult, BidPriceHisResult.class, null);
				bidPriceHisResult.setBidPriceRound(curbidPriceRound.getRoundNo());
				bidPriceHisResult.setRoundName(curbidPriceRound.getRoundName());
//				bidPriceHisResult.setPriceUnit(unitName);
				bidPriceHisResult.setCurrencyCode(currencyCode);
				bidPriceHisResult.setCreateTime(NowTimeUtils.getNowDate());
				bidPriceHisResult.setFinalBidPrice(bidPriceResult.getBidPrice());
				bidPriceHisResult.setEvaluationPrice(bidPriceResult.getBidPrice());

				if(BidPriceEnum.IS_PRICE_ITEM.equals(bidPriceResult.getBidPriceType())){
					if(null == bidPriceResultComposite.getBidPriceResult()){
						MessageDialog.openWarning(getShell(), MessageFormat.format(Messages.Tips_pleaseEnter, bidPriceResult.getBidPriceName()));
						return false;
					}
				}
				bidPriceResultList.add(bidPriceHisResult);
			}
		}
		bidPriceResultCompositeList.clear();
		if(bidPriceHisResultService.saveUpateSupplierReBidPriceHisResult(tenderProjectEntity.getId(), supplier.getId(), bidPriceResultList,curbidPriceRound.getId())){
			supplierOpeningResult = supplierOpeningResultService.getSupplierOpeningResult(tenderProjectEntity.getId(), supplier.getId());
			bidPriceRoundStatusService.updatRoundStatus(curbidPriceRound);
		}else{
			
			return false;	
		}
		supplier.setSupplierOpeningResult(supplierOpeningResult);
		return true;	
	}
	
	
	
	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

}
