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

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.MessageDialog;
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.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
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.Display;

import com.gx.obe.ColorConstants;
import com.gx.obe.common.file.utils.ParsingXmlUtils;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.common.widget.composite.ESashForm;
import com.gx.obe.evaluation.step.listener.AiEvaluationListener;
import com.gx.obe.util.utils.CollectionUtils;
import com.gx.obe.web.entity.Struct;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.evaluation.EvaluationFactor;
import com.gx.obe.web.entity.evaluation.EvaluationStep;
import com.gx.obe.web.entity.expert.Expert;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.service.StructService;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/**
 * @Description: 智能评审供应商列表
 * @author chenxw
 */
public class AiEvaluationSupplierComposite extends Composite {
	
	private StructService structService;
	private EvaluationStep curStep;
	private EvaluationFactor curFactor;
	private AiEvaluationListener listener;
	private EvaluationSupplierComposite evaluationSupplier;
	private Composite leftComposite;
	private Supplier curSupplier;
	private boolean isStruct = false;
	private BidFileOrSkipComposite bidFileComposite;
	private Composite rightComposite;
	private StackLayout stackLayout = new StackLayout();
	private TenderProjectEntity curTender;
	private Expert curExpert;
	private StructListComposite structListComposite;
	private ESashForm sashForm;
	private CLabel supplierNameLabel;
	private ELink displayInterfaceLink;
	private List<Supplier> supplierList;
	private ExecutorService executorService;
	private Map<String, List<Struct>> structListMap = new Hashtable<String, List<Struct>>();;
	
	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public AiEvaluationSupplierComposite(Composite parent, int style) {
		super(parent, style);
		this.addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent e) {
				if (null != executorService) executorService.shutdownNow();
			}
		});
		GridLayout gl_supplierComposite = new GridLayout(1, false);
		gl_supplierComposite.verticalSpacing = 0;
		gl_supplierComposite.horizontalSpacing = 0;
		gl_supplierComposite.marginHeight = 0;
		gl_supplierComposite.marginWidth = 0;
		this.setLayout(gl_supplierComposite);
		this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		Composite composite = new Composite(this, SWT.NONE);
		composite.setLayout(new GridLayout(2, false));
		composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		supplierNameLabel = new CLabel(composite, SWT.NONE);
		supplierNameLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		displayInterfaceLink = new ELink(composite, SWT.NONE);
		displayInterfaceLink.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				isStruct = !isStruct;
				displayInterface(true);
			}
		});
		displayInterfaceLink.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		
		ESepator sepLabTop = new ESepator(this, SWT.HORIZONTAL);
		sepLabTop.setBackground(ColorConstants.SEP_LIGHT_COLOR);
		sepLabTop.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		
		sashForm = new ESashForm(this, SWT.NONE);
		sashForm.setBackground(ColorConstants.SKIN_BG);
		sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		sashForm.setSashWidth(7);
		
		leftComposite = new Composite(sashForm, SWT.NONE);
		leftComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		GridLayout gl_leftComposite = new GridLayout(1, false);
		gl_leftComposite.marginHeight = 0;
		gl_leftComposite.marginWidth = 0;
		leftComposite.setLayout(gl_leftComposite);
		
		rightComposite = new Composite(sashForm, SWT.NONE);
		rightComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		rightComposite.setLayout(stackLayout);
		structService = new StructService();
	}
	
	/**
	 * @Description: 刷新
	 * @author chenxw
	 */
	public void refresh(EvaluationFactor curFactor) {
		
		this.curFactor = curFactor;
		this.curTender = listener.getCurTender();
		this.curExpert = listener.getCurExpert();
		this.curStep = listener.getCurStep();
		this.supplierList = listener.getSupplierList();
		
		refreshSupplierEvaluationComposite();
		refreshStructListMap();
	}
	
	/**
	 * @Description: 刷新供应商评审界面
	 * @author chenxw
	 */
	private void refreshSupplierEvaluationComposite() {
		if (null == evaluationSupplier || evaluationSupplier.isDisposed()) {
			if (curStep.getStepType().equals(com.gx.obe.components.core.enumeration.EvaluationStepEnum.COMPLIANCE)) {
				evaluationSupplier = new AiEvaluationComplianceComposite(leftComposite, SWT.NONE);
			} else if (curStep.getStepType().equals(com.gx.obe.components.core.enumeration.EvaluationStepEnum.DETAIL)) {
				evaluationSupplier = new AiEvaluationScoreComposite(leftComposite, SWT.NONE);
			}
			evaluationSupplier.addAiEvaluationListener(listener);
			evaluationSupplier.setStructListMap(structListMap);
		}
		evaluationSupplier.refresh(curFactor);
		leftComposite.layout();
	}
	
	/**
	 * @Description: 刷新结构化数据
	 * @author chenxw
	 */
	private void refreshStructListMap() {
		if (null != executorService) executorService.shutdownNow();
		if (supplierList.isEmpty()) {
			return;
		}
		executorService = Executors.newFixedThreadPool(supplierList.size() > 5 ? 5 : supplierList.size());
		structListMap.clear();
		for (final Supplier supplier : supplierList) {
			executorService.submit(new Runnable() {
				public void run() {
					List<Struct> structList = structService.getStructBySupplierIdAndFactorIdList(curTender.getId(), supplier.getId(), curFactor.getId());
					if (CollectionUtils.isNull(structList)) {
						structList = ParsingXmlUtils.parsingStructXML(curTender.getId(), supplier.getId(), curFactor.getId(), curFactor.getDataType());
						if (CollectionUtils.isNull(structList)) {
							structList = new ArrayList<Struct>();
						} else {
							structService.batchSave(structList);
							structList = structService.getStructBySupplierIdAndFactorIdList(curTender.getId(), supplier.getId(), curFactor.getId());
						}
					}
					structListMap.put(supplier.getId(), structList);
				}
			});
		}
		executorService.shutdown();
		new Thread(new Runnable() {
			public void run() {
				boolean _awaitTermination;
				try {
					_awaitTermination = executorService.awaitTermination(5, TimeUnit.SECONDS);
				} catch (InterruptedException e) {
					_awaitTermination = false;
				}
				final boolean awaitTermination = _awaitTermination;
				Display.getDefault().syncExec(new Runnable() {
					public void run() {
						if (awaitTermination) {
							evaluationSupplier.redrawTable();
						} else {
							MessageDialog.openError(getShell(), "加载数据出错！");
						}
					}
				});
			}
		}).start();
	}
	
	/**
	 * @Description: 选择供应商事件
	 * @author chenxw
	 * @param curSupplier
	 */
	public void selectingSupplierAction(Supplier curSupplier) {
		this.curSupplier = curSupplier;
		supplierNameLabel.setText(curSupplier.getSupplierName());
		
		boolean _isStruct = isStruct;
		isStruct = CollectionUtils.isNotNull(structListMap.get(curSupplier.getId()));
		displayInterface(isStruct != _isStruct);
	}
	
	/**
	 * @Description: 显示界面
	 * @author chenxw
	 * @param isAlter
	 */
	private void displayInterface(boolean isAlter) {
		if (isStruct) {
			if (null == structListComposite || structListComposite.isDisposed()) {
				structListComposite = new StructListComposite(rightComposite, SWT.NONE);
				structListComposite.addAiEvaluationListener(listener);
			}
			structListComposite.refresh(structListMap.get(curSupplier.getId()));
			stackLayout.topControl = structListComposite;
			displayInterfaceLink.setText("查看投标文件");
			displayInterfaceLink.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/pdf_16.png"));
		} else {
			if (null == bidFileComposite || bidFileComposite.isDisposed()) {
				bidFileComposite = new BidFileOrSkipComposite(rightComposite, SWT.NONE);
			}
			bidFileComposite.refresh(curTender, curSupplier, curExpert, curFactor);
			stackLayout.topControl = bidFileComposite;
			displayInterfaceLink.setText("查看结构化数据");
			displayInterfaceLink.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/items.png"));
		}
		if (isAlter) {
			if (isStruct) sashForm.setWeights(new int[] { 7, 3 });
			else sashForm.setWeights(new int[] { 5, 5 });
		}
		evaluationSupplier.resizeColumnOptimal();
		displayInterfaceLink.getParent().layout();
		rightComposite.layout();
		sashForm.layout();
	}
	
	/**
	 * @Description: 刷新投标人结构化数据
	 * @author chenxw
	 * @param supplierId
	 */
	public void refreshSupplierStruct(String supplierId) {
		evaluationSupplier.refreshSupplierStruct(supplierId);
	}
	
	/**
	 * @Description: 刷新投标人结果
	 * @author chenxw
	 * @param supplierId
	 */
	public void refreshSupplierResult(String supplierId) {
		evaluationSupplier.refreshSupplierResult(supplierId);
	}
	
	public void addAiEvaluationListener(AiEvaluationListener listener) {
		this.listener = listener;
	}
	
	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
	
}
