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

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.widgets.ELink;
import org.eclipse.swt.core.widgets.ESepator;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
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.Label;
import org.eclipse.swt.widgets.Text;

import com.gx.obe.ColorConstants;
import com.gx.obe.business.entity.ExpertEvaluationStep;
import com.gx.obe.business.entity.SupplierEvaluationStep;
import com.gx.obe.business.enumeration.SupplierEnum;
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.dialog.ApplyReEvaluationDialog;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.LogUtils;
import com.gx.obe.util.utils.NumericChineseUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.SupplierEvaluationResult;
import com.gx.obe.web.entity.auth.AuthUser;
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.entity.tender.TenderProjectRuleEntity;
import com.gx.obe.web.service.ProjectRuleService;
import com.gx.obe.web.service.SupplierEvaluationResultService;
import com.gx.obe.web.service.SupplierEvaluationStepService;
import com.gx.obe.web.service.SupplierService;
import com.gx.obe.web.service.evaluation.EvaluationStepService;
import com.gx.obe.web.service.expert.ExpertEvaluationResultService;
import com.gx.obe.web.service.expert.ExpertEvaluationStepService;
import com.gx.obe.web.service.expert.ExpertService;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

import de.kupzog.ktable.KTable;
import de.kupzog.ktable.SWTX;
import de.kupzog.ktable.model.CommonKtableCModel;
import de.kupzog.ktable.renderers.CellAlignmentRender;
import de.kupzog.ktable.renderers.CellContentRender;
import de.kupzog.ktable.renderers.CellForegroundRender;
import de.kupzog.ktable.renderers.CellImageRender;
import de.kupzog.ktable.renderers.CellRender;
import de.kupzog.ktable.renderers.FixedWrapCellRenderer;
import de.kupzog.ktable.renderers.TextWrapCellRenderer;

/** 
 * @Description: 推荐排名中标候选人结果
 * @author chenxw 
 */
public class RecommendRankResultTableComposite extends Composite{
	
	private TenderProjectEntity tenderProjectEntity;
	private EvaluationStep evaluationStep;
	private Text evaluationOpinion_text;
	private Expert CURRENT_EXPERT;
	private ExpertService expertService;
	private ProjectRuleService projectRuleService;
//	private ExpertEvaluationStepService expertEvaluationStepService ;
	private SupplierEvaluationStepService supplierEvaluationStepService;
	private ExpertEvaluationResultService expertEvaluationResultService;
	private SupplierEvaluationResultService supplierEvaluationResultService ;
	private EvaluationStepService evaluationStepService = new EvaluationStepService();
	private SupplierService supplierService = new SupplierService();
	private Composite table_composite;
	private Composite composite_3;
	private Composite composite_4;
	private Label notLabel;
	private Composite composite;
	private ELink applyReEvaluation_link;
	private int recommendCount;
	private List<Supplier> supplierList;
	private EvaluationStep recommonedRank;
	private HashMap<String, Integer> supplierRankMap;
	private HashMap<String, Map<Integer, Integer>> supplierRankVoteMap;
	private List<AuthUser> userList;
	private String supplierName;
	private Map<String, ExpertEvaluationResult> expertEvaluationResultMap;
	
	private ExpertEvaluationStepService expertEvaluationStepService = new ExpertEvaluationStepService();
	
	{
		LogUtils.logClass(RecommendRankResultTableComposite.class);
	}
	
	/**
	 * @param parentShell
	 * @param tenderProjectEntity
	 * @param tenderProjectRuleEntity
	 * @param evaluationStep
	 * @param listener
	 */
	public RecommendRankResultTableComposite(Composite parentShell, int style) {
		super(parentShell,style);
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.verticalSpacing = 0;
		gridLayout.horizontalSpacing = 0;
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 0;
		setLayout(gridLayout);
		setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		
		
		composite_3 = new Composite(this, SWT.NONE);
		composite_3.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		composite_3.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
		GridLayout gl_composite_3 = new GridLayout(2, false);
		composite_3.setLayout(gl_composite_3);
		
		notLabel = new Label(composite_3, SWT.WRAP);
		notLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		notLabel.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		notLabel.setForeground(ColorConstants.NOTE_TIPS_COLOR);
		
		applyReEvaluation_link = new ELink(composite_3, SWT.NONE);
		applyReEvaluation_link.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/hand.png"));
		applyReEvaluation_link.setText(Messages.Button_appllyForBack);
		applyReEvaluation_link.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				applyReEvaluationAction();
			}
		});
		
		Composite container = new Composite(this, SWT.NONE);
		container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		GridLayout gl_container = new GridLayout(1, false);
		gl_container.marginHeight = 1;
		gl_container.marginWidth = 1;
		gl_container.verticalSpacing = 0;
		gl_container.horizontalSpacing = 0;
		container.setLayout(gl_container);
		container.setBackground(ColorConstants.BORDER_LINE_COLOR);
		
		table_composite = new Composite(container, SWT.NONE);
		GridLayout gl_table_composite = new GridLayout(1, false);
		gl_table_composite.verticalSpacing = 0;
		gl_table_composite.horizontalSpacing = 0;
		gl_table_composite.marginHeight = 0;
		gl_table_composite.marginWidth = 0;
		table_composite.setLayout(gl_table_composite);
		GridData gd_table_composite = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
		gd_table_composite.heightHint = 150;
		table_composite.setLayoutData(gd_table_composite);
		table_composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		
		composite = new Composite(container, SWT.NONE);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		composite.setLayout(new GridLayout(1, false));
		
		Label evaluationOpinion_label = new Label(composite, SWT.NONE);
		evaluationOpinion_label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		evaluationOpinion_label.setText(Messages.Title_evaluationOpinion);
		evaluationOpinion_label.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
		evaluationOpinion_label.setForeground(ColorConstants.NOTE_TIPS_COLOR);
		
		ESepator splabel = new ESepator(container, SWT.SEPARATOR | SWT.HORIZONTAL);
		splabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		splabel.setBackground(ColorConstants.SEP_LIGHT_COLOR);
		
		composite_4 = new Composite(container, SWT.NONE);
		GridData gd_composite_4 = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
		gd_composite_4.heightHint = 20;
		composite_4.setLayoutData(gd_composite_4);
		composite_4.setLayout(new GridLayout(1, false));
		composite_4.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		evaluationOpinion_text = new Text(composite_4, SWT.READ_ONLY | SWT.WRAP | SWT.V_SCROLL);
		evaluationOpinion_text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		evaluationOpinion_text.setFont(SWTResourceManager.getFont("宋体", 10, SWT.NORMAL));
		evaluationOpinion_text.setText("");
		expertService = new ExpertService();
		supplierEvaluationResultService = new SupplierEvaluationResultService();
		expertEvaluationResultService = new ExpertEvaluationResultService();
	}

	/**
	 * @Description: 刷新评标界面
	 * @author chenxw
	 * @param tenderProjectEntity
	 * @param tenderProjectRuleEntity
	 * @param evaluationStep 
	 */
	public void refresh(TenderProjectEntity tenderProjectEntity, TenderProjectRuleEntity tenderProjectRuleEntity, EvaluationStep evaluationStep, String OPERATOR_USER_ID){
		this.tenderProjectEntity = tenderProjectEntity;
		this.evaluationStep = evaluationStep;
		this.supplierList = getSupplierList();
		if(null == projectRuleService){
			projectRuleService = new ProjectRuleService();
		}
		supplierName = com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProjectEntity.getTenderType());
		
		CURRENT_EXPERT = expertService.getEvaluationStepExpert(tenderProjectEntity.getId(), evaluationStep);
		
		applyReEvaluation_link.setVisible(false);
		applyReEvaluation_link.setText(MessageFormat.format(Messages.Button_appllyForBackFormat, evaluationStep.getStepName()));
		tenderProjectRuleEntity = projectRuleService.getProjectRule(tenderProjectEntity.getId());
		if(null == tenderProjectRuleEntity)tenderProjectRuleEntity = new TenderProjectRuleEntity();
		List<EvaluationStep> recommonedRankList = evaluationStepService.getEvaluationStepListByType(tenderProjectEntity.getId(), com.gx.obe.components.core.enumeration.EvaluationStepEnum.RECOMMONED_RANK);
		if (null != recommonedRankList && recommonedRankList.size() > 0) {
			recommonedRank = recommonedRankList.get(0);
		}
		if(null == supplierEvaluationStepService ){
			supplierEvaluationStepService = new SupplierEvaluationStepService();
		}
		List<SupplierEvaluationStep> querySupplierEvaluationStepList = new ArrayList<SupplierEvaluationStep>();
		List<ExpertEvaluationResult> queryExpertEvaluationResultList = new ArrayList<ExpertEvaluationResult>();
		if (null != recommonedRank) {
			querySupplierEvaluationStepList = supplierEvaluationStepService.getSupplierEvaluationStepByTenderIdAndStepId(tenderProjectEntity.getId(), recommonedRank.getId());
			queryExpertEvaluationResultList = expertEvaluationResultService.getExpertStepAllSupplierEvaluationResultList(tenderProjectEntity.getId(), recommonedRank.getId(), null);
			recommendCount = recommonedRank.getEvaluationParamByKey(com.gx.obe.components.core.enumeration.EvaluationStepEnum.RECOMMEND_COUNT, Integer.class, 3);
			
			userList = expertService.getEvaluationStepUserList(tenderProjectEntity.getId(), recommonedRank);
		}
		
		supplierRankMap = new HashMap<String, Integer>();
		supplierRankVoteMap = new HashMap<String, Map<Integer,Integer>>();
		expertEvaluationResultMap = new HashMap<String, ExpertEvaluationResult>();
		for (Supplier supplier : supplierList) {
			for (SupplierEvaluationStep supplierEvaluationStep : querySupplierEvaluationStepList) {
				if (StringUtils.equals(supplier.getId(), supplierEvaluationStep.getSupplierId())) {
					supplierRankMap.put(supplier.getId(), supplierEvaluationStep.getSortNo());
					break;
				}
			}
			
			Map<Integer, Integer> supplierExpertVoteMap = new HashMap<Integer, Integer>();
			for (ExpertEvaluationResult expertEvaluationResult : queryExpertEvaluationResultList) {
				if (StringUtils.equals(supplier.getId(), expertEvaluationResult.getSupplierId())) {
					int sortNo = expertEvaluationResult.getSortNoIntValue();
					if (sortNo == 0) {
						continue;
					}
					int value = supplierExpertVoteMap.containsKey(sortNo) ? supplierExpertVoteMap.get(sortNo) : 0;
					supplierExpertVoteMap.put(expertEvaluationResult.getSortNoIntValue(), ++value);
				}
				for (AuthUser user : userList) {
					if (StringUtils.equals(supplier.getId(), expertEvaluationResult.getSupplierId()) && StringUtils.equals(user.getId(), expertEvaluationResult.getUserId())) {
						expertEvaluationResultMap.put(supplier.getId() + "-" + user.getId(), expertEvaluationResult);
					}
				}
			}
			supplierRankVoteMap.put(supplier.getId(), supplierExpertVoteMap);
			
			SupplierEvaluationResult supplierEvaluationResult = supplier.getSupplierEvaluationResult();
			if(null == supplierEvaluationResult){
				supplierEvaluationResult = new SupplierEvaluationResult();
				supplierEvaluationResult.setTenderId(tenderProjectEntity.getId());
				supplierEvaluationResult.setSupplierId(supplier.getId());
				supplier.setSupplierEvaluationResult(supplierEvaluationResult);
			}
		}
		Collections.sort(supplierList, new Comparator<Supplier>() {
			public int compare(Supplier behindSupplier, Supplier frontSupplier) {
				if (supplierRankMap.containsKey(frontSupplier.getId()) && supplierRankMap.containsKey(behindSupplier.getId())) {
					int frontSortNo = supplierRankMap.get(frontSupplier.getId());
					int behindSortNo = supplierRankMap.get(behindSupplier.getId());
					return behindSortNo - frontSortNo;
				}
				return 0;
			}
		});
		// 排序后设置默认推荐
		if(tenderProjectRuleEntity.getRecommendCountNotNull() < 1){
			tenderProjectRuleEntity.setRecommendCount(1);
		}
		
		boolean complate = null != evaluationStep.getStepStatus() && evaluationStep.getStepStatus().equals(CommonEnum.COMPLETE);
		if(complate && null != OPERATOR_USER_ID && OPERATOR_USER_ID.equals(Constants.USER.getId())){
			applyReEvaluation_link.setVisible(true);
		}
		drawEvaluationTable();
		if(null != tenderProjectEntity.getEvaluationOpinion()){
			evaluationOpinion_text.setText(tenderProjectEntity.getEvaluationOpinion());
		}
		StringBuilder msg = new StringBuilder();
		if(null != evaluationStep.getStepStatus() &&evaluationStep.getStepStatus().equals(CommonEnum.COMPLETE)){
			msg.append(MessageFormat.format(Messages.Tips_progressComplate, evaluationStep.getStepName()));
		}else if(null != evaluationStep.getStepStatus() &&evaluationStep.getStepStatus().equals(CommonEnum.IN_PROGRESS)){
			msg.append(MessageFormat.format(Messages.Tips_progressIn, evaluationStep.getStepName()));
		}else {
			msg.append(MessageFormat.format(Messages.Tips_progressNotStart, evaluationStep.getStepName()));
		}
		notLabel.setText(msg.toString());
	}
	
	/**
	 * @Description: 实现评审表格
	 * @author chenxw 
	 */
	private void drawEvaluationTable(){
		
		for (Control control : table_composite.getChildren()) {
			control.dispose();
		}
		
		final int expertColCount = userList.size() + 1;
		final int colCount = (expertColCount) * recommendCount + 1;
		
		KTable resultKTable = new KTable(table_composite, SWTX.AUTO_SCROLL | SWT.FULL_SELECTION | SWTX.EDIT_ON_KEY);
		resultKTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		final CommonKtableCModel commonKtableCModel = new CommonKtableCModel(resultKTable, 2, 1, supplierList.size(), colCount + 1);
		// 设置列宽
		commonKtableCModel.setColumnMaxWidth(0, 200);
		commonKtableCModel.setColumnMinWidth(0, 150);
		
		commonKtableCModel.addRowSpan(0, 0, 2);
		commonKtableCModel.addRowSpan(0, colCount, 2);
		commonKtableCModel.addRowSpan(0, colCount + 1, 2);
		
		for (int j = 0; j < supplierList.size(); j++) {
			commonKtableCModel.setRowHeight(j, Constants.ROW_HIGHT);
		}
		CellContentRender contentRender = new CellContentRender() {
			public Object receiveContent(int row, int col) {
				//当前列属于第几名
				int recommendCountIndex = ((col -1) / expertColCount) + 1;
				//专家列表索引
				int expertIndex = (col % expertColCount) - 1;
				if (row == 0) {
					if (col == 0) {
						return supplierName;
					} else if (expertIndex == 0 && recommendCountIndex <= recommendCount) {
						commonKtableCModel.addColSpan(0, col, expertColCount);
						return "第" + NumericChineseUtils.getChinese(recommendCountIndex) + "名";
					} else if (col == colCount) {
						return "最终排名";
					} else if (col == colCount + 1) {
						return "推荐";
					}
				} else if (row == 1) {
					if (col > 0 && recommendCountIndex <= recommendCount) {
						if (expertIndex == -1) {
							return "总票数";
						} else {
							AuthUser expert = userList.get(expertIndex);
							if (null != expert) {
								return expert.getUserName();
							}
						}
					}
				} else {
					Supplier supplier = supplierList.get(row - commonKtableCModel.getFixedHeaderRowCount());
					if (null != supplier) {
						if (col == 0) {
							return supplier.getSupplierName();
						} else if (recommendCountIndex <= recommendCount) {
							if (expertIndex == -1) {
								if (supplierRankVoteMap.containsKey(supplier.getId())) {
									Map<Integer, Integer> map = supplierRankVoteMap.get(supplier.getId());
									if (map.containsKey(recommendCountIndex)) {
										return map.get(recommendCountIndex);
									}
								}
							}
						} else if (col == colCount) {
							if (supplierRankMap.containsKey(supplier.getId())) {
								return supplierRankMap.get(supplier.getId());
							}
						} else if (col == colCount + 1) {
							SupplierEvaluationResult supplierEvaluationResult = supplier.getSupplierEvaluationResult();
							if(null != supplierEvaluationResult.getRecommend() && supplierEvaluationResult.getRecommend().equals(SupplierEnum.RECOMMONED_YES)){
								return "推荐";
							}else if(null != supplierEvaluationResult.getRecommend() && supplierEvaluationResult.getRecommend().equals(SupplierEnum.RECOMMONED_NO)){
								return "不推荐";
							}
						}
					}
				}
				return "";
			}
		};
		
		CellImageRender imageRender = new CellImageRender() {
			public Image receiveCellImage(int row, int col) {
				//当前列属于第几名
				int recommendCountIndex = ((col -1) / expertColCount) + 1;
				//专家列表索引
				int expertIndex = (col % expertColCount) - 1;
				if (row >= commonKtableCModel.getFixedHeaderRowCount()) {
					if (expertIndex != -1) {
						Supplier supplier = supplierList.get(row - commonKtableCModel.getFixedHeaderRowCount());
						AuthUser expert = userList.get(expertIndex);
						if (null != supplier && null != expert) {
							String key = supplier.getId() + "-" + expert.getId();
							if (expertEvaluationResultMap.containsKey(key)) {
								int sortNo = expertEvaluationResultMap.get(key).getSortNoIntValue();
								if (sortNo == recommendCountIndex) {
									return ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/flag_green.png");
								}
							}
						}
					}
				}
				return null;
			}
		};
		commonKtableCModel.setCellImageRender(imageRender);
		
		commonKtableCModel.setCellContentRender(contentRender);
		// 设置单元格渲染器
		CellRender cellRender = new CellRender() {
			public Object receiveCellRender(int row, int col) {
				if (commonKtableCModel.isFixedCell(col, row)) {
					return new FixedWrapCellRenderer();
				} else {
					return new TextWrapCellRenderer();
				}
			}
		};
		commonKtableCModel.setCellRender(cellRender);
		
		// 编辑单元格对齐方式
		CellAlignmentRender cellAlignmentRender = new CellAlignmentRender() {
			public int receiveCellAlignment(int row, int col) {
				if (row >= commonKtableCModel.getFixedHeaderColumnCount() && col == 0) {
					return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_LEFT;
				}
				return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
			}
		};
		commonKtableCModel.setCellAlignmentRender(cellAlignmentRender);
		
		// 设置单元格前景颜色
		CellForegroundRender cellForegroundRender = new CellForegroundRender() {
			public Color receiveCellForeground(int row, int col) {
				return null;
			}
		};
		commonKtableCModel.setCellForegroundRender(cellForegroundRender);
		resultKTable.setModel(commonKtableCModel);
	}
	
	/**
	 * @Description: 刷新投标人的价格分
	 * @author guoyr
	 * @return
	 */
	private List<Supplier> getSupplierList(){
		
		List<Supplier> supplierList = supplierService.getEvaluationStepSupplierList(tenderProjectEntity.getId(), evaluationStep);
		if(null != supplierList && supplierList.size() > 0){
			// 获取投标人评标结果
			List<SupplierEvaluationResult> supplierEvaluationResultList = supplierEvaluationResultService.getSupplierEvaluationResultListByTenderId(tenderProjectEntity.getId());
		
			for(Supplier supplier : supplierList){
				SupplierEvaluationResult supplierEvaluationResult = null;
				if(null != supplierEvaluationResultList && supplierEvaluationResultList.size() > 0){
					for(SupplierEvaluationResult evalResult : supplierEvaluationResultList){
						if(ObjectUtils.equals(evalResult.getSupplierId(), supplier.getId())){
							supplierEvaluationResult = evalResult;
							break;
						}
					}
				}
				
				if(null == supplierEvaluationResult){
					supplierEvaluationResult = new SupplierEvaluationResult();
					supplierEvaluationResult.setTenderId(tenderProjectEntity.getId());
					supplierEvaluationResult.setSupplierId(supplier.getId());
				}
				supplier.setSupplierEvaluationResult(supplierEvaluationResult);
			}
		}else {
		}
		if(null == supplierList)supplierList = new ArrayList<Supplier>();
		return supplierList;
	}
	
	/**
	 * @Description: 申请回退
	 * @author guoyr 
	 */
	private void applyReEvaluationAction(){
		if(applyReEvaluation_link.getEnabled()){
			ExpertEvaluationStep expertEvaluationStep = expertEvaluationStepService.getExpertEvaluationStep(tenderProjectEntity.getId(), evaluationStep.getId(), CURRENT_EXPERT.getUserId());
			if(null != expertEvaluationStep){
				ApplyReEvaluationDialog applyReEvaluationDialog = new ApplyReEvaluationDialog(getShell(), evaluationStep, expertEvaluationStep);
				applyReEvaluationDialog.open();
			}
		}
	}
}
