package com.gx.obe.management.dialog;

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

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.core.widgets.EButton;
import org.eclipse.swt.core.widgets.EDialog;
import org.eclipse.swt.core.widgets.ESepator;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
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.Shell;

import com.gx.obe.ColorConstants;
import com.gx.obe.components.core.I18NEnum;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.LogUtils;
import com.gx.obe.components.core.util.MoneyUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.web.entity.Supplier;
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.SupplierService;
import com.swtdesigner.ResourceManager;

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.TextWrapCellRenderer;

/**
 * @Description: 保证金管理
 * @author guoyr
 */
public class BidBondDialog extends EDialog {
	
	private SupplierService supplierService = new SupplierService();
	private ProjectRuleService projectRuleService;
	private List<Supplier> supplierList = new ArrayList<Supplier>();
	private KTable resultKTable;
	private CommonKtableCModel commKTableModel;
	private TenderProjectRuleEntity tenderProjectRuleEntity;
	private TenderProjectEntity tenderProjectEntity;
	private Composite contentComposite;
	private EButton saveBtn;

	{
		LogUtils.logClass(BidBondDialog.class);
	}
	
	/**
	 * Create the dialog.
	 * @param parentShell
	 */
	public BidBondDialog(Shell parentShell, TenderProjectEntity tenderProjectEntity) {
		super(parentShell);
		this.tenderProjectEntity = tenderProjectEntity;
	}

	/**
	 * Create contents of the dialog.
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		Composite container = (Composite) super.createDialogArea(parent);
		GridLayout gl_container = new GridLayout(1, false);
		gl_container.verticalSpacing = 0;
		gl_container.horizontalSpacing = 0;
		gl_container.marginHeight = 0;
		gl_container.marginWidth = 0;
		container.setLayout(gl_container);
		
		contentComposite = new Composite(container, SWT.NONE);
		FillLayout fl_contentComposite = new FillLayout(SWT.HORIZONTAL);
		fl_contentComposite.marginHeight = 1;
		fl_contentComposite.marginWidth = 1;
		contentComposite.setLayout(fl_contentComposite);
		contentComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		ESepator label = new ESepator(container, SWT.SEPARATOR | SWT.HORIZONTAL);
		label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		label.setBackground(ColorConstants.SEP_LIGHT_COLOR);
		
		Composite operateComposite = new Composite(container, SWT.NONE);
		operateComposite.setBackgroundMode(SWT.INHERIT_FORCE);
		operateComposite.setBackgroundImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/fill_bg.png"));
		GridLayout gl_operateComposite = new GridLayout(2, false);
		operateComposite.setLayout(gl_operateComposite);
		operateComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		saveBtn = new EButton(operateComposite, SWT.NONE);
		saveBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				completeAction();
			}
		});
		GridData gd_completeBtn = new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1);
		gd_completeBtn.widthHint = 90;
		saveBtn.setLayoutData(gd_completeBtn);
		saveBtn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/save.png"));
		saveBtn.setText(Messages.Button_save);
		
		EButton cancel_btn = new EButton(operateComposite, SWT.NONE);
		cancel_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/close.png"));
		cancel_btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				cancelAction();
			}
		});
		GridData gd_cancelBtn = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		gd_cancelBtn.widthHint = 90;
		cancel_btn.setLayoutData(gd_cancelBtn);
		cancel_btn.setText(Messages.Button_close);
		
		init();
		return container;
	}
	
	/**
	 * @Description: 初始化界面
	 */
	private void init(){
		projectRuleService = new ProjectRuleService();
		supplierList.clear();
		tenderProjectRuleEntity = projectRuleService.getProjectRule(tenderProjectEntity.getId());
		supplierList = supplierService.getSupplierList(tenderProjectEntity.getId());
		
		drawKTable();
	}

	/**
	 * @Description: 保存
	 */
	private void completeAction(){
		resultKTable.closeCellEditor();
		if(!commKTableModel.isChanged()){
			if(!MessageDialog.openConfirm(getShell(), "您未做任何输入，确认要保存吗？")){
				return;
			}
		}
		if(null != supplierList && supplierList.size() > 0){
			int resultNum = supplierService.batchSaveOrUpdate(supplierList, new String[]{"bidBond"});
			if(resultNum > 0){
				MessageDialog.openInformation(getShell(), Messages.Tips_saveSuccess);
				cancelAction();
			}
		}
	}
	
	/**
	 * @Description: 取消
	 */
	private void cancelAction(){
		getShell().close();
	}

	/**
	 * @Description: 实现评审表格
	 */
	private void drawKTable(){
		resultKTable = new KTable(contentComposite, SWTX.AUTO_SCROLL | SWT.FULL_SELECTION | SWTX.EDIT_ON_KEY | SWTX.FILL_WITH_LASTCOL);
		commKTableModel = new CommonKtableCModel(resultKTable, 1, 1, supplierList.size(), 1);
		commKTableModel.setColumnMinWidth(0, 200);
		
		// 设置单元格内容
		CellContentRender contentRender = new CellContentRender(){
			public Object receiveContent(int row, int col) {
				int currRow = row - commKTableModel.getFixedRowCount();
				if(row == 0){
					if(col == 0){
						return MessageFormat.format(Messages.NameFormat, com.gx.obe.components.core.I18N.getString(I18NEnum.SUPPLIERNAME, tenderProjectEntity.getTenderType()));
					}else if(col == 1){
						return "保证金("+tenderProjectRuleEntity.getEvalPriceUnit()+")";
					}
				}else {
					Supplier supplier = supplierList.get(currRow);
					if(null != supplier){
						if(col == 0){
							return ObjectUtils.getObjString(supplier.getSupplierName());
						}else if(col == 1){
							if(null != supplier.getBidBond()){
								return MoneyUtils.getMoneyFormatByUnit(supplier.getBidBond(), tenderProjectRuleEntity.getEvalPriceUnit());
							}
						}
					}
				}
				return "";
			}
		};
		commKTableModel.setCellContentRender(contentRender);
		
		// 设置单元格渲染器
		CellRender cellRender = new CellRender(){
			public Object receiveCellRender(int row, int col) {
				if(commKTableModel.isFixedCell(col, row)){
					return new FixedWrapCellRenderer();
				}else{
					return new TextWrapCellRenderer();
				}
			}
		};
		commKTableModel.setCellRender(cellRender);
		
		// 设置单元格编辑器
        final KTableCellEditorText text = new KTableCellEditorText();
		text.setSingleClickEdit(true);
		CellEditorRender cellEditorRender = new CellEditorRender(){
			public Object receiveCellEditor(int row, int col) {
				return text;
			}
		};
		commKTableModel.setCellEditorRender(cellEditorRender);
		
		// 编辑单元格内容
		CellEditContentRender editContentRender = new CellEditContentRender(){
			public void receiveContent(int row, int col, Object content) {
				if(null == content)return;
				int currRow = row - commKTableModel.getFixedRowCount();
				if(!commKTableModel.isFixedCell(col, row)){
					Supplier supplier = supplierList.get(currRow);
					if(null != supplier && ObjectUtils.getObjString(content).length() < 17){
						BigDecimal result = MoneyUtils.getMoneyFromText(content.toString(), tenderProjectRuleEntity.getEvalPriceUnit());
						if(null != result && result.compareTo(BigDecimal.ZERO) > 0){
							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(col < commKTableModel.getFixedColumnCount() && row >= commKTableModel.getFixedRowCount()){
					return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_LEFT;
				}else {
					if(row < commKTableModel.getFixedRowCount()){
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_CENTER;
					}else{
						return SWTX.ALIGN_VERTICAL_CENTER | SWTX.ALIGN_HORIZONTAL_RIGHT;
					}
				}
			}
		};
		commKTableModel.setCellAlignmentRender(cellAlignmentRender);
		
		resultKTable.setModel(commKTableModel);
	}
	
	/**
	 * Return the initial size of the dialog.
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(500, 350);
	}
}
