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

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.utils.SwtUtils;
import org.eclipse.swt.core.widgets.EButton;
import org.eclipse.swt.core.widgets.ECombo;
import org.eclipse.swt.core.widgets.EDialog;
import org.eclipse.swt.core.widgets.ELink;
import org.eclipse.swt.core.widgets.ESepator;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import com.gx.obe.ColorConstants;
import com.gx.obe.DictValueEnum;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.evaluation.step.checker.BaseChecker;
import com.gx.obe.evaluation.step.composite.clear.ArithmeticErrorItemListComposite;
import com.gx.obe.evaluation.step.composite.clear.ErrorLeakItemListComposite;
import com.gx.obe.evaluation.step.composite.clear.InventoryPriceItemListComposite;
import com.gx.obe.evaluation.step.composite.clear.MaterialPriceItemListComposite;
import com.gx.obe.evaluation.step.composite.clear.UnCompeteItemListComposite;
import com.gx.obe.evaluation.step.inter.IBoqChecker;
import com.gx.obe.evaluation.step.inter.IChecker;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.web.entity.DictionaryValue;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.evaluation.EvaluationStep;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.service.SupplierService;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

public class ViewCleanTenderDetailDialog extends EDialog {
	
	private SupplierService supplierService = new SupplierService();
	private TenderProjectEntity tenderProject;
	private Supplier supplier;
	private EvaluationStep evaluationStep;
	private List<Supplier> supplierList;
	// 淡红色色
	private Composite staticComposite;
//	private Composite contentComposite;
	private Composite messageComposite;
	private CLabel messageLabel;
	private Composite cleanTenderResultComposite;
	private DictionaryValue dictionaryValue;
	private Composite cleanTenderDetailComposite;
	private StackLayout sl_staticComposite = new StackLayout();
	private Composite composite_supplier;
	private Composite detailLoadComposite;
	private ELink preSupplierBtn;
	private ELink nextSupplierBtn;
	private ECombo supplierCombo;
	private Button showErrorOnlyBtn;
	private IBoqChecker boqChecker;
	private CLabel errorNumLabel;
	private EButton viewBoqBtn;
	private Map<String, IChecker> checkerMap = new HashMap<String, IChecker>();
	
	/**
	 * Create the dialog.
	 * 
	 * @param parentShell
	 */
	public ViewCleanTenderDetailDialog(Shell parentShell, TenderProjectEntity tenderProject, Supplier supplier, EvaluationStep evaluationStep, DictionaryValue dictionaryValue) {
		super(parentShell);
		this.tenderProject = tenderProject;
		this.dictionaryValue = dictionaryValue;
		this.supplier = supplier;
		this.evaluationStep = evaluationStep;
	}
	
	/**
	 * Create contents of the dialog.
	 * 
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		
		staticComposite = (Composite) super.createDialogArea(parent);
		staticComposite.setLayout(sl_staticComposite);
		
		cleanTenderDetailComposite = new Composite(staticComposite, SWT.NONE);
		GridLayout gl_cleanTenderDetailComposite = new GridLayout(1, false);
		gl_cleanTenderDetailComposite.verticalSpacing = 0;
		gl_cleanTenderDetailComposite.marginHeight = 0;
		gl_cleanTenderDetailComposite.marginWidth = 0;
		cleanTenderDetailComposite.setLayout(gl_cleanTenderDetailComposite);
		
		composite_supplier = new Composite(cleanTenderDetailComposite, SWT.NONE);
		composite_supplier.setBackgroundMode(SWT.INHERIT_FORCE);
		GridLayout gl_composite_supplier = new GridLayout(7, false);
		composite_supplier.setLayout(gl_composite_supplier);
		composite_supplier.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		supplierCombo = new ECombo(composite_supplier, SWT.NONE);
		GridData gd_selectCaType_combo_combo = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gd_selectCaType_combo_combo.widthHint = 300;
		supplierCombo.setBorderColor(SWTResourceManager.getColor(60, 138, 226));
		supplierCombo.setLayoutData(gd_selectCaType_combo_combo);
		supplierCombo.setText("");
		supplierCombo.setHintText("--请选择供应商--");
		supplierCombo.setDownArrowImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/arrow_down_simp.png"));
		supplierCombo.addSelectionListener(new ECombo.ComboSelectoinListener() {
			@Override
			public void itemSelectoin(String name, Object value, int index) {
				loadCleanTenderDetail(supplierList.get(index));
			}
		});
		
		preSupplierBtn = new ELink(composite_supplier, SWT.NONE);
		preSupplierBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				viewNextSupplier(-1);
			}
		});
		preSupplierBtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		preSupplierBtn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/arrow_up.png"));
		preSupplierBtn.setText("上一家");
		
		nextSupplierBtn = new ELink(composite_supplier, SWT.NONE);
		nextSupplierBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				viewNextSupplier(1);
			}
		});
		nextSupplierBtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		nextSupplierBtn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/arrow_down.png"));
		nextSupplierBtn.setText("下一家");
		
		errorNumLabel = new CLabel(composite_supplier, SWT.NONE);
		errorNumLabel.setAlignment(SWT.CENTER);
		errorNumLabel.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		errorNumLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		errorNumLabel.setText("");
		
		showErrorOnlyBtn = new Button(composite_supplier, SWT.CHECK);
		showErrorOnlyBtn.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				loadCheckDetail(null);
			}
		});
		showErrorOnlyBtn.setText("只显示错误项");
		
		viewBoqBtn = new EButton(composite_supplier, SWT.NONE);
		viewBoqBtn.setText("查看工程量清单");
		viewBoqBtn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/view.png"));
		viewBoqBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				viewBoqAction();
			}
		});
		
		ESepator sep = new ESepator(cleanTenderDetailComposite, SWT.SEPARATOR | SWT.HORIZONTAL);
		sep.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		sep.setBackground(ColorConstants.SEP_LIGHT_COLOR);
		
		detailLoadComposite = new Composite(cleanTenderDetailComposite, SWT.NONE);
		detailLoadComposite.setLayout(new FillLayout(SWT.HORIZONTAL));
		detailLoadComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		cleanTenderResultComposite = new Composite(staticComposite, SWT.NONE);
		cleanTenderResultComposite.setLayout(new FillLayout(SWT.HORIZONTAL));
		
		messageComposite = new Composite(staticComposite, SWT.NONE);
		messageComposite.setLayout(new GridLayout(1, false));
		
		messageLabel = new CLabel(messageComposite, SWT.NONE);
		messageLabel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/hourglass.png"));
		messageLabel.setFont(SWTResourceManager.getFont("微软雅黑", 20, SWT.BOLD));
		messageLabel.setForeground(ColorConstants.NOTE_TIPS_COLOR);
		messageLabel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 1));
		messageLabel.setText("正在进行特征码检查，请稍等...");
		
		init();
		return staticComposite;
	}
	
	/**
	 * Description: 初始化
	 * Create Date: Jul 2, 20143:24:24 PM<br/>
	 * Author : guoyr <br/>
	 * Modify Date: <br/>
	 * Modify By : <br/>
	 */
	private void init() {
		this.setTitle(dictionaryValue.getDictValueName());
		messageLabel.setText("正在加载" + dictionaryValue.getDictValueName() + "结果，请稍等...");
		supplierList = supplierService.getEvaluationStepSupplierList(tenderProject.getId(), evaluationStep);
		
		supplierList = supplierService.getEvaluationStepSupplierList(tenderProject.getId(), evaluationStep);
		supplierCombo.removeAll();
		if (null != supplierList) {
			for (Supplier _supplier : supplierList) {
				supplierCombo.addItem(_supplier.getSupplierName(), _supplier.getId());
			}
		}
		if (null != supplier) {
			supplierCombo.setSelectionValue(supplier.getId());
		}
		loadCleanTenderDetail(supplier);
	}
	
	/**
	 * Description: 开始清标
	 * Create Date: Jun 18, 20141:36:33 PM<br/>
	 * Author : guoyr <br/>
	 * Modify Date: <br/>
	 * Modify By : <br/>
	 */
	private void loadCleanTenderDetail(final Supplier curSupplier) {
		
		IChecker curChecker = null != curSupplier ? checkerMap.get(curSupplier.getId()) : null;
		if (null != curChecker) {
			loadCheckDetail(curChecker);
		} else {
			sl_staticComposite.topControl = messageComposite;
			staticComposite.layout();
			Thread drawKTableThread = new Thread(new Runnable() {
				public void run() {
					final IChecker checker = BaseChecker.getCleanTenderChecker(tenderProject, evaluationStep, dictionaryValue, curSupplier);
					checkerMap.put(curSupplier.getId(), checker);
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {}
					Display.getDefault().syncExec(new Runnable() {
						public void run() {
							if (null != cleanTenderResultComposite && !cleanTenderResultComposite.isDisposed()) {
								loadCheckDetail(checker);
							}
						}
					});
				}
			});
			drawKTableThread.start();
		}
	}
	
	/**
	 * @Description: 加载检查详情
	 * @author guoyr
	 * @param checker
	 */
	private void loadCheckDetail(IChecker checker) {
		if (checker == null) {
			return;
		}
		if (supplierCombo.getSelectionIndex() == 0) {
			preSupplierBtn.setEnabled(false);
			if (supplierCombo.getItemCount() > 0) {
				nextSupplierBtn.setEnabled(true);
			}
		} else {
			if (supplierCombo.getSelectionIndex() == supplierCombo.getItemCount() - 1) {
				nextSupplierBtn.setEnabled(false);
			} else {
				nextSupplierBtn.setEnabled(true);
			}
			preSupplierBtn.setEnabled(true);
		}
		StringBuilder message = new StringBuilder();
		if (checker.getErrorCount() > 0) {
			showErrorOnlyBtn.setEnabled(true);
			message.append("共[" + checker.getErrorCount() + "]处错误。  ");
		} else {
			message.append("无错误。 ");
			showErrorOnlyBtn.setEnabled(false);
		}
		// 算术性错误检查
		if (ObjectUtils.equals(dictionaryValue.getDictValueCode(), DictValueEnum.CleanTender.ARITHMETIC_ERROR)) {
			
			if (null == boqChecker) {
				boqChecker = new ArithmeticErrorItemListComposite(detailLoadComposite, SWT.NONE);
			}
			String calculationError = evaluationStep.getEvaluationParamByKey(EvaluationStep.CALCULATION_ERROR);
			// 如果是根据差额率来计算
			if (ObjectUtils.equals(calculationError, EvaluationStep.CALCULATION_ERROR_RATE)) {
				BigDecimal rate = evaluationStep.getEvaluationParamByKey(EvaluationStep.CALCULATION_ERROR_RATE, BigDecimal.class);
				if (null == rate || rate.compareTo(BigDecimal.ZERO) == 0) {
					rate = BigDecimal.valueOf(5);
				}
				message.append("差额率超过[±");
				message.append(rate);
				message.append("%]为算术错误。");
			} else {
				BigDecimal value = evaluationStep.getEvaluationParamByKey(EvaluationStep.CALCULATION_ERROR_VALUE, BigDecimal.class);
				if (null == value || value.compareTo(BigDecimal.ZERO) == 0) {
					value = BigDecimal.valueOf(20);
				}
				message.append("差额超过[±");
				message.append(value);
				message.append("]元为算术错误。");
			}
			
		} else if (ObjectUtils.equals(dictionaryValue.getDictValueCode(), DictValueEnum.CleanTender.ERROR_LEAK)) {
			// 错漏项检查
			if (null == boqChecker) {
				boqChecker = new ErrorLeakItemListComposite(detailLoadComposite, SWT.NONE);
			}
		} else if (ObjectUtils.equals(dictionaryValue.getDictValueCode(), DictValueEnum.CleanTender.UNCOMPETE_CHECK)) {
			// 不可竞争费检查
			if (null == boqChecker) {
				boqChecker = new UnCompeteItemListComposite(detailLoadComposite, SWT.NONE);
			}
		} else if (ObjectUtils.equals(dictionaryValue.getDictValueCode(), DictValueEnum.CleanTender.INVENTORY_PRICE)) {
			// 清单报价检查
			if (null == boqChecker) {
				boqChecker = new InventoryPriceItemListComposite(detailLoadComposite, SWT.NONE);
			}
			
			BigDecimal priceRateMaxRate = evaluationStep.getEvaluationParamByKey(EvaluationStep.MAX_DIFFERENCE_RATE, BigDecimal.class);
			if (null == priceRateMaxRate || priceRateMaxRate.compareTo(BigDecimal.ZERO) <= 0) {
				priceRateMaxRate = BigDecimal.valueOf(25);
			}
			BigDecimal priceRateMinRate = evaluationStep.getEvaluationParamByKey(EvaluationStep.MIN_DIFFERENCE_RATE, BigDecimal.class);
			if (null == priceRateMinRate || priceRateMinRate.compareTo(BigDecimal.ZERO) >= 0) {
				priceRateMinRate = BigDecimal.valueOf(-25);
			}
			message.append("差额率大于[");
			message.append(priceRateMaxRate);
			message.append("%]为过高，小于[");
			message.append(priceRateMinRate);
			message.append("%]为过低。");
			
		} else if (ObjectUtils.equals(dictionaryValue.getDictValueCode(), DictValueEnum.CleanTender.MATERIAL_PRICE)) {
			// 材料报价检查
			if (null == boqChecker) {
				boqChecker = new MaterialPriceItemListComposite(detailLoadComposite, SWT.NONE);
			}
			
			BigDecimal priceRateMaxRate = evaluationStep.getEvaluationParamByKey(EvaluationStep.MAX_DIFFERENCE_RATE, BigDecimal.class);
			if (null == priceRateMaxRate || priceRateMaxRate.compareTo(BigDecimal.ZERO) <= 0) {
				priceRateMaxRate = BigDecimal.valueOf(25);
			}
			BigDecimal priceRateMinRate = evaluationStep.getEvaluationParamByKey(EvaluationStep.MIN_DIFFERENCE_RATE, BigDecimal.class);
			if (null == priceRateMinRate || priceRateMinRate.compareTo(BigDecimal.ZERO) >= 0) {
				priceRateMinRate = BigDecimal.valueOf(-25);
			}
			message.append("差额率大于±");
			message.append(priceRateMaxRate);
			message.append("%为过高，小于");
			message.append(priceRateMinRate);
			message.append("%为过低。");
		}
		if (showErrorOnlyBtn.getSelection()) {
			boqChecker.listErrorOnlyCheckDetail(checker);
		} else {
			boqChecker.listCheckDetail(checker);
		}
		errorNumLabel.setText(message.toString());
		sl_staticComposite.topControl = cleanTenderDetailComposite;
		detailLoadComposite.layout();
		staticComposite.layout();
	}
	
	/**
	 * @Description:
	 * @author guoyr
	 * @param preOrNext
	 */
	private void viewNextSupplier(int preOrNext) {
		int selectIndex = supplierCombo.getSelectionIndex();
		if (selectIndex + preOrNext >= 0 && selectIndex + preOrNext < supplierList.size()) {
			supplierCombo.select(selectIndex + preOrNext);
			loadCleanTenderDetail(supplierList.get(selectIndex + preOrNext));
		}
	}
	
	/**
	 * @Description: 查看工程量清单
	 * @author guoyr
	 */
	private void viewBoqAction() {
		if (supplierCombo.getSelectionIndex() >= 0 && supplierCombo.getSelectionIndex() < supplierList.size()) {
			ViewBoqDialog dialog = new ViewBoqDialog(getShell(), tenderProject, supplierList.get(supplierCombo.getSelectionIndex()), evaluationStep);
			dialog.open();
		}
	}
	
	/**
	 * Return the initial size of the dialog.
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(SwtUtils.SCREEN_WIDTH, SwtUtils.SCREEN_HEIGHT);
	}
}
