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.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.Label;
import org.eclipse.swt.widgets.Shell;

import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.components.core.I18NEnum;
import com.gx.obe.components.core.util.MoneyUtils;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.LogUtils;
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 TenderFeeDialog extends EDialog {
	
	private SupplierService supplierService = new SupplierService();
	private ProjectRuleService projectRuleService ;
	private TenderProjectEntity tenderProjectEntity;
	private TenderProjectRuleEntity tenderProjectRuleEntity;
	private List<Supplier> supplierList;
	private KTable resultKTable;
	private CommonKtableCModel commKTableModel;
	private Composite composite;
	private EButton saveBtn;

	{
		LogUtils.logClass(TenderFeeDialog.class);
	}
	
	/**
	 * Create the dialog.
	 * @param parentShell
	 */
	public TenderFeeDialog(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);
		
		composite = new Composite(container, SWT.NONE);
		FillLayout fl_composite = new FillLayout(SWT.HORIZONTAL);
		fl_composite.marginHeight = 1;
		fl_composite.marginWidth = 1;
		composite.setLayout(fl_composite);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		Label label = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
		label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		
		Composite composite_1 = new Composite(container, SWT.NONE);
		composite_1.setBackgroundMode(SWT.INHERIT_FORCE);
		composite_1.setBackgroundImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/fill_bg.png"));
		composite_1.setLayout(new GridLayout(2, false));
		GridData gd_composite_1 = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
		gd_composite_1.widthHint = 90;
		composite_1.setLayoutData(gd_composite_1);
		
		saveBtn = new EButton(composite_1, SWT.NONE);
		saveBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				completeAction();
			}
		});
		GridData gd_saveBtn = new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1);
		gd_saveBtn.widthHint = 90;
		saveBtn.setLayoutData(gd_saveBtn);
		saveBtn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/save.png"));
		saveBtn.setText(Messages.Button_save);
		
		EButton cancel_btn = new EButton(composite_1, 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();
			}
		});
		cancel_btn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		cancel_btn.setText(Messages.Button_close);
		
		init();
		return container;
	}
	
	/**
	 * @Description: 初始化界面
	 * @author guoyr
	 */
	private void init(){
		projectRuleService = new ProjectRuleService();
		// 获得项目规则
		tenderProjectRuleEntity = projectRuleService.getProjectRule(tenderProjectEntity.getId());
		if(null == tenderProjectRuleEntity){
			tenderProjectRuleEntity = new TenderProjectRuleEntity();
		}
		// 获得项目下的投标人
		supplierList = supplierService.getSupplierList(tenderProjectEntity.getId());
		if(null == supplierList){
			supplierList = new ArrayList<Supplier>();
		}
		
		drawKTable();
	}
	
	/**
	 * @Description: 渲染KTable表格
	 * @author guoyr
	 */
	private void drawKTable(){
		resultKTable = new KTable(composite, 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.getTenderFee()){
								return MoneyUtils.getMoneyFormatByUnit(supplier.getTenderFee(), 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.setTenderFee(result);
						}else {
							supplier.setTenderFee(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);
	}
	
	/**
	 * @Description: 保存
	 * @author guoyr
	 */
	private void completeAction(){
		resultKTable.closeCellEditor();
		if(!saveBtn.getEnabled()){
			return ;
		}
		if(!commKTableModel.isChanged()){
			if(!MessageDialog.openConfirm(getShell(), "您未做任何输入，确认要保存吗？")){
				return;
			}
			
		}
		if(null != supplierList && supplierList.size() > 0){
			if(supplierService.batchSaveOrUpdate(supplierList, new String[]{"tenderFee"}) > 0){
				MessageDialog.openInformation(getShell(), Messages.Tips_saveSuccess);
				cancelAction();
			}
		}
	}
	
	/**
	 * @Description: 取消
	 * @author guoyr
	 */
	private void cancelAction(){
		getShell().close();
	}
	
	/**
	 * Return the initial size of the dialog.
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(450, 300);
	}
}
