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

import java.math.BigDecimal;
import java.text.MessageFormat;
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.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;

import com.gx.obe.business.entity.EditPriceItem;
import com.gx.obe.business.entity.EditPriceItemResult;
import com.gx.obe.components.core.Constants;
import com.gx.obe.components.core.I18NEnum;
import com.gx.obe.components.core.enumeration.BidPriceEnum;
import com.gx.obe.components.core.util.MoneyUtils;
import com.gx.obe.evaluation.step.composite.EvaluationResultComposite;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.CollectionUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.evaluation.EvaluationStep;
import com.gx.obe.web.entity.price.BidPrice;
import com.gx.obe.web.entity.price.BidPriceResult;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.entity.tender.TenderProjectRuleEntity;
import com.gx.obe.web.service.BidPriceResultService;
import com.gx.obe.web.service.BidPriceService;
import com.gx.obe.web.service.EditPriceItemResultService;
import com.gx.obe.web.service.EditPriceItemService;
import com.gx.obe.web.service.SupplierService;
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;

/** 
 * @Description: 修正报价结果界面
 * @author chenxw 
 */
public class EditPriceResultComposite extends EvaluationResultComposite {
	
	private SupplierService supplierService = new SupplierService();
	private EditPriceItemService editPriceItemService ;
	private EditPriceItemResultService editPriceItemResultService ;
	private BidPriceResultService bidPriceResultService ;
	
	private Composite composite;
	private KTable resultTable;
	
	private int headRow = 2;
	private int headCol = 1;
	private int evaluationPriceCol;
	
	private Map<Point, String> contentMap = new HashMap<Point, String>();

	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public EditPriceResultComposite(Composite parent, int style) {
		super(parent, style);
		
		composite = new Composite(tableComposite, SWT.NONE);
		composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		GridLayout gl_composite = new GridLayout(1, false);
		gl_composite.marginHeight = 0;
		gl_composite.marginWidth = 0;
		composite.setLayout(gl_composite);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
	}
	
	/**
	 * @Description: 刷新
	 * @author chenxw
	 * @param tenderProjectEntity
	 * @param evaluationStep
	 * @param tenderProjectRuleEntity 
	 */
	public void refresh(TenderProjectEntity tenderProjectEntity, EvaluationStep evaluationStep, TenderProjectRuleEntity tenderProjectRuleEntity) {
		super.refresh(tenderProjectEntity, evaluationStep, tenderProjectRuleEntity);
		refreshResultTable();
	}
	
	/**
	 * @Description: 刷新结果表格
	 * @author chenxw 
	 */
	private void refreshResultTable() {
		if (null != resultTable) resultTable.dispose();
		if(null == editPriceItemService){
			editPriceItemService = new EditPriceItemService();
		}
		resultTable = new KTable(composite, SWTX.AUTO_SCROLL | SWT.FULL_SELECTION | SWTX.FILL_WITH_LASTCOL | SWTX.EDIT_ON_KEY);
		resultTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		List<Supplier> supplierList = supplierService.getEvaluationStepSupplierList(tenderProjectEntity.getId(), evaluationStep);
		if (null == supplierList) supplierList = new ArrayList<Supplier>();
		List<EditPriceItem> editPriceItemList = editPriceItemService.getEditPriceItemList(tenderProjectEntity.getId());
		if (null == editPriceItemList) editPriceItemList = new ArrayList<EditPriceItem>();
		
		CommonKtableCModel model = new CommonKtableCModel(resultTable, headRow, headCol, supplierList.size(), editPriceItemList.size() * 2 + 1);
		model.setContentRowHeight(Constants.ROW_HIGHT);
		resultTable.setModel(model);
		
		evaluationPriceCol = editPriceItemList.size() * 2 + headCol;
		
		refreshResultTableTitle(model, editPriceItemList);
		refreshResultTableContent(supplierList, editPriceItemList);
		
		// 设置单元格内容
		model.setCellContentRender(new CellContentRender() {
			public Object receiveContent(int row, int col) {
				return ObjectUtils.getObjString(contentMap.get(new Point(row, col)));
			}
		});
		
		// 编辑单元格对齐方式
		model.setCellAlignmentRender(new CellAlignmentRender() {
			public int receiveCellAlignment(int row, int col) {
				if (row < headRow) return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
				if (col == evaluationPriceCol) return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_RIGHT;
				return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_LEFT;
			}
		});
		
	}

	/**
	 * @Description: 刷新表头
	 * @author chenxw
	 * @param model
	 * @param editPriceItemList 
	 */
	private void refreshResultTableTitle(CommonKtableCModel model, List<EditPriceItem> editPriceItemList) {
		String supplierName = com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProjectEntity.getTenderType());
		contentMap.put(new Point(0, 0), MessageFormat.format(Messages.NameFormat, supplierName));
		model.addRowSpan(0, 0, 2);
		model.setColumnWidth(0, 300);
		
		String editPriceTitle = "修正报价";
		String editReasonTitle = "修正原因";
		for (int i = 0; i < editPriceItemList.size(); i++) {
			contentMap.put(new Point(0, i * 2 + headCol), editPriceItemList.get(i).getItemName());
			model.addColSpan(0, i * 2 + headCol, 2);
			contentMap.put(new Point(1, i * 2 + headCol), editPriceTitle);
			model.setColumnWidth(i * 2 + headCol, 100);
			contentMap.put(new Point(1, i * 2 + headCol + 1), editReasonTitle);
			model.setColumnWidth(i * 2 + headCol + 1, 300);
		}
		contentMap.put(new Point(0, evaluationPriceCol), "评标价（" + tenderProjectRuleEntity.getPriceUnitUseDefault() + "）");
		model.addRowSpan(0, evaluationPriceCol, 2);
		model.setColumnWidth(evaluationPriceCol, 100);
	}

	/**
	 * @Description: 刷新表内容
	 * @author chenxw
	 * @param supplierList
	 * @param editPriceItemList 
	 */
	private void refreshResultTableContent(List<Supplier> supplierList, List<EditPriceItem> editPriceItemList) {
		if(null == bidPriceResultService){
			bidPriceResultService = new BidPriceResultService();
		}
		if(null == editPriceItemResultService){
			editPriceItemResultService = new EditPriceItemResultService();
		}
		Map<String, EditPriceItemResult> editPriceItemResultMap = new HashMap<String, EditPriceItemResult>();
		List<EditPriceItemResult> editPriceItemResultList = editPriceItemResultService.getEditPriceItemResultList(tenderProjectEntity.getId());
		for (EditPriceItemResult editPriceItemResult : editPriceItemResultList) {
			editPriceItemResultMap.put(editPriceItemResult.getSupplierId() + editPriceItemResult.getEditPriceItemId(), editPriceItemResult);
		}
		
		Map<String, BidPriceResult> bidPriceResultMap = new HashMap<String, BidPriceResult>();
		BidPriceService bidPriceService = new BidPriceService();
		BidPrice bidPrice = bidPriceService.getBidPriceByJoinTotal(tenderProjectEntity.getId());
		List<BidPriceResult> bidPriceResultList = bidPriceResultService.getBidPriceResultList(tenderProjectEntity.getId(), bidPrice.getId());
		if (CollectionUtils.isNotNull(bidPriceResultList)) for (BidPriceResult bidPriceResult : bidPriceResultList) {
			bidPriceResultMap.put(bidPriceResult.getSupplierId(), bidPriceResult);
		}
		
		for (int i = 0; i < supplierList.size(); i++) {
			Supplier supplier = supplierList.get(i);
			
			BidPriceResult bidPriceResult = bidPriceResultMap.get(supplier.getId());
			if (null == bidPriceResult) continue;
			BigDecimal priceOriginal = bidPriceResult.getEvaluationPriceOriginal();
			if (null == priceOriginal) priceOriginal = bidPriceResult.getBidPrice();
			if (null == priceOriginal) continue;
			if (priceOriginal.compareTo(BigDecimal.ZERO) == 0) continue;
			
			contentMap.put(new Point(i + headRow, 0), supplier.getSupplierName());
			for (int j = 0; j < editPriceItemList.size(); j++) {
				EditPriceItem editPriceItem = editPriceItemList.get(j);
				EditPriceItemResult editPriceItemResult = editPriceItemResultMap.get(supplier.getId() + editPriceItem.getId());
				if (null != editPriceItemResult) {
					contentMap.put(new Point(i + headRow, j * 2 + headCol), getEditPriceString(editPriceItemResult.getEditPrice(), editPriceItem.getEditType(), priceOriginal));
					contentMap.put(new Point(i + headRow, j * 2 + headCol + 1), editPriceItemResult.getEditReason());
				}
			}
			
			contentMap.put(new Point(i + headRow, evaluationPriceCol), bidPriceResult.getFormatEvaluatoinPriceByUnit(tenderProjectRuleEntity.getEvalPriceUnit()));
		}
	}

	/**
	 * @Description: 获取修正报价
	 * @author chenxw
	 * @param editPrice
	 * @param editType
	 * @param priceOriginal
	 * @return
	 */
	private String getEditPriceString(BigDecimal editPrice, String editType, BigDecimal priceOriginal) {
		StringBuilder editPriceString = new StringBuilder();
		if (null != editPrice) {
			if (BidPriceEnum.EDIT_ADD_SUB.equals(editType)) {
				if (editPrice.compareTo(BigDecimal.ZERO) < 0) {
					editPriceString.append("减少");
					editPrice = editPrice.multiply(BigDecimal.valueOf(-1));
				} else {
					editPriceString.append("增加");
				}
				editPriceString.append(MoneyUtils.getMoneyWidthUnit(editPrice, tenderProjectRuleEntity.getPriceUnitUseDefault()));
			} else if (BidPriceEnum.EDIT_FLOAT.equals(editType)) {
				if (editPrice.compareTo(BigDecimal.ZERO) < 0) {
					editPriceString.append("下浮");
					editPrice = editPrice.multiply(BigDecimal.valueOf(-1));
				} else {
					editPriceString.append("上浮");
				}
				editPriceString.append(moneyToFloat(editPrice, priceOriginal));
			}
		}
		return editPriceString.toString();
	}

	/**
	 * @Description: 金额转浮动
	 * @author chenxw
	 * @param editPrice
	 * @param priceOriginal
	 * @return 
	 */
	private String moneyToFloat(BigDecimal editPrice, BigDecimal priceOriginal) {
		return editPrice.multiply(BigDecimal.valueOf(100)).divide(priceOriginal, 2, BigDecimal.ROUND_HALF_UP).toPlainString().concat("%");
	}
	
	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
}
