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

import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.ImageResolver;
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.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
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 com.gx.obe.ColorConstants;
import com.gx.obe.common.file.entity.BidFile;
import com.gx.obe.common.file.entity.EvaluationPoint;
import com.gx.obe.common.file.enumeration.FileConstants;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.common.widget.shell.SelectionShell;
import com.gx.obe.config.ConfigConstants;
import com.gx.obe.config.utils.PropertiesUtils;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.CollectionUtils;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.evaluation.EvaluationFactor;
import com.gx.obe.web.entity.expert.Expert;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.tools.ole.DocumentFactory;
import com.gx.tools.ole.DocumentLoader;
import com.gx.tools.ole.LoadFileListener;
import com.gx.tools.utils.CaInfoUtil;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

public class BidFileOrSkipComposite extends Composite implements SelectionShell.SelectionListener<Object> {
	
	private BidFileLRU bidFileLRU = new BidFileLRU();
	private Composite bidFileComposite;
	private Composite noBidFileComposite;
	private StackLayout bidFileStackLayout = new StackLayout();
	private ImageResolver imageResolver = new ImageResolver();
	private CLabel bidFileLabel, pointLabel;
	private ELink bidFileListLabel, pointListLabel;
	private boolean useSpecialPdf;
	private boolean showOleToolBar;
	private TenderProjectEntity tenderProject;
	private Supplier supplier;
	private Expert expert;
	private EvaluationFactor evaluationFactor;
	private Composite bidFileTitleComposite;
	
	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public BidFileOrSkipComposite(Composite parent, int style) {
		super(parent, style);
		GridLayout gl_composite = new GridLayout(1, false);
		gl_composite.verticalSpacing = 0;
		gl_composite.horizontalSpacing = 0;
		gl_composite.marginHeight = 0;
		gl_composite.marginWidth = 0;
		setLayout(gl_composite);
		
		bidFileTitleComposite = new Composite(this, SWT.NONE);
		GridLayout gl_bidFileTitleComposite = new GridLayout(2, false);
		gl_bidFileTitleComposite.marginHeight = 0;
		gl_bidFileTitleComposite.marginWidth = 0;
		gl_bidFileTitleComposite.horizontalSpacing = 50;
		bidFileTitleComposite.setLayout(gl_bidFileTitleComposite);
		bidFileTitleComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		Composite composite = new Composite(bidFileTitleComposite, SWT.NONE);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		composite.setLayout(new GridLayout(2, false));
		
		bidFileLabel = new CLabel(composite, SWT.NONE);
		bidFileLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		bidFileLabel.setText("文件名称");
		bidFileLabel.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		bidFileLabel.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		bidFileLabel.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				listAction(bidFileLabel, BidFile.getBidFileExamineList(tenderProject.getId(), supplier.getId(), expert.getEvalBidType()), LabelType.BID_FILE);
			}
		});
		bidFileListLabel = new ELink(composite, SWT.NONE);
		bidFileListLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, true, 1, 1));
		bidFileListLabel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/next.png"));
		bidFileListLabel.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				listAction(bidFileLabel, BidFile.getBidFileExamineList(tenderProject.getId(), supplier.getId(), expert.getEvalBidType()), LabelType.BID_FILE);
			}
		});
		
		Composite composite_1 = new Composite(bidFileTitleComposite, SWT.NONE);
		composite_1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		composite_1.setLayout(new GridLayout(2, false));
		
		pointLabel = new CLabel(composite_1, SWT.NONE);
		pointLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		pointLabel.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		pointLabel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/link.png"));
		pointLabel.setText("响应点名称");
		pointLabel.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				String respItemPath = FileConstants.getBidFilePath(tenderProject.getId(), supplier.getId()).concat(FileConstants.PSD_XML);
				listAction(pointLabel, BidFile.getBidFileEvaluationPointList(respItemPath, evaluationFactor.getFactorCode()), LabelType.EVALUATION_POINT);
			}
		});
		
		pointListLabel = new ELink(composite_1, SWT.NONE);
		pointListLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, true, 1, 1));
		pointListLabel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/next.png"));
		pointListLabel.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				String respItemPath = FileConstants.getBidFilePath(tenderProject.getId(), supplier.getId()).concat(FileConstants.PSD_XML);
				listAction(pointLabel, BidFile.getBidFileEvaluationPointList(respItemPath, evaluationFactor.getFactorCode()), LabelType.EVALUATION_POINT);
			}
		});
		
		bidFileComposite = new Composite(this, SWT.NONE);
		bidFileComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		bidFileComposite.setLayout(bidFileStackLayout);
		
		noBidFileComposite = new Composite(bidFileComposite, SWT.NONE);
		GridLayout gl_noBidFileComposite = new GridLayout(1, false);
		gl_noBidFileComposite.verticalSpacing = 0;
		gl_noBidFileComposite.horizontalSpacing = 0;
		gl_noBidFileComposite.marginHeight = 0;
		gl_noBidFileComposite.marginWidth = 0;
		noBidFileComposite.setLayout(gl_noBidFileComposite);
		
		ESepator noBidFileSep = new ESepator(noBidFileComposite, SWT.HORIZONTAL);
		noBidFileSep.setBackground(ColorConstants.SEP_LIGHT_COLOR);
		noBidFileSep.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		
		CLabel noBidFileLabel = new CLabel(noBidFileComposite, SWT.NONE);
		noBidFileLabel.setForeground(SWTResourceManager.getColor(200, 200, 200));
		noBidFileLabel.setFont(SWTResourceManager.getFont("宋体", 40, SWT.BOLD));
		noBidFileLabel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 1));
		noBidFileLabel.setText(Messages.Tips_noBidFiles);
		
		init();
	}
	
	private void init() {
		useSpecialPdf = PropertiesUtils.getProperty(ConfigConstants.USE_SPECIAL_PDF, "00").equals("01");
	}
	
	public void refresh(TenderProjectEntity tenderProject, Supplier supplier, Expert expert, EvaluationFactor evaluationFactor) {
		this.tenderProject = tenderProject;
		this.supplier = supplier;
		this.expert = expert;
		this.evaluationFactor = evaluationFactor;
		refreshBidFileComposite();
	}
	
	/**
	 * @Description: 刷新投标文件界面
	 * @author chenxw
	 */
	public void refreshBidFileComposite() {
		String respItemPath = FileConstants.getBidFilePath(tenderProject.getId(), supplier.getId()).concat(FileConstants.PSD_XML);
		List<EvaluationPoint> pointList = BidFile.getBidFileEvaluationPointList(respItemPath, evaluationFactor.getFactorCode());
		List<BidFile> bidFileList = BidFile.getBidFileExamineList(tenderProject.getId(), supplier.getId(), expert.getEvalBidTypeNotNull());
		if (CollectionUtils.isNull(pointList)) {
			if (CollectionUtils.isNull(bidFileList)) {
				bidFileLabel.setText(Messages.Tips_noBidFiles);
				bidFileStackLayout.topControl = noBidFileComposite;
				bidFileComposite.layout();
			} else {
				BidFile curBidFile = CollectionUtils.get(bidFileList, t -> t.getFileId().equals("EQCompositeFileName"));
				if (null == curBidFile) {
					curBidFile = bidFileList.get(0);
				}
				selection(curBidFile);
			}
			pointLabel.setText("未绑定响应点！");
		} else {
			final EvaluationPoint evaluationPoint = pointList.get(0);
			selection(evaluationPoint);
			BidFile curBidFile = CollectionUtils.get(bidFileList, t -> t.getFileId().equals(evaluationPoint.getBidFile().getFileId()));
			if (null != curBidFile) {
				bidFileLabel.setText(curBidFile.getSimpleName());
			}
		}
		bidFileLabel.getParent().layout();
		pointLabel.getParent().layout();
		bidFileTitleComposite.layout();
	}
	
	/**
	 * @Description: 列表展示
	 * @author chenxw
	 */
	private void listAction(CLabel label, List<? extends Object> list, final LabelType labelType) {
		
		switch (labelType) {
		case BID_FILE:
			bidFileListLabel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/arrow_down_simp.png"));
			break;
		case EVALUATION_POINT:
			pointListLabel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/arrow_down_simp.png"));
			break;
		}
		
		Point point = label.getParent().toDisplay(new Point(0, 0));
		Rectangle parentRectangle = label.getParent().getBounds();
		SelectionShell<Object> cacheShell = new SelectionShell<Object>(getShell());
		cacheShell.addSelectionListener(this);
		cacheShell.addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent arg0) {
				switch (labelType) {
					case BID_FILE:
						bidFileListLabel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/next.png"));
						bidFileListLabel.getParent().layout();
						break;
					case EVALUATION_POINT:
						pointListLabel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/next.png"));
						pointListLabel.getParent().layout();
						break;
				}
			}
		});
		cacheShell.listCache(CollectionUtils.toHashMap(list, t -> {
			if (t instanceof EvaluationPoint) {
				return ((EvaluationPoint) t).getName();
			} else if (t instanceof BidFile) {
				BidFile file = (BidFile) t;
				return StringUtils.isNotEmpty(file.getSimpleName()) ? file.getSimpleName() : file.getName();
			}
			return null;
		}));
		cacheShell.setBackgroundImage(imageResolver.getImage(getShell().getBackgroundImage(), parentRectangle.width, 200));
		cacheShell.setLocation(point.x - 1, point.y + parentRectangle.height);
		cacheShell.setSize(Math.max(parentRectangle.width + 2, 200), Math.max(cacheShell.computeSize(parentRectangle.width, SWT.DEFAULT).y, 50));
		cacheShell.setAlpha(220);
		cacheShell.open();
	}
	
	/** 
	 * @Description: 选择文件列表和响应点列表回调
	 * @author chenxw
	 * @param object 
	 */
	public void selection(Object object) {
		if (object instanceof EvaluationPoint) {
			EvaluationPoint evaluationPoint = (EvaluationPoint) object;
			pointLabel.setText(evaluationPoint.getName());
			pointLabel.getParent().layout();
			openAndLocationBidFile(supplier.getId(), evaluationPoint.getBidFile(), evaluationPoint.getBookmark(), evaluationPoint.getPageNo());
		} else if (object instanceof BidFile) {
			BidFile bidFile = (BidFile) object;
			bidFileLabel.setText(bidFile.getSimpleName());
			bidFileLabel.getParent().layout();
			openAndLocationBidFile(supplier.getId(), bidFile, "", 0);
		}
		bidFileTitleComposite.layout();
	}
	
	/**
	 * @Description: 打开并定位投标文件
	 * @author chenxw
	 * @param ID
	 * @param bidFile
	 * @param bookmark
	 * @param pageNumber
	 */
	private void openAndLocationBidFile(String ID, File bidFile, final String bookmark, final int pageNumber) {
		String bidPath = bidFile.getAbsolutePath();
		bidFileLabel.setImage(imageResolver.getSysIcon(bidFile));
		Composite composite = bidFileLRU.get(bidPath);
		if (null == composite) {
			String pdfType = useSpecialPdf ? CaInfoUtil.getCaType(tenderProject.getId(), ID).getPdfType() : null;
			DocumentLoader documentLoader = DocumentFactory.getDocumentLoader(bidFile.getAbsolutePath(), pdfType);
			documentLoader.addLoadFileListener(new LoadFileListener() {
				public void fileLoaded(DocumentLoader loader) {
					loadFileSuccessAction(loader, bookmark, pageNumber);
				}
			});
			composite = new Composite(bidFileComposite, SWT.NONE);
			composite.setLayout(new FillLayout());
			composite.setData(documentLoader);
			documentLoader.openDocument(composite, true);
			bidFileLRU.put(bidPath, composite);
		} else {
			composite.redraw();
			loadFileSuccessAction((DocumentLoader) composite.getData(), bookmark, pageNumber);
		}
		bidFileStackLayout.topControl = composite;
		bidFileComposite.layout();
	}
	
	/**
	 * @Description: 加载文件成功事件
	 * @author chenxw
	 * @param loader
	 * @param bookmark
	 * @param pageNumber
	 */
	private void loadFileSuccessAction(DocumentLoader loader, String bookmark, int pageNumber) {
		if (null == loader) {
			return;
		}
		loader.showOrHiddenToolBar(showOleToolBar);
		if (null != bookmark && loader.bookmarkLocate(bookmark)) {
			return;
		}
		if (pageNumber > 0) {
			loader.gotoPage(pageNumber);
		}
		loader.activate();
	}
	
	class BidFileLRU extends LinkedHashMap<String, Composite> {
		private static final long serialVersionUID = -6239823442890164304L;
		
		protected boolean removeEldestEntry(java.util.Map.Entry<String, Composite> eldest) {
			if (size() > 5) {
				eldest.getValue().dispose();
				return true;
			}
			return false;
		}
	}
	
	public enum LabelType {
		BID_FILE, EVALUATION_POINT;
	}
	
	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
	
}
