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.business.enumeration.SupplierEnum;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.components.core.enumeration.CommonEnum;
import com.gx.obe.config.utils.PropertiesUtils;
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.util.utils.StringUtils;
import com.gx.obe.util.utils.UuidUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.SupplierOpeningResult;
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.SupplierOpeningResultService;
import com.gx.obe.web.service.SupplierService;
import com.gx.obe.web.service.evaluation.EvaluationStepService;
import com.gx.utils.NowTimeUtils;
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 EvaluationPriceRepairDialog extends EDialog {
	
	private ProjectRuleService projectRuleService ;
	private SupplierService supplierService = new SupplierService();
	private SupplierOpeningResultService supplierOpeningResultService ;
	private EvaluationStepService evaluationStepService = new EvaluationStepService();
 	private List<Supplier> supplierList = new ArrayList<Supplier>();
	private TenderProjectRuleEntity tenderProjectRuleEntity;
	private TenderProjectEntity tenderProjectEntity;
	private KTable resultKTable;
	private CommonKtableCModel commKTableModel;
	private Composite contentComposite;
	private EButton saveBtn;
	private boolean canModifyFinalBidPrice = true;
	private com.gx.obe.web.service.TenderProjectService tenderProjectServices;

	
	{
		LogUtils.logClass(EvaluationPriceRepairDialog.class);
	}
	
	/**
	 * Create the dialog.
	 * @param parentShell
	 */
	public EvaluationPriceRepairDialog(Shell parentShell, TenderProjectEntity tenderProjectEntity) {
		super(parentShell);
		this.tenderProjectEntity = tenderProjectEntity;
		tenderProjectServices = new com.gx.obe.web.service.TenderProjectService();
		supplierOpeningResultService = new SupplierOpeningResultService();
	}

	/**
	 * 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) {
				saveAction();
			}
		});
		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(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);
		projectRuleService = new ProjectRuleService();
		init();
		return container;
	}
	
	/**
	 * @Description: 初始化界面
	 */
	private void init(){
		saveBtn.setEnabled(false);
		supplierList.clear();
		tenderProjectRuleEntity = projectRuleService.getProjectRule(tenderProjectEntity.getId());
		supplierList = supplierService.getSupplierOpenbidAndEvaluateResultList(tenderProjectEntity.getId());
		// 已经完成价格评审或推荐投标人，不能再修改
		if(evaluationStepService.isCompletePriceAndRecommonedStep(tenderProjectEntity.getId())){
			canModifyFinalBidPrice = false;
		}
		drawKTable();
	}
	
	/**
	 * @Description: 保存
	 */
    private void saveAction() {
        if (!saveBtn.getEnabled()) return;
        if (null != supplierList && supplierList.size() > 0) {
            int resultNum = 0;
            for (Supplier supplier : supplierList) {
                SupplierOpeningResult supplierOpeningResult = supplier.getSupplierOpeningResult();
                supplierOpeningResult.setBidOpeningStatus(SupplierEnum.OPENBID_SUCCESS);
                supplierOpeningResult.setRevokeStatus(SupplierEnum.REVOKE_NO);
                supplierOpeningResult.setBidOpeningTime(NowTimeUtils.getNowDate());
                if (StringUtils.isNotEmpty(supplierOpeningResult.getId())) {
                    if (supplierOpeningResultService.updateAssignProperty(supplierOpeningResult, new String[] { "bidOpeningStatus", "bidOpeningTime", "revokeStatus", "evaluationPrice" })) {
                        resultNum++;
                    }
                } else {
                    supplierOpeningResult.setId(UuidUtils.getUUID());
                    if (supplierOpeningResultService.insert(supplierOpeningResult)) {
                        resultNum++;
                    }
                }
            }
            if (resultNum == supplierList.size()) {
                MessageDialog.openInformation(getShell(), Messages.Tips_saveSuccess);
                
                // 修改项目开标状态
                if (!ObjectUtils.equals(tenderProjectEntity.getBidOpeningStatus(), CommonEnum.COMPLETE)) {
                    tenderProjectEntity.setBidOpeningStatus(CommonEnum.COMPLETE);
                    tenderProjectServices.updateAssignProperty(tenderProjectEntity, new String[] { "id", "bidOpeningStatus" });
                }
                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.setContentRowHeight(30);
		
		// 设置单元格内容
		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){
						String[] priceEvalContent = PropertiesUtils.getProperty("priceEvalContent", "").split(":");
						if(null != priceEvalContent && priceEvalContent.length==2){
							return priceEvalContent[0]+"（"+priceEvalContent[1]+"）";
						}
						return Messages.EvaluationPrice+"（" + tenderProjectRuleEntity.getEvalPriceUnit()+"）";
					}
				}else {
					Supplier supplier = supplierList.get(currRow);
					if(col == 0){
						return null != supplier && null != supplier.getSupplierName() ? supplier.getSupplierName() : "";
					}else if(col == 1){
						SupplierOpeningResult openBidResult = supplier.getSupplierOpeningResult();
						if(null != openBidResult) {
							return openBidResult.getFormatEvaluatoinPriceByUnit(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) {
				if(canModifyFinalBidPrice){
					return text;
				}else {
					return null;
				}
			}
		};
		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);
					SupplierOpeningResult openBidResult = null != supplier && null != supplier.getSupplierOpeningResult() ? supplier.getSupplierOpeningResult() : null;
					
					if(null != openBidResult){
						if(StringUtils.isNotEmpty(content.toString())){
							BigDecimal result = MoneyUtils.getMoneyFromText(content.toString(), tenderProjectRuleEntity.getEvalPriceUnit());
							if(null != result){
								openBidResult.setEvaluationPrice(result);
							}
						}else {
							openBidResult.setEvaluationPrice(null);
						}
						saveBtn.setEnabled(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);
	}
}
