package com.gx.obe.evaluation.step.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.core.listener.LoadingAdatper;
import org.eclipse.swt.core.widgets.ELink;
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.Display;

import com.gx.obe.action.bean.Action;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.common.widget.composite.TitleComposite;
import com.gx.obe.common.widget.shell.ProgressMessageDialog;
import com.gx.obe.common.widget.utils.MenuFunctionUtils;
import com.gx.obe.components.core.Constants;
import com.gx.obe.components.core.I18N;
import com.gx.obe.components.core.I18NEnum;
import com.gx.obe.components.core.enumeration.CommonEnum;
import com.gx.obe.components.core.util.MoneyUtils;
import com.gx.obe.evaluation.step.thread.DownLoadSupplierBidBondThread;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.BigDecimalUtils;
import com.gx.obe.util.utils.DateUtils;
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.SupplierBidBond;
import com.gx.obe.web.entity.auth.Menu;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.service.ProjectRuleService;
import com.gx.obe.web.service.SupplierBidBondService;
import com.gx.obe.web.service.SupplierService;
import com.gx.obe.web.service.TenderProjectService;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

import de.kupzog.ktable.KTable;
import de.kupzog.ktable.SWTX;
import de.kupzog.ktable.editors.KTableCellEditorText;
import de.kupzog.ktable.model.CommonKtableCModel;
import de.kupzog.ktable.renderers.CellAlignmentRender;
import de.kupzog.ktable.renderers.CellContentRender;
import de.kupzog.ktable.renderers.CellEditContentRender;
import de.kupzog.ktable.renderers.CellEditorRender;
import de.kupzog.ktable.renderers.CellRender;
import de.kupzog.ktable.renderers.FixedWrapCellRenderer;
import de.kupzog.ktable.renderers.TextCellRenderer;

/**
 * @Description: 投标保证金管理
 * @author guoyr
 */
public class BidBondComposite extends Composite {
	
	private ProjectRuleService projectRuleService = new ProjectRuleService();
	private SupplierBidBondService supplierBidBondService = new SupplierBidBondService();
	private SupplierService supplierService = new SupplierService();
	private TenderProjectEntity tenderProject;
	private Menu menu;
//	private ProjectRule projectRule;
	private List<SupplierBidBond> supplierBidBondList = new ArrayList<SupplierBidBond>();
	private List<Supplier> supplierList = new ArrayList<Supplier>();
	private Map<String,String> supplierMap = new HashMap<String,String>();
	private KTable resultKTable;
	private CommonKtableCModel commKTableModel;
//	private EButton save_btn;
	private String priceUnit = CommonEnum.YUAN;
	private TitleComposite titleComposite;
	private ELink label_down_load;
	private TenderProjectService tenderProjectService = new TenderProjectService();
	private Composite topComposite;
	
	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public BidBondComposite(Composite parent,Action action, int style) {
		super(parent, style);
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.verticalSpacing = 0;
		gridLayout.horizontalSpacing = 0;
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 0;
		setLayout(gridLayout);
		this.tenderProject = (TenderProjectEntity)parent.getData("tenderProjectEntity");
		if(null == tenderProject) {
			tenderProject = (TenderProjectEntity)parent.getData("tenderProject");
		}
		this.menu = (Menu)parent.getData("menu");
		
		titleComposite = new TitleComposite(this, SWT.NONE);
		titleComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
//		ELink importBidBondBtn = titleComposite.addELink("IMPORT");
//		importBidBondBtn.addMouseListener(new MouseAdapter() {
//			@Override
//			public void mouseUp(MouseEvent e) {
//				importBidBondAction();
//			}
//		});
//		importBidBondBtn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/download.png"));
//		importBidBondBtn.setText("导入投标保证金");
		
		Composite composite_1 = new Composite(this, SWT.NONE);
		composite_1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		composite_1.setBackground(SWTResourceManager.getColor(211, 211, 211));
		GridLayout gl_composite_1 = new GridLayout(1, false);
		gl_composite_1.verticalSpacing = 0;
		gl_composite_1.horizontalSpacing = 0;
		gl_composite_1.marginHeight = 1;
		gl_composite_1.marginWidth = 1;
		composite_1.setLayout(gl_composite_1);
		topComposite = new Composite(composite_1, SWT.NONE);
		topComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		topComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		GridLayout gl_topComposite = new GridLayout(1, false);
		gl_topComposite.verticalSpacing = 0;
		gl_topComposite.horizontalSpacing = 0;
		gl_topComposite.marginHeight = 0;
		gl_topComposite.marginWidth = 0;
		topComposite.setLayout(gl_topComposite);
		
		resultKTable = new KTable(topComposite, SWTX.AUTO_SCROLL | SWT.FULL_SELECTION | SWTX.EDIT_ON_KEY | SWTX.FILL_WITH_LASTCOL);
		resultKTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
//		Composite composite_2 = new Composite(this, SWT.NONE);
//		composite_2.setLayout(new GridLayout(1, false));
//		composite_2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
//		
//		save_btn = new EButton(composite_2, SWT.NONE);
//		save_btn.setBackground(Constants.SKIN_BG);
//		save_btn.setForeground(Constants.SKIN_FOREGROUND);
//		save_btn.setActiveBorderColor(Constants.SKIN_ACTIVE_BG);
//		save_btn.setActiveBgColor(Constants.SKIN_ACTIVE_BG);
//		save_btn.setActiveForeground(Constants.SKIN_ACTIVE_FOREGROUND);
//		save_btn.setArcWidth(6);
//		save_btn.addMouseListener(new MouseAdapter() {
//			public void mouseUp(MouseEvent e) {
//				saveAction();
//			}
//		});
//		save_btn.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
//		GridData gd_savebutton_1 = new GridData(SWT.CENTER, SWT.FILL, true, true, 1, 1);
//		gd_savebutton_1.heightHint = 35;
//		gd_savebutton_1.widthHint = 200;
//		save_btn.setLayoutData(gd_savebutton_1);
//		save_btn.setText("保 存");
		
		label_down_load = titleComposite.addELink("DOWNLOAD_BIDBOND");
		label_down_load.setText(Messages.Button_download);
		label_down_load.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				downLoadSupplierBidBond();
			}
		});
		label_down_load.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/download.png"));
	

		init();
	}
	
	public void downLoadSupplierBidBond() {
		if(label_down_load.getEnabled()){
			final ProgressMessageDialog messageProgress = new ProgressMessageDialog(getShell(), false, -1, new LoadingAdatper() {
				public void finish(boolean flag) {
					Display.getDefault().syncExec(new Runnable() {
						public void run() {
							if(!resultKTable.isDisposed()) {
								supplierBidBondList = supplierBidBondService.getSupplierBondByTenderId(tenderProject.getId());
								drawKTable();
								topComposite.layout();
								topComposite.getParent().layout();
							}
						}
					});
				}
				
			});
			new DownLoadSupplierBidBondThread(tenderProject, messageProgress).start();
			messageProgress.setTitle(MessageFormat.format(Messages.Button_downloadFormat, Messages.BidBond ));
			messageProgress.setCountDownTime(3);
			messageProgress.setForceClose(true);
			messageProgress.setOperateVisible(false);
			messageProgress.open();
		}
	
	}

	/**
	 * @Description: 初始化
	 * @author guoyr
	 */
	private void init(){
		titleComposite.setTitle(Messages.BidBond);
		supplierBidBondList.clear();
		supplierList = supplierService.getAllSupplierList(tenderProject.getId());
		if(null != supplierList && supplierList.size() > 0) {
			for(Supplier supplier : supplierList) {
				supplierMap.put(supplier.getId(), supplier.getSupplierName());
			}
		}
		supplierBidBondList = supplierBidBondService.getSupplierBondByTenderId(tenderProject.getId());
		//未开标不准查看
		if(!tenderProjectService.isBidOpeningComplate(tenderProject.getId())) {
			label_down_load.setEnabled(false);
		}
		drawKTable();
		MenuFunctionUtils menuFunctionUtils = new MenuFunctionUtils();
		menuFunctionUtils.initFunctionAuthority(menu);
	}
	
	/**
	 * @Description: 绘制表格
	 * @author guoyr 
	 */
	private void drawKTable(){
		commKTableModel = new CommonKtableCModel(resultKTable, 1, 0, supplierBidBondList.size(), 5);
		commKTableModel.setContentRowHeight(Constants.ROW_HIGHT);
		commKTableModel.setColumnWidth(0, 50);
		commKTableModel.setColumnMaxWidth(0, 200);
		commKTableModel.setColumnMinWidth(1, 200);
		commKTableModel.setColumnMinWidth(2, 200);
		commKTableModel.setColumnMinWidth(3, 200);
		commKTableModel.setColumnMinWidth(4, 50);
		resultKTable.setAutoComputerSurplusWidth(false);
		
		// 设置单元格内容
		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 MessageFormat.format(Messages.NameFormat, I18N.getString(I18NEnum.SUPPLIERNAME, tenderProject.getTenderType()));
					}else if(col == 2){
						return Messages.BidBond;
//						return "投标保证金("+CommonEnum.getPriceUintCN(priceUnit)+")";
					}else if(col == 3){
						return Messages.RemittedByBasicAccount;
					}else if(col == 4){
						return Messages.PaymentTime;
					}
				}else {
					if(col == 0){
						return row;
					}else {
						SupplierBidBond supplierBidBond = supplierBidBondList.get(row - commKTableModel.getFixedRowCount());
						if(col == 1){
							return supplierMap.get(supplierBidBond.getSupplierId());
						}else if(col == 2){
//							if(null != supplier.getBidBond() && supplier.getBidBond().compareTo(BigDecimal.ZERO) > 0){
//								return "有";
//							}
//							if(null != supplier.getBidBondType()){
//								if("1".equals(supplier.getBidBondType())){
//									return "缴纳";
//								}else if("0".equals(supplier.getBidBondType())){
//									return "不缴纳";
//								}
//							}
							return MoneyUtils.getMoneyWidthUnit(supplierBidBond.getAmount(), CommonEnum.YUAN);
						}else if(col == 3){
							if(null != supplierBidBond.getBidCashDeposiPpayType()){
								if(supplierBidBond.getBidCashDeposiPpayType().equals(CommonEnum.LEAF)){
									return Messages.Yes;
								}else{
									return Messages.No;
								}
							}else{
								return "";
							}
						}else if(col == 4){
							if(null != supplierBidBond.getRenderTime()){
								return DateUtils.getTimestampFormat(supplierBidBond.getRenderTime());
							}else {
								return "";
							}
						}
					}
				}
				return "";
			}
		};
		commKTableModel.setCellContentRender(contentRender);
		
		// 设置单元格渲染器
		CellRender cellRender = new CellRender(){
			public Object receiveCellRender(int row, int col) {
				if(commKTableModel.isFixedCell(col, row)){
					return new FixedWrapCellRenderer();
				}else{
					if(col == 2){
						return new TextCellRenderer();
					}else {
						return null;
					}
				}
			}
		};
		commKTableModel.setCellRender(cellRender);
		
		// 设置单元格编辑器
        final KTableCellEditorText text = new KTableCellEditorText();
		text.setSingleClickEdit(true);
		CellEditorRender cellEditorRender = new CellEditorRender(){
			public Object receiveCellEditor(int row, int col) {
				if(row >= commKTableModel.getFixedRowCount() && col == 2){
					return text;
				}
				return null;
			}
		};
		commKTableModel.setCellEditorRender(cellEditorRender);
		
		// 编辑单元格内容
		CellEditContentRender editContentRender = new CellEditContentRender(){
			public void receiveContent(int row, int col, Object content) {
				if(null == content)return;
				if(row >= commKTableModel.getFixedRowCount() && col == 2){
					Supplier supplier = supplierList.get(row - commKTableModel.getFixedRowCount());
					BigDecimal result = ObjectUtils.getObjBigDecimal(content);
					if(null != result && result.compareTo(BigDecimal.ZERO) > 0){
						if(StringUtils.equals(CommonEnum.WAN_YUAN, priceUnit)){
							result = BigDecimalUtils.mul(result, new BigDecimal(10000));
						}
						supplier.setBidBond(result);
					}else {
						supplier.setBidBond(null);
					}
					commKTableModel.setChanged(true);
				
				}
			}
		};
		commKTableModel.setCellEditContentRender(editContentRender);
		
		// 编辑单元格对齐方式
		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){
						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;
					}
				}
			}
		};
		commKTableModel.setCellAlignmentRender(cellAlignmentRender);
		
		resultKTable.setModel(commKTableModel);
	}
	
	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
}
