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

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.listener.RoundBorderLineListener;
import org.eclipse.swt.core.widgets.ELink;
import org.eclipse.swt.core.widgets.EMenu;
import org.eclipse.swt.custom.SashForm;
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.Label;

import com.gx.obe.ColorConstants;
import com.gx.obe.business.enumeration.ProjectRuleEnum;
import com.gx.obe.business.enumeration.SupplierEnum;
import com.gx.obe.business.vo.ExchangeRate;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.common.widget.dialog.EditSubBidPriceItemDialog;
import com.gx.obe.components.core.Constants;
import com.gx.obe.components.core.I18NEnum;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.BigDecimalUtils;
import com.gx.obe.util.utils.CollectionUtils;
import com.gx.obe.util.utils.NumberFormatUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.SupplierOpeningResult;
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.SupplierOpeningResultService;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

import de.kupzog.ktable.KTable;
import de.kupzog.ktable.KTableCellSelectionAdapter;
import de.kupzog.ktable.SWTX;
import de.kupzog.ktable.editors.KTableCellEditorButton;
import de.kupzog.ktable.model.CommonKtableCModel;
import de.kupzog.ktable.renderers.ButtonCellRenderer;
import de.kupzog.ktable.renderers.CellAlignmentRender;
import de.kupzog.ktable.renderers.CellContentRender;
import de.kupzog.ktable.renderers.CellEditorRender;
import de.kupzog.ktable.renderers.CellEventActionRender;
import de.kupzog.ktable.renderers.CellRender;
import de.kupzog.ktable.renderers.FixedWrapCellRenderer;
import de.kupzog.ktable.renderers.TextCellRenderer;
import de.kupzog.ktable.renderers.TextWrapCellRenderer;

public class PriceEditAndResultComposite extends Composite {
	
	private TenderProjectEntity tenderProject;
	private TenderProjectRuleEntity projectRule;
	private ProjectRuleService projectRuleService;
	private SupplierOpeningResultService supplierOpeningResultService;
	private List<Supplier> supplierList;
	private KTable resultKTable;
	private Composite evaluationTableComposite;
	private boolean isModify;
	private ExchangeRate exchangeRate;
	private Label message_label;
	private SortType sortType = SortType.DEFAULT;
	
	private SashForm sashForm;
	private BidPriceTableDetailComposite bidPriceTableDetailComposite;
	private ELink sortLink;
	
	enum SortType {
		DEFAULT, EVAL_PRICE_HIGH_LOW, EVAL_PRICE_LOW_HIGH;
	}
	
	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public PriceEditAndResultComposite(Composite parent, int style) {
		super(parent, style);
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 0;
		setLayout(gridLayout);
		setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		
		Composite composite = new Composite(this, SWT.NONE);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		composite.setLayout(new GridLayout(3, false));
		
		message_label = new Label(composite, SWT.WRAP);
		message_label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		message_label.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		message_label.setForeground(ColorConstants.NOTE_TIPS_COLOR);
		
		sortLink = new ELink(composite, SWT.NONE);
		sortLink.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				sortOperation();
			}
		});
		sortLink.setText(Messages.Button_sortByDefault);
		
		ELink changeLink = new ELink(composite, SWT.NONE);
		changeLink.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/switch.png"));
		changeLink.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				sortOperation();
			}
		});
		changeLink.setText(Messages.Button_change);
//		
//		ELink link_1 = new ELink(composite, SWT.NONE);
//		link_1.addMouseListener(new MouseAdapter() {
//			public void mouseUp(MouseEvent e) {
//				sortType = SortType.EVAL_PRICE_HIGH_LOW;
//				refreshEvaluationPrice();
//			}
//		});
//		link_1.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/down.png"));
//		link_1.setText(MessageFormat.format(Messages.PriorityHighToLowFormat, Messages.EvaluationPrice));
//		
//		ELink link_2 = new ELink(composite, SWT.NONE);
//		link_2.addMouseListener(new MouseAdapter() {
//			public void mouseUp(MouseEvent e) {
//				sortType = SortType.EVAL_PRICE_LOW_HIGH;
//				refreshEvaluationPrice();
//			}
//		});
//		link_2.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/up.png"));
//		link_2.setText(MessageFormat.format(Messages.PriorityLowToHightFormat, Messages.EvaluationPrice));
		
		sashForm = new SashForm(this, SWT.VERTICAL);
		sashForm.setBackground(ColorConstants.SKIN_BG);
		sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		evaluationTableComposite = new Composite(sashForm, SWT.NONE);
		evaluationTableComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		evaluationTableComposite.addPaintListener(new RoundBorderLineListener(ColorConstants.BORDER_LINE_COLOR));
		GridLayout gl_evaluationTableComposite = new GridLayout(1, false);
		gl_evaluationTableComposite.marginHeight = 1;
		gl_evaluationTableComposite.marginWidth = 1;
		evaluationTableComposite.setLayout(gl_evaluationTableComposite);
		
		init();
	}
	
	private void init() {
		supplierOpeningResultService = new SupplierOpeningResultService();
		projectRuleService = new ProjectRuleService();
	}
	
	public void refresh(TenderProjectEntity tenderProjectEntity, List<Supplier> supplierList, boolean isModify) {
		this.tenderProject = tenderProjectEntity;
		this.supplierList = supplierList;
		this.isModify = isModify;
		projectRule = projectRuleService.getProjectRule(tenderProjectEntity.getId());
		refreshMessageLabel();
		refreshExchangeRate();
		refreshSupplierList();
		sortAction(SortType.DEFAULT);
	}
	
	
	public void sortOperation() {
		EMenu supplierOp = new EMenu(getShell());
		supplierOp.addMenuItem(Messages.Button_sortByDefault, ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/items.png"), true, new EMenu.ClickListener() {
			public void click() {
				sortAction(SortType.DEFAULT);
			}
		});
		supplierOp.addMenuItem(MessageFormat.format(Messages.PriorityHighToLowFormat, Messages.EvaluationPrice), ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/down.png"), true, new EMenu.ClickListener() {
			public void click() {
				sortAction(SortType.EVAL_PRICE_HIGH_LOW);
			}
		});
		supplierOp.addMenuItem(MessageFormat.format(Messages.PriorityLowToHightFormat, Messages.EvaluationPrice), ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/up.png"), true, new EMenu.ClickListener() {
			public void click() {
				sortAction(SortType.EVAL_PRICE_LOW_HIGH);
			}
		});

		supplierOp.setBackground(SWTResourceManager.getColor(60, 138, 226));
		supplierOp.setAlpha(200);
		supplierOp.open(sortLink);
		
	}

	private void sortAction(SortType sortType) {
		this.sortType = sortType;
		if(sortType.equals(SortType.DEFAULT)) {
			sortLink.setText(Messages.Button_sortByDefault);
			sortLink.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/items.png"));
		}else if(sortType.equals(SortType.EVAL_PRICE_HIGH_LOW)) {
			sortLink.setText(MessageFormat.format(Messages.PriorityHighToLowFormat, Messages.EvaluationPrice));
			sortLink.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/down.png"));
		}if(sortType.equals(SortType.EVAL_PRICE_LOW_HIGH)) {
			sortLink.setText(MessageFormat.format(Messages.PriorityLowToHightFormat, Messages.EvaluationPrice));
			sortLink.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/up.png"));
		}
		sortLink.getParent().layout();
		refreshEvaluationPrice();
	}
	/**
	 * @Description: 刷新消息标签
	 * @author chenxw
	 */
	private void refreshMessageLabel() {
//		WidgetUtils.setControlVisible(message_label, isModify);
		if (isModify) {
			message_label.setText(MessageFormat.format(Messages.Tips_quotation_comparison, Messages.Button_correctPrice));
		} else {
			message_label.setText("");
		}
	}
	
	private void refreshSupplierList() {
		List<SupplierOpeningResult> supplierOpeningResultList = supplierOpeningResultService.getSupplierOpeningResultListByTenderIdAndBidOpeningStatus(tenderProject.getId(), SupplierEnum.OPENBID_SUCCESS);
		for (final Supplier supplier : supplierList) {
			SupplierOpeningResult supplierOpeningResult = null;
			if (null != supplierOpeningResultList && supplierOpeningResultList.size() > 0) {
				supplierOpeningResult = CollectionUtils.get(supplierOpeningResultList, t -> {
					if (supplier.getId().equals(t.getSupplierId())) {
						if (null == t.getEvaluationPrice()) {
							t.setEvaluationPrice(t.getBidPrice());
						}
						return true;
					}
					return false;
				});
			}
			if (null == supplierOpeningResult) {
				supplierOpeningResult = new SupplierOpeningResult();
				supplierOpeningResult.setTenderId(tenderProject.getId());
				supplierOpeningResult.setSupplierId(supplier.getId());
			}
			supplier.setSupplierOpeningResult(supplierOpeningResult);
		}
	}

	/**
	 * @Description:刷新汇率
	 * @author chenxw
	 */
	private void refreshExchangeRate() {
		exchangeRate = projectRule.getParamByKey(ProjectRuleEnum.EXCHANGE_RATE);
		if (null == exchangeRate) {
			exchangeRate = new ExchangeRate();
		}
	}
	
	/**
	 * @Description:刷新评标价
	 * @author chenxw
	 */
	private void refreshEvaluationPrice() {
		if (resultKTable != null) {
			resultKTable.dispose();
		}
		
		resultKTable = new KTable(evaluationTableComposite, SWTX.AUTO_SCROLL | SWT.FULL_SELECTION | SWTX.EDIT_ON_KEY | SWTX.FILL_WITH_LASTCOL);
		resultKTable.addCellSelectionListener(new KTableCellSelectionAdapter() {
			public void cellSelected(int col, int row, int statemask) {
				if (row != 0) {
					refreshBidPriceTableDetailComposite(supplierList.get(row - 2));
				}
			}
		});
		resultKTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		resultKTable.setAutoComputerSurplusWidth(true);
		
		int colIndex = 1;
		final int bidPriceCurrencyCol = (++colIndex);// 投标报价币种
		final int sourceBidPriceCol = (++colIndex);// 原始报价
		final int finalBidPriceCol = (++colIndex);// 最终报价
		final int modifyReasionCol = (++colIndex);// 修正原因
		final int evaluationPriceCurrency = (++colIndex);// 评标价币种
		final int exchangeRateCol = (++colIndex);// 汇率
		final int evaluationPrice = (++colIndex);// 评标价
		final int operator = (++colIndex);//修正操作按钮
		
		int colCount = 3;// 序号、供应商列、操作列
		int bidPriceColCount = 0;
		bidPriceColCount += (bidPriceCurrencyCol > 0 ? 1 : 0);
		bidPriceColCount += (sourceBidPriceCol > 0 ? 1 : 0);
		bidPriceColCount += (finalBidPriceCol > 0 ? 1 : 0);
		bidPriceColCount += (modifyReasionCol > 0 ? 1 : 0);
		
		int evaluationPriceColCount = 0;
		evaluationPriceColCount += (evaluationPriceCurrency > 0 ? 1 : 0);
		evaluationPriceColCount += (exchangeRateCol > 0 ? 1 : 0);
		evaluationPriceColCount += (evaluationPrice > 0 ? 1 : 0);
		
		List<Supplier> sortSupplierList = getSortSupplierList();
		
		// 开标一览表报价多余两列,显示双表头,并且显示汇总报价和评标价
		final CommonKtableCModel commKTableModel = new CommonKtableCModel(resultKTable, 2, 0, sortSupplierList.size(), colCount + bidPriceColCount + evaluationPriceColCount);
		commKTableModel.setContentRowHeight(Constants.ROW_HIGHT);
		commKTableModel.addRowSpan(0, 0, commKTableModel.getFixedRowCount());
		commKTableModel.addRowSpan(0, 1, commKTableModel.getFixedRowCount());
		commKTableModel.addRowSpan(0, operator, commKTableModel.getFixedRowCount());
		
		commKTableModel.setColumnWidth(0, 50);
		commKTableModel.setColumnMaxWidth(0, 60);
		commKTableModel.setColumnWidth(1, 200);
		for (int col = 2; col < commKTableModel.getColCount(); col++) {
			commKTableModel.setColumnWidth(col, 100);
		}
		if (bidPriceCurrencyCol > 0) {
			commKTableModel.setColumnWidth(bidPriceCurrencyCol, 80);
		}
		if (evaluationPriceCurrency > 0) {
			commKTableModel.setColumnWidth(evaluationPriceCurrency, 80);
		}
		commKTableModel.setColumnWidth(operator, 100);
		commKTableModel.setColumnWidth(exchangeRateCol, 80);
		
		final int bidPriceStartCol = 2;
		final int evaluationPriceStartCol = bidPriceStartCol + bidPriceColCount;
		commKTableModel.addColSpan(0, bidPriceStartCol, bidPriceColCount);
		commKTableModel.addColSpan(0, evaluationPriceStartCol, evaluationPriceColCount);
		
		// 设置单元格内容
		final String SUPPLIER_NAME = com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProject.getTenderType());
		CellContentRender contentRender = new CellContentRender() {
			public Object receiveContent(int row, int col) {
				if (row < commKTableModel.getFixedRowCount()) {
					if (col == 0) {
						return Messages.Num;
					} else if (col == 1) {
						return SUPPLIER_NAME;
					} else if (col == operator) {
						return Messages.Button_operate;
					} else {
						if (col == bidPriceStartCol) {
							if (row == 0) {
								return Messages.BidPrice;
							}
						}
						if (col == bidPriceCurrencyCol) {
							return Messages.Currency;
						}
						if (col == sourceBidPriceCol) {
							return Messages.OriginalBidPrice;
						}
						if (col == finalBidPriceCol) {
							return Messages.BidPrice;
						}
						if (col == modifyReasionCol) {
							return Messages.CorrectReason;
						}
						if (col == evaluationPriceStartCol) {
							if (row == 0) {
								return Messages.EvaluationPrice;
							}
						}
						if (col == evaluationPriceCurrency) {
							return Messages.Currency;
						}
						if (col == exchangeRateCol) {
							return Messages.ExchangeRate;
						}
						if (col == evaluationPrice) {
							return Messages.EvaluationPrice;
						}
						if (col == operator) {
							return Messages.Button_correctPrice;
						}
					}
					return "";
				} else {
					if (col == 0) {
						return (row - commKTableModel.getFixedRowCount() + 1);
					} else {
						Supplier supplier = sortSupplierList.get(row - commKTableModel.getFixedRowCount());
						SupplierOpeningResult supplierOpeningResult = supplier.getSupplierOpeningResult();
						if (col == 1) {
							return supplier.getSupplierName();
						}
						if (col == operator) {
							return Messages.Button_correctPrice;
						} else {
							if (col == bidPriceCurrencyCol) {
								return supplierOpeningResult.getCurrencyNameUseDefault(projectRule.getCurrencyName());
							}
							if (col == sourceBidPriceCol) {
								return supplierOpeningResult.getBidPriceWithUnit(projectRule.getPriceUnitUseDefault());
							}
							if (col == finalBidPriceCol) {
								return supplierOpeningResult.getFinalBidPriceWithUnit(projectRule.getPriceUnitUseDefault());
							}
							if (col == modifyReasionCol) {
								return ObjectUtils.getObjString(supplierOpeningResult.getModifyReason());
							}
							if (col == evaluationPriceCurrency) {
								return ObjectUtils.getObjString(projectRule.getEvalCurrencyName());
							}
							if (col == exchangeRateCol) {
								return NumberFormatUtils.format(exchangeRate.get(supplierOpeningResult.getCurrencyCode()));
							}
							if (col == evaluationPrice) {
								return supplierOpeningResult.getEvaluationPriceWithUnit(projectRule.getEvalPriceUnit());
							}
							
						}
					}
				}
				return "";
			}
		};
		commKTableModel.setCellContentRender(contentRender);
		
		// 设置单元格渲染器
		final ButtonCellRenderer buttonCellRenderer = new ButtonCellRenderer();
		final TextWrapCellRenderer textWrapCellRenderer = new TextWrapCellRenderer();
		final TextCellRenderer textCellRenderer = new TextCellRenderer();
		CellRender cellRender = new CellRender() {
			public Object receiveCellRender(int row, int col) {
				if (commKTableModel.isFixedCell(col, row)) {
					return new FixedWrapCellRenderer();
				} else {
					if (col == operator) {
						if (!isModify) {
							buttonCellRenderer.setEnable(false);
						}
						return buttonCellRenderer;
					}
					if (col == modifyReasionCol) {
						return textWrapCellRenderer;
					}
					return textCellRenderer;
				}
			}
		};
		commKTableModel.setCellRender(cellRender);
		
		// 设置单元格编辑器
		CellEditorRender cellEditorRender = new CellEditorRender() {
			public Object receiveCellEditor(int row, int col) {
				if (row > -commKTableModel.getFixedRowCount()) {
					if (col == operator) {
						if (resultKTable.getCurCell().y != row || resultKTable.getCurCell().x != col) {
							resultKTable.getCurCell().y = row;
							resultKTable.getCurCell().x = col;
						}
						return new KTableCellEditorButton(resultKTable, new CellEventActionRender() {
							public void receiveAction(int row, int col) {
								if (isModify) {
									Supplier supplier = sortSupplierList.get(row - commKTableModel.getFixedRowCount());
									operatorAction(supplier);
								}
							}
						});
					}
				}
				
				return null;
			}
		};
		commKTableModel.setCellEditorRender(cellEditorRender);
		
		// 编辑单元格对齐方式
		CellAlignmentRender cellAlignmentRender = new CellAlignmentRender() {
			public int receiveCellAlignment(int row, int col) {
				if (row < commKTableModel.getFixedRowCount()) {
					return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
				} else {
					if (col == 0 || col == bidPriceCurrencyCol || col == evaluationPriceCurrency || col == exchangeRateCol) {
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
					} else if (col == 1 || col == operator || col == modifyReasionCol) {
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_LEFT;
					} else {
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_RIGHT;
					}
				}
			}
		};
		commKTableModel.setCellAlignmentRender(cellAlignmentRender);
		
		resultKTable.setModel(commKTableModel);
		resultKTable.getParent().layout();
	}
	
	/**
	 * @Description: 刷新投标报价表明细界面
	 * @author chenxw
	 * @param supplier 
	 */
	private void refreshBidPriceTableDetailComposite(Supplier supplier) {
		if (bidPriceTableDetailComposite != null) {
			bidPriceTableDetailComposite.dispose();
		}
		sashForm.layout();
		
		bidPriceTableDetailComposite = new BidPriceTableDetailComposite(sashForm, SWT.NONE);
		GridLayout gl_bidPriceTableDetailComposite = new GridLayout(1, false);
		gl_bidPriceTableDetailComposite.marginHeight = 0;
		gl_bidPriceTableDetailComposite.marginWidth = 0;
		bidPriceTableDetailComposite.setLayout(gl_bidPriceTableDetailComposite);
		
		sashForm.setWeights(new int[] {1, 1});
		sashForm.layout();
		
		bidPriceTableDetailComposite.refresh(tenderProject, supplier);
	}

	/**
	 * @Description: 获取排序后的供应商列表
	 * @author chenxw
	 * @return 
	 */
	private List<Supplier> getSortSupplierList() {
		List<Supplier> sortSupplierList = new ArrayList<>(supplierList);
		if (sortType != SortType.DEFAULT) {
			Collections.sort(sortSupplierList, (s1, s2) -> {
				BigDecimal ep1 = s1.getSupplierOpeningResult().getEvaluationPrice();
				BigDecimal ep2 = s2.getSupplierOpeningResult().getEvaluationPrice();
				switch (sortType) {
					case EVAL_PRICE_HIGH_LOW:
						return BigDecimalUtils.compareTo(ep2, ep1);
					case EVAL_PRICE_LOW_HIGH:
						return BigDecimalUtils.compareTo(ep1, ep2);
					default:
						return 0;
				}
			});
		}
		return sortSupplierList;
	}

	/**
	 * @Description: 修正报价
	 * @author guoyr
	 * @param supplier
	 */
	private void operatorAction(Supplier supplier) {
		EditSubBidPriceItemDialog dialog = new EditSubBidPriceItemDialog(getShell(), supplier, projectRule);
		dialog.open();
		SupplierOpeningResult supplierOpeningResult = supplierOpeningResultService.getSupplierOpeningResult(supplier.getTenderId(), supplier.getId());
		if (supplierOpeningResult != null) {
			supplier.setSupplierOpeningResult(supplierOpeningResult);
		}
		resultKTable.redraw();
	}
	
	@Override
	protected void checkSubclass() {}
}
