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

import java.io.File;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.eclipse.swt.SWT;
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.Display;
import org.eclipse.swt.widgets.Label;

import com.gx.obe.ColorConstants;
import com.gx.obe.common.file.entity.BidFile;
import com.gx.obe.common.file.enumeration.FileConstants;
import com.gx.obe.components.core.Constants;
import com.gx.obe.components.core.I18NEnum;
import com.gx.obe.evaluation.step.inter.IBidPriceShowTable;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.XmlUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.SupplierOpeningResult;
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.swtdesigner.SWTResourceManager;

import de.kupzog.ktable.KTable;
import de.kupzog.ktable.KTableCellSelectionAdapter;
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.CellRender;
import de.kupzog.ktable.renderers.FixedCellRenderer;
import de.kupzog.ktable.renderers.TextCellRenderer;

/**
 * @Description: 投标总报价管理
 * @author guoyr
 */
public class ShowSubBidPriceTableComposite extends Composite implements IBidPriceShowTable{
	
	private BidPriceResultService bidPriceResultService ;
	private KTable bidPriceTable;
	private CommonKtableCModel commKTableModel;
	private Map<String, BidPriceResult> supplierBidPriceResultMap;
	private List<BidPrice> bidPriceList;
	private List<Supplier> supplierList;
	private Composite bidPriceDetailComposite;

	
	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public ShowSubBidPriceTableComposite(Composite parent, int style) {
		super(parent, style);
		setBackground(ColorConstants.BORDER_LINE_COLOR);
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.verticalSpacing = 0;
		gridLayout.horizontalSpacing = 0;
		gridLayout.marginHeight = 1;
		gridLayout.marginWidth = 1;
		setLayout(gridLayout);
		
		Composite composite = new Composite(this, SWT.NONE);
		composite.setBackgroundMode(SWT.INHERIT_FORCE);
		composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		GridData gd_composite = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
		gd_composite.heightHint = 100;
		composite.setLayoutData(gd_composite);
		GridLayout gl_composite = new GridLayout(1, false);
		gl_composite.marginHeight = 0;
		gl_composite.marginWidth = 0;
		composite.setLayout(gl_composite);
		
		bidPriceTable = new KTable(composite, SWTX.AUTO_SCROLL | SWT.FULL_SELECTION | SWTX.FILL_WITH_LASTCOL | SWTX.EDIT_ON_KEY);
		bidPriceTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		bidPriceDetailComposite = new Composite(this, SWT.NONE);
		bidPriceDetailComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		bidPriceDetailComposite.setBackgroundMode(SWT.INHERIT_FORCE);
		bidPriceDetailComposite.setVisible(false);
		GridData gd_bidPriceDetailComposite = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
		gd_bidPriceDetailComposite.heightHint = 100;
		gd_bidPriceDetailComposite.exclude = true;
		bidPriceDetailComposite.setLayoutData(gd_bidPriceDetailComposite);
		GridLayout gl_bidPriceDetailComposite = new GridLayout(1, false);
		gl_bidPriceDetailComposite.verticalSpacing = 0;
		gl_bidPriceDetailComposite.horizontalSpacing = 0;
		gl_bidPriceDetailComposite.marginHeight = 0;
		gl_bidPriceDetailComposite.marginWidth = 0;
		bidPriceDetailComposite.setLayout(gl_bidPriceDetailComposite);
		init();
	}
	
	private void init() {
		bidPriceResultService = new BidPriceResultService();
		final int bidPriceStartIndex = 2;
		bidPriceTable.addCellSelectionListener(new KTableCellSelectionAdapter() {
			public void cellSelected(int col, int row, int statemask) {
				bidPriceDetailComposite.setVisible(false);
				((GridData) bidPriceDetailComposite.getLayoutData()).exclude = true;
				layout();
				if (row < commKTableModel.getFixedRowCount()) {
					return;
				}
				BidPrice _bidPrice = null;
				if (bidPriceList.size() == 1) {
					_bidPrice = bidPriceList.get(0);
				} else if (bidPriceList.size() > col - bidPriceStartIndex) {
					_bidPrice = bidPriceList.get(col - bidPriceStartIndex);
				}
				if (null == _bidPrice) {
					return;
				}
				final Supplier supplier = supplierList.get(row - commKTableModel.getFixedRowCount());
				final BidPrice bidPrice = _bidPrice;
				new Thread(new Runnable() {
					public void run() {
						String bidPriceDetailFileName = BidFile.getBidPriceDetailFileName(supplier.getTenderId(), supplier.getId(), bidPrice.getSortNo() - 1);
						if (null == bidPriceDetailFileName || bidPriceDetailFileName.isEmpty()) {
							return;
						}
						File xmlFile = new File(FileConstants.getBidFilePath(supplier.getTenderId(), supplier.getId()) + bidPriceDetailFileName);
						if (null == xmlFile || !xmlFile.exists()) {
							return;
						}
						Document document = XmlUtils.getXmlDocument(xmlFile.getAbsolutePath());
						if (null == document) {
							return;
						}
						final List<?> trElementList = document.getRootElement().elements("tr");
						if (null == trElementList || trElementList.isEmpty()) {
							return;
						}
						Element trElement = (Element) trElementList.get(0);
						final List<?> tdElementList = trElement.elements("td");
						if (null == tdElementList || tdElementList.isEmpty()) {
							return;
						}
						Display.getDefault().syncExec(new Runnable() {
							public void run() {
								showBidPriceDetailTable(supplier, bidPrice, trElementList, tdElementList);
							}
						});
					}
				}).start();
			}
		});
	}

	/**
	 * @Description: 显示报价明细列表
	 * @author chenxw
	 * @param bidPrice 
	 * @param supplier 
	 * @param trElementList
	 * @param tdElementList 
	 */
	private void showBidPriceDetailTable(Supplier supplier, BidPrice bidPrice, final List<?> trElementList, final List<?> tdElementList) {
		if (null == bidPriceDetailComposite || bidPriceDetailComposite.isDisposed()) {
			return;
		}
		bidPriceDetailComposite.setVisible(true);
		((GridData) bidPriceDetailComposite.getLayoutData()).exclude = false;
		
		for (Control control : bidPriceDetailComposite.getChildren()) {
			control.dispose();
		}
		
		Composite labelComposite = new Composite(bidPriceDetailComposite, SWT.NONE);
		labelComposite.setBackground(ColorConstants.SKIN_BG);
		labelComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		labelComposite.setLayout(new GridLayout(1, false));
		
		Label label = new Label(labelComposite, SWT.NONE);
		label.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		label.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		label.setText(supplier.getSupplierName().concat("-").concat(bidPrice.getBidPriceName().concat("明细")));
		
//		ESepator topSep = new ESepator(bidPriceDetailComposite, SWT.NONE);
//		topSep.setBackground(ColorConstants.SEP_LIGHT_COLOR);
//		topSep.setLineStyle(SWT.LINE_DOT);
//		topSep.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1));
		
		Composite composite = new Composite(bidPriceDetailComposite, SWT.NONE);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		GridLayout gl_composite = new GridLayout(1, false);
		gl_composite.marginHeight = 0;
		gl_composite.marginWidth = 0;
		composite.setLayout(gl_composite);
		
		KTable bidPriceDetailTable = new KTable(composite, SWTX.AUTO_SCROLL | SWT.FULL_SELECTION | SWTX.FILL_WITH_LASTCOL | SWTX.EDIT_ON_KEY);
		bidPriceDetailTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		final CommonKtableCModel bidPriceDetailTableModel = new CommonKtableCModel(bidPriceDetailTable, 1, 0, trElementList.size() - 1, tdElementList.size());
		bidPriceDetailTableModel.setContentRowHeight(Constants.ROW_HIGHT);

		// 设置单元格内容
		CellContentRender contentRender = new CellContentRender() {
			public Object receiveContent(int row, int col) {
				if (row < bidPriceDetailTableModel.getFixedRowCount()) {
					if (tdElementList.size() > col) {
						Element tdElement = (Element) tdElementList.get(col);
						return tdElement.getTextTrim();
					}
				} else {
					Element trElement = (Element) trElementList.get(row);
					List<?> tdElementList = trElement.elements("td");
					if (tdElementList.size() > col) {
						Element tdElement = (Element) tdElementList.get(col);
						return tdElement.getTextTrim();
					}
				}
				return "";
			}
		};
		bidPriceDetailTableModel.setCellContentRender(contentRender);

		// 设置单元格渲染器
		CellRender cellRender = new CellRender() {
			public Object receiveCellRender(int row, int col) {
				if (bidPriceDetailTableModel.isFixedCell(col, row)) {
					return new FixedCellRenderer();
				} else {
					return new TextCellRenderer();
				}
			}
		};
		bidPriceDetailTableModel.setCellRender(cellRender);

		// 编辑单元格对齐方式
		CellAlignmentRender cellAlignmentRender = new CellAlignmentRender() {
			public int receiveCellAlignment(int row, int col) {
				return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
			}
		};
		bidPriceDetailTableModel.setCellAlignmentRender(cellAlignmentRender);

		bidPriceDetailTable.setModel(bidPriceDetailTableModel);
		bidPriceDetailComposite.layout();
		layout();
	}
	
	/** 
	 * @Description: 刷新投标报价
	 * @author guoyr
	 * @param tenderProjectEntity
	 * @param tenderProjectRuleEntity
	 * @param supplierList 
	 */
	public void refreshBidPriceResult(final TenderProjectEntity tenderProjectEntity, final TenderProjectRuleEntity tenderProjectRuleEntity, final List<Supplier> supplierList, final List<BidPrice> bidPriceList){
		this.supplierList = supplierList;
		this.bidPriceList = bidPriceList;
		commKTableModel = new CommonKtableCModel(bidPriceTable, 1, 0, supplierList.size(), 3 + bidPriceList.size() + (bidPriceList.size() > 1?1:0));
		commKTableModel.setContentRowHeight(Constants.ROW_HIGHT);
		commKTableModel.setColumnWidth(0, 50);
		commKTableModel.setColumnMaxWidth(0, 50);
		commKTableModel.setColumnWidth(1, 200);
		final int bidPriceStartIndex = 2;
		if(bidPriceList.size() > 3){
			for(int col = 0; col < bidPriceList.size(); col ++){
				commKTableModel.setColumnWidth(col +bidPriceStartIndex, 100);
			}
			bidPriceTable.setAutoComputerSurplusWidth(true);
		}else {
			for(int col = 0; col < bidPriceList.size(); col ++){
				commKTableModel.setColumnWidth(col +bidPriceStartIndex, 150);
			}
			bidPriceTable.setAutoComputerSurplusWidth(false);
		}
		final int totalBidPriceCol = bidPriceList.size() > 1?commKTableModel.getColCount() -2 : -1;
		if(totalBidPriceCol > 0){
			commKTableModel.setColumnWidth(totalBidPriceCol, 200);
		}
		supplierBidPriceResultMap = new HashMap<String, BidPriceResult>();
		Map<String, BidPriceResult> queryBidPriceResultMap = new HashMap<String, BidPriceResult>();
		List<BidPriceResult> bidPriceResultList = bidPriceResultService.getBidPriceResultList(tenderProjectEntity.getId(), null);
		if(null != bidPriceResultList){
			for(BidPriceResult bidPriceResult : bidPriceResultList){
				queryBidPriceResultMap.put(bidPriceResult.getSupplierId()+"_"+bidPriceResult.getBidPriceId(), bidPriceResult);
			}
		}
		for(Supplier supplier : supplierList){
			for(BidPrice bidPrice : bidPriceList){
				BidPriceResult bidPriceResult = queryBidPriceResultMap.get(supplier.getId()+"_"+bidPrice.getId());
				supplierBidPriceResultMap.put(supplier.getId() + "_" + bidPrice.getId(), bidPriceResult);
			}
		}
		
		// 设置单元格内容
		commKTableModel.setCellContentRender(new CellContentRender(){
			public Object receiveContent(int row, int col) {
				if(row < commKTableModel.getFixedRowCount()){
					if(col == 0){
						return Messages.Num ;
					}else if(col == 1){
						return MessageFormat.format(Messages.NameFormat, com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProjectEntity.getTenderType()));
					}else if(col >= bidPriceStartIndex && col < bidPriceStartIndex + bidPriceList.size()){
						BidPrice bidPrice = bidPriceList.get(col - bidPriceStartIndex);
						if(null != bidPrice){
							return bidPrice.getBidPriceName();
						}
					} else if(col == totalBidPriceCol){
						return "投标报价合计(" + tenderProjectRuleEntity.getPriceUnitUseDefault()+")";
					}
					return "";
				}else {
					if(col == 0){
						return row +"";
					}else{
						Supplier supplier = supplierList.get(row - commKTableModel.getFixedRowCount());
						if(col == 1){
							return supplier.getSupplierName();
						}else if(col >= bidPriceStartIndex && col < bidPriceStartIndex + bidPriceList.size()){
							BidPrice bidPrice = bidPriceList.get(col -bidPriceStartIndex);
							if(null != bidPrice){
								BidPriceResult bidPriceResult = supplierBidPriceResultMap.get(supplier.getId()+"_"+bidPrice.getId());
								if(null != bidPriceResult && null != bidPriceResult.getBidPrice()){
									return bidPriceResult.getBidPriceWithUnit(tenderProjectRuleEntity.getPriceUnitUseDefault());
								}
							}
						}else if(col == totalBidPriceCol){
							SupplierOpeningResult supplierOpeningResult = supplier.getSupplierOpeningResult();
							if(null != supplierOpeningResult && null != supplierOpeningResult.getBidPrice()){
								BidPriceResult bidPriceResult = null;
								if (null != bidPriceList && bidPriceList.size() != 0) {
									bidPriceResult = supplierBidPriceResultMap.get(supplier.getId()+"_"+bidPriceList.get(0).getId());
								}
								if (null == bidPriceResult) {
									return supplierOpeningResult.getBidPriceWithUnit(tenderProjectRuleEntity.getPriceUnitUseDefault());
								} else {
									return supplierOpeningResult.getBidPriceWithUnit(tenderProjectRuleEntity.getPriceUnitUseDefault());
								}
							}
						}
					}
				}
				return "";
			}
		});
		
		// 设置单元格渲染器
		commKTableModel.setCellRender(new CellRender(){
			public Object receiveCellRender(int row, int col) {
				if(commKTableModel.isFixedCell(col, row)){
					return new FixedCellRenderer();
				}else {
					return new TextCellRenderer();
				}
			}
		});
		
		// 编辑单元格对齐方式
		commKTableModel.setCellAlignmentRender(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 == 1){
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_LEFT;
					}else{
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
					}
				}
			}
		});
		
		bidPriceTable.setModel(commKTableModel);
	
	}
	
	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
}
