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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.core.widgets.ESepator;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.ScrolledComposite;
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.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;

import com.gx.obe.ColorConstants;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.components.core.Constants;
import com.gx.obe.components.core.I18NEnum;
import com.gx.obe.components.core.enumeration.CommonEnum;
import com.gx.obe.evaluation.step.inter.ISupplierRecommoned;
import com.gx.obe.message.Messages;
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.evaluation.EvaluationStep;
import com.gx.obe.web.entity.expert.Expert;
import com.gx.obe.web.entity.expert.ExpertEvaluationResult;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.service.expert.ExpertEvaluationResultService;
import com.gx.obe.web.service.expert.ExpertEvaluationStepService;
import com.gx.utils.ActionLogUtils;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

public class RecommendRankEvaluationTableComposite extends Composite {

	private Composite evaluationComposite;
	private Composite headComposite;
	private Composite bodyComposite;
	private Composite evaluationTableComposite;
	private TenderProjectEntity tenderProjectEntity;
	private EvaluationStep evaluationStep;
	private List<Supplier> selectSupplierList;
	private int recommendCount;
	private ScrolledComposite scrolledComposite;
	private List<ISupplierRecommoned> recommonSupplierList;
	private Expert CURRENT_EXPERT;
	private ExpertEvaluationResultService expertEvaluationResultService;
	private ExpertEvaluationStepService expertEvaluationStepService ;
	private Map<String, ExpertEvaluationResult> expertEvaluationResultMap;
	private Map<Integer, Supplier> supplierMap;
	private Composite composite_1;
	private RecommendRankEvaluationTableTdComposite titleComposite;
	private List<Supplier> supplierList;
	private Label noteMessageLabel;

	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public RecommendRankEvaluationTableComposite(Composite parent, int style) {
		super(parent, style);
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 0;
		setLayout(gridLayout);
		setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

		evaluationComposite = new Composite(this, SWT.NONE);
		evaluationComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		evaluationComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		GridLayout gl_evaluationComposite = new GridLayout(1, false);
		gl_evaluationComposite.verticalSpacing = 0;
		gl_evaluationComposite.horizontalSpacing = 0;
		gl_evaluationComposite.marginHeight = 0;
		gl_evaluationComposite.marginWidth = 0;
		evaluationComposite.setLayout(gl_evaluationComposite);
		
		headComposite = new Composite(evaluationComposite, SWT.NONE);
		headComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		GridData gd_composite_5 = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
		gd_composite_5.widthHint = 500;
		headComposite.setLayoutData(gd_composite_5);
		GridLayout gl_composite_5 = new GridLayout(2, false);
		headComposite.setLayout(gl_composite_5);
		headComposite.setBackgroundMode(SWT.INHERIT_FORCE);

		
		CLabel cleanTenderStepName = new CLabel(headComposite, SWT.NONE);
		cleanTenderStepName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, true, 1, 1));
		cleanTenderStepName.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		cleanTenderStepName.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/tips_blue.png"));
		cleanTenderStepName.setText("");
		
		noteMessageLabel = new Label(headComposite, SWT.NONE);
		noteMessageLabel.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		noteMessageLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, true, 1, 1));
		noteMessageLabel.setText("请您根据排名选择要推荐的供应商！");

		ESepator sep = new ESepator(evaluationComposite, SWT.NONE);
		sep.setBackground(ColorConstants.SEP_LIGHT_COLOR);
		sep.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		bodyComposite = new Composite(evaluationComposite, SWT.NONE);
		bodyComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		GridLayout gl_bodyComposite = new GridLayout(1, false);
		gl_bodyComposite.marginHeight = 100;
		gl_bodyComposite.marginWidth = 200;
		bodyComposite.setLayout(gl_bodyComposite);
		bodyComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		
		scrolledComposite = new ScrolledComposite(bodyComposite, SWT.H_SCROLL | SWT.V_SCROLL);
		scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		scrolledComposite.setExpandHorizontal(true);
		scrolledComposite.setExpandVertical(true);
		
		composite_1 = new Composite(scrolledComposite, SWT.NONE);
		composite_1.setBackground(ColorConstants.BORDER_LINE_COLOR);
		GridLayout gl_composite_1 = new GridLayout(1, false);
		gl_composite_1.verticalSpacing = 1;
		gl_composite_1.marginHeight = 1;
		gl_composite_1.marginWidth = 1;
		composite_1.setLayout(gl_composite_1);
		composite_1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		titleComposite = new RecommendRankEvaluationTableTdComposite(composite_1, SWT.NONE);
		titleComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));

		
		evaluationTableComposite = new Composite(composite_1, SWT.NONE);
		evaluationTableComposite.setBackgroundMode(SWT.INHERIT_FORCE);
		evaluationTableComposite.setBackground(ColorConstants.BORDER_LINE_COLOR);
		GridLayout gl_evaluationTableComposite = new GridLayout(1, false);
		gl_evaluationTableComposite.marginWidth = 0;
		gl_evaluationTableComposite.verticalSpacing = 1;
		gl_evaluationTableComposite.horizontalSpacing = 1;
		gl_evaluationTableComposite.marginHeight = 0;
		evaluationTableComposite.setLayout(gl_evaluationTableComposite);
		GridData gd_evaluationTableComposite = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
		gd_evaluationTableComposite.minimumHeight = 200;
		evaluationTableComposite.setLayoutData(gd_evaluationTableComposite);
		
		scrolledComposite.setContent(composite_1);
		scrolledComposite.setMinSize(composite_1.computeSize(SWT.DEFAULT, SWT.DEFAULT));
		
		init();
	}

	/**
	 * @Description: 初始化
	 * @author chenxw 
	 */
	private void init() {
		expertEvaluationResultService = new ExpertEvaluationResultService();
		expertEvaluationStepService = new ExpertEvaluationStepService();
		recommonSupplierList = new ArrayList<ISupplierRecommoned>();
		supplierMap = new HashMap<Integer, Supplier>();
		expertEvaluationResultMap = new HashMap<String, ExpertEvaluationResult>();
		selectSupplierList = new ArrayList<Supplier>();
		scrolledComposite.getVerticalBar().setIncrement(30);
		scrolledComposite.forceFocus();
		addListener(SWT.Activate, new Listener() {
	        public void handleEvent(Event e) {
	            scrolledComposite.setFocus();
	        }
	    });
	}

	/**
	 * @Description: 刷新
	 * @author chenxw
	 * @param tenderProjectEntity
	 * @param curUser
	 * @param evaluationStep
	 * @param supplierList 
	 */
	public void refresh(TenderProjectEntity tenderProjectEntity, Expert currentExpert, EvaluationStep evaluationStep, List<Supplier> supplierList) {
		this.tenderProjectEntity = tenderProjectEntity;
		this.CURRENT_EXPERT = currentExpert;
		this.evaluationStep = evaluationStep;
		this.supplierList = supplierList;
		noteMessageLabel.setText("请您为每个排名选择要推荐的"+com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProjectEntity.getTenderType())+"！");
		supplierMap.clear();
		expertEvaluationResultMap.clear();
		selectSupplierList.clear();
		titleComposite.addTitle(Messages.SortNo, com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProjectEntity.getTenderType()));
		selectSupplierList.addAll(supplierList);
		// 修改评标专家的评审记录
		ActionLogUtils.addServerLog(tenderProjectEntity.getId(), "进入" + evaluationStep.getStepName(), Constants.USER.getUserName());
		expertEvaluationStepService.updateExpertEvaluationStatus(CommonEnum.IN_PROGRESS, tenderProjectEntity.getId(), evaluationStep, CURRENT_EXPERT.getUserId());
		List<ExpertEvaluationResult> queryExpertEvaluationResultList = expertEvaluationResultService.getExpertStepAllSupplierEvaluationResultList(tenderProjectEntity.getId(), evaluationStep.getId(), CURRENT_EXPERT.getUserId());
		for(Supplier supplier : supplierList){
			// 获取评标专家对投标人的评审记录
			ExpertEvaluationResult expertEvaluationResult = null;
			if(null != queryExpertEvaluationResultList && queryExpertEvaluationResultList.size() > 0){
				for(ExpertEvaluationResult queryExpertEvaluationResult : queryExpertEvaluationResultList){
					if(ObjectUtils.equals(queryExpertEvaluationResult.getSupplierId(), supplier.getId())){
						expertEvaluationResult = queryExpertEvaluationResult;
						break;
					}
				}
			}
			if(null != expertEvaluationResult){
				int sortNo = expertEvaluationResult.getSortNoIntValue();
				if (sortNo != 0) {
					supplierMap.put(sortNo, supplier);
				}
				expertEvaluationResultMap.put(supplier.getId(), expertEvaluationResult);
			}
		}
		recommendCount = evaluationStep.getEvaluationParamByKey(com.gx.obe.components.core.enumeration.EvaluationStepEnum.RECOMMEND_COUNT, Integer.class, 3);
		drawEvaluationTable();
	}
	
	/**
	 * @Description: 生成推荐排名表格
	 * @author chenxw 
	 */
	private void drawEvaluationTable() {
		recommonSupplierList.clear();
		for (Control control : evaluationTableComposite.getChildren()) {
			control.dispose();
		}
		for (int i = 1; i <= recommendCount; i++) {
			RecommendRankEvaluationTableTdComposite composite = new RecommendRankEvaluationTableTdComposite(evaluationTableComposite, SWT.NONE);
			composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
			
			ExpertEvaluationResult expertEvaluationResult = null;
			Supplier supplier = supplierMap.get(i);
			if(null != supplier){
				expertEvaluationResult = expertEvaluationResultMap.get(supplier.getId());
			}
			composite.addParameter(tenderProjectEntity, selectSupplierList, i, supplier, null != expertEvaluationResult ? expertEvaluationResult.getSupplierOpinion() : null);
			recommonSupplierList.add(composite);
		}
		evaluationTableComposite.layout();
		scrolledComposite.setMinSize(composite_1.computeSize(SWT.DEFAULT, SWT.DEFAULT));
	}

	/**
	 * @Description: 保存推荐排名结果
	 * @author chenxw
	 * @return 
	 */
	public boolean saveRecommendRankEvaluationResult() {
		List<ExpertEvaluationResult> expertEvaluationResultList = new ArrayList<ExpertEvaluationResult>();
		for (ISupplierRecommoned composite : recommonSupplierList) {
			Supplier supplier = composite.getSupplier();
			if(null == supplier){
				continue;
			}
			int sortNo = composite.getSupplierSortNo();
			String supplierOpinion = composite.getSupplierOpinion();
			Supplier oldSupplier = supplierMap.get(sortNo);
			if (null != oldSupplier) {
				ExpertEvaluationResult oldEvaluationResult = expertEvaluationResultMap.get(oldSupplier.getId());
				if(null != oldEvaluationResult){
					oldEvaluationResult.setSortNo(0);
				}
			}
			ExpertEvaluationResult expertEvaluationResult = null;
			if (null != supplier) {
				expertEvaluationResult = expertEvaluationResultMap.get(supplier.getId());
				if(null == expertEvaluationResult){
					expertEvaluationResult = new ExpertEvaluationResult();
					expertEvaluationResult.setId(UuidUtils.getUUID());
				}
				expertEvaluationResult.setTenderId(tenderProjectEntity.getId());
				expertEvaluationResult.setStepId(evaluationStep.getId());
				expertEvaluationResult.setUserId(CURRENT_EXPERT.getUserId());
				expertEvaluationResult.setSupplierId(supplier.getId());
				expertEvaluationResult.setSupplierOpinion(supplierOpinion);
				expertEvaluationResult.setSortNo(sortNo);
				expertEvaluationResultList.add(expertEvaluationResult);
			}
		}
		return expertEvaluationStepService.saveRecommendRankEvaluationResult(tenderProjectEntity.getId(), CURRENT_EXPERT.getUserId(), evaluationStep, expertEvaluationResultList);
	}
	
	/**
	 * @Description: 提交推荐排名结果
	 * @author chenxw
	 * @return 
	 */
	public boolean submitRecommendRankEvaluationResult() {
		if (saveRecommendRankEvaluationResult()) {
			StringBuffer msg = new StringBuffer();
			for (ISupplierRecommoned composite : recommonSupplierList) {
				Supplier nowSupplier = composite.getSupplier();
				int sortNo = composite.getSupplierSortNo();
				if(null == nowSupplier){
					msg.append("第").append(sortNo).append("名未选择要推荐的").append(com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProjectEntity.getTenderType())).append("，请选择！");
					MessageDialog.openInformation(getShell(), msg.toString());
					return false;
				}
			}
			if (expertEvaluationStepService.submitRecommendRankEvaluationResult(tenderProjectEntity.getId(), CURRENT_EXPERT.getUserId(), evaluationStep, supplierList, recommendCount)) {
				return true;
			}
		}
		MessageDialog.openInformation(getShell(), Messages.Dialog_warmTips, Messages.Tips_saveEvalResultFailed);
		return false;
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
	
}
