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

import java.text.MessageFormat;
import java.text.SimpleDateFormat;

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.ELabel;
import org.eclipse.swt.core.widgets.ESepator;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Point;
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.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.gx.obe.ColorConstants;
import com.gx.obe.business.entity.ExpertEvaluationStep;
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.web.entity.evaluation.EvaluationStep;
import com.gx.obe.web.service.ProjectRuleService;
import com.gx.obe.web.service.TenderProjectService;
import com.gx.obe.web.service.expert.ExpertEvaluationStepService;
import com.gx.utils.NowTimeUtils;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/** 
 * @Description: 申请退回
 * @author guoyr 
 */
public class ApplyReEvaluationDialog extends EDialog {
	private Text applyReasonText;
	private Text historyApplyReasonText;
	private EButton applyReEvaluation_btn;
	private Label stepName;
	private EvaluationStep evaluationStep;
	private ExpertEvaluationStep expertEvaluationStep;
	private Composite applyReason_composite;
	private Composite apply_composite;
	private SashForm sashForm;
	private TenderProjectService tenderProjectService ;
	private ExpertEvaluationStepService expertEvaluationStepService ;
	private Label messageLabel;
	private Label textCount;
	
	{
		LogUtils.logClass(ApplyReEvaluationDialog.class);
	}
	
	public ApplyReEvaluationDialog(Shell parentShell, EvaluationStep evaluationStep, ExpertEvaluationStep expertEvaluationStep) {
		super(parentShell);
		this.evaluationStep = evaluationStep;
		this.expertEvaluationStep = expertEvaluationStep;
		setTitle(Messages.Button_appllyForBack);
		tenderProjectService = new TenderProjectService();
		expertEvaluationStepService = new ExpertEvaluationStepService();
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		
		Composite top = (Composite) super.createDialogArea(parent);
		GridLayout gl_top = new GridLayout(1, false);
		gl_top.verticalSpacing = 0;
		gl_top.horizontalSpacing = 0;
		gl_top.marginHeight = 0;
		gl_top.marginWidth = 0;
		top.setLayout(gl_top);
		
		Composite container = new Composite(top, SWT.NONE);
		container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
		GridLayout gl_container = new GridLayout(1, false);
		gl_container.marginHeight = 10;
		gl_container.marginWidth = 10;
		container.setLayout(gl_container);
		
		stepName = new Label(container, SWT.WRAP);
		stepName.setForeground(ColorConstants.NOTE_TIPS_COLOR);
		stepName.setFont(SWTResourceManager.getFont("微软雅黑", 12, SWT.BOLD));
		stepName.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1));
		stepName.setText(evaluationStep.getStepName());
		
		sashForm = new SashForm(top, SWT.NONE);
		sashForm.setBackground(ColorConstants.BORDER_LINE_COLOR);
		sashForm.setSashWidth(1);
		sashForm.setOrientation(SWT.VERTICAL);
		sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		applyReason_composite = new Composite(sashForm, SWT.NONE);
		applyReason_composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		GridLayout gl_applyReason_composite = new GridLayout(1, false);
		gl_applyReason_composite.marginHeight = 0;
		gl_applyReason_composite.verticalSpacing = 0;
		gl_applyReason_composite.marginWidth = 0;
		applyReason_composite.setLayout(gl_applyReason_composite);
		
		CLabel label_2 = new CLabel(applyReason_composite, SWT.NONE);
		label_2.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/tips.png"));
		label_2.setForeground(ColorConstants.FONT_BLACK_COLOR);
		label_2.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
		label_2.setText(Messages.Title_hisReBackReason);
		
		ESepator label_1 = new ESepator(applyReason_composite, SWT.SEPARATOR | SWT.HORIZONTAL);
		label_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		label_1.setBackground(ColorConstants.SEP_LIGHT_COLOR);
		
		historyApplyReasonText = new Text(applyReason_composite, SWT.READ_ONLY | SWT.WRAP | SWT.V_SCROLL);
		historyApplyReasonText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		historyApplyReasonText.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		historyApplyReasonText.setTextLimit(200);
		historyApplyReasonText.setText("");
		
		apply_composite = new Composite(sashForm, SWT.NONE);
		apply_composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		GridLayout gl_apply_composite = new GridLayout(1, false);
		gl_apply_composite.marginHeight = 0;
		gl_apply_composite.verticalSpacing = 0;
		gl_apply_composite.marginWidth = 0;
		apply_composite.setLayout(gl_apply_composite);
		
		ELabel lblsbd = new ELabel(apply_composite, SWT.WRAP);
		lblsbd.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/edit.png"));
		lblsbd.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
		lblsbd.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		lblsbd.setForeground(ColorConstants.FONT_BLACK_COLOR);
		lblsbd.setText(Messages.Title_reBackReason);
		
		ESepator label_r2 = new ESepator(apply_composite, SWT.SEPARATOR | SWT.HORIZONTAL);
		label_r2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		label_r2.setBackground(ColorConstants.SEP_LIGHT_COLOR);
		
		applyReasonText = new Text(apply_composite, SWT.WRAP | SWT.V_SCROLL);
		applyReasonText.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		applyReasonText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		applyReasonText.setTextLimit(500);
		sashForm.setWeights(new int[] {1, 1});
		
		messageLabel = new Label(top, SWT.WRAP);
		messageLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1));
		messageLabel.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		messageLabel.setForeground(ColorConstants.NOTE_TIPS_COLOR); 
		
		ESepator label = new ESepator(top, SWT.SEPARATOR | SWT.HORIZONTAL);
		label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		label.setBackground(ColorConstants.SEP_LIGHT_COLOR);
		
		Composite composite_1 = new Composite(top, SWT.NONE);
		composite_1.setBackgroundMode(SWT.INHERIT_FORCE);
		composite_1.setBackgroundImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/fill_bg.png"));
		composite_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		GridLayout gl_composite_1 = new GridLayout(3, false);
		composite_1.setLayout(gl_composite_1);
		
		textCount = new Label(composite_1, SWT.NONE);
		textCount.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		textCount.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1));
		textCount.setForeground(ColorConstants.NOTE_TIPS_COLOR);
		textCount.setText("");
		
		
		applyReEvaluation_btn = new EButton(composite_1, SWT.NONE);
		applyReEvaluation_btn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				saveAction();
			}
		});
		GridData gd_revokeBtn = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
		applyReEvaluation_btn.setLayoutData(gd_revokeBtn);
		applyReEvaluation_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/hand.png"));
		applyReEvaluation_btn.setText(Messages.Button_appllyForBack);
		
		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) {
				getShell().close();
			}
		});
		GridData gd_cancleBtn = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		cancel_btn.setLayoutData(gd_cancleBtn);
		cancel_btn.setText(Messages.Button_close);

		init();
		return container;
	}
	
	/**
	 * @Description:初始化 
	 * @author guoyr 
	 */
	private void init(){
		new ProjectRuleService();
		messageLabel.setText(Messages.Tips_evaluationReturn);
		if(null != expertEvaluationStep.getApplyReason()){
			historyApplyReasonText.setText(expertEvaluationStep.getApplyReason());
			historyApplyReasonText.setSelection(historyApplyReasonText.getText().length());
		}
		if(CommonEnum.YES.equals(expertEvaluationStep.getApplyStatus())){
			applyReEvaluation_btn.setText(Messages.Button_cancelApplication);
			messageLabel.setText(Messages.Tips_evaluationReturning);
			sashForm.setMaximizedControl(applyReason_composite);
		}else {
			applyReEvaluation_btn.setText(Messages.Button_appllyForBack);
			if(null == expertEvaluationStep.getApplyReason() || expertEvaluationStep.getApplyReason().length() == 0){
				sashForm.setMaximizedControl(apply_composite);
			}
			boolean canReBack = true;
			if(tenderProjectService.isEvaluationComplate(evaluationStep.getTenderId())){
				applyReEvaluation_btn.setEnabled(false);
				applyReasonText.setEditable(false);
				messageLabel.setText(Messages.Tips_evaluationFinishReturn);
				canReBack = false;
			}else {
				// 内蒙临时解决方案，如果是两阶段开标，如果经济标开标完成后，其之前的评标步骤不能再进行回退
//				TenderProjectRuleEntity tenderProjectRuleEntity = projectRuleService.getProjectRule(evaluationStep.getTenderId());
//				if(null != tenderProjectRuleEntity && TenderProjectEnum.BID_OPENING_TWO_STAGE.equals(tenderProjectRuleEntity.getBidOpeningStage())){
//					TenderProjectEntity tenderProjectEntity = tenderProjectService.getById(evaluationStep.getTenderId());
//					if(null != tenderProjectEntity.getPriceBidStatus() && tenderProjectEntity.getPriceBidStatus().equals(CommonEnum.COMPLETE)){
//						// 目前无法区是哪些步骤是经济标开标之前的步骤，暂时先用最后一个打分步骤
//						List<EvaluationStep> scoreEvaluationStepList = evaluationStepService.getEvaluationStepListByType(tenderProjectEntity.getId(), com.gx.obe.components.core.enumeration.EvaluationStepEnum.DETAIL);
//						if(null != scoreEvaluationStepList && scoreEvaluationStepList.size() > 0){
//							if(evaluationStep.getSortNo() <= scoreEvaluationStepList.get(scoreEvaluationStepList.size()-1).getSortNo()){
//								applyReEvaluation_btn.setEnabled(false);
//								applyReasonText.setEditable(false);
//								messageLabel.setText(Messages.Tips_evaluationPriceFinishReturn);
//								canReBack = false;
//							}
//						}
//					}
//				}
			}
			if(!canReBack){
				final String keyCharacter = PropertiesUtils.getProperty("keyCharacter", "g");
				if(null != keyCharacter && keyCharacter.length() > 0){
					final Listener keyListener = new Listener() {
						public void handleEvent(Event e) {
							if ((e.stateMask == SWT.CTRL) && e.keyCode == keyCharacter.charAt(0)){
								applyReEvaluation_btn.setEnabled(!applyReEvaluation_btn.getEnabled());
								applyReasonText.setEditable(!applyReasonText.getEditable());
							}
						}
					};
					apply_composite.getDisplay().addFilter(SWT.KeyDown, keyListener);;
					apply_composite.addDisposeListener(new DisposeListener() {
						public void widgetDisposed(DisposeEvent e) {
							apply_composite.getDisplay().removeFilter(SWT.KeyDown, keyListener);  
						}
					});
				}
			}
		}
		applyReasonText.forceFocus();
		applyReasonText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent arg0) {
				textCount.setText(MessageFormat.format(Messages.Tips_inputWordsCountWidthMax, applyReasonText.getText().trim().length(), 200));
			}
		});
		
	}

	/**
	 * @Description: 保存
	 * @author guoyr 
	 */
	private void saveAction(){
		if(!applyReEvaluation_btn.getEnabled()){
			return;
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		if(null != expertEvaluationStep.getApplyStatus() && expertEvaluationStep.getApplyStatus().equals(CommonEnum.YES)){
			StringBuilder reason = new StringBuilder(expertEvaluationStep.getApplyReason());
			reason.append("\r\n");
			reason.append(format.format(NowTimeUtils.getNowDate()));
			reason.append("－");
			reason.append(Messages.Button_cancelApplication);
			expertEvaluationStep.setApplyStatus(null);
			expertEvaluationStep.setApplyReason(reason.toString());
			expertEvaluationStepService.updateAssignProperty(expertEvaluationStep, new String[]{"applyStatus", "applyReason"});
			getShell().close();
		}else {
			if(applyReasonText.getText().trim().length() > 0){
//				if(MessageDialog.openConfirm(getShell(), "确认要申请退回，重新进行评审吗？")){
					expertEvaluationStep.setApplyStatus(CommonEnum.YES);
					StringBuilder reason = new StringBuilder();
					if(historyApplyReasonText.getText().length() > 0){
						reason.append(historyApplyReasonText.getText());
						reason.append("\r\n");
					}
					reason.append(format.format(NowTimeUtils.getNowDate()));
					reason.append("\r\n      ");
					reason.append(applyReasonText.getText().trim());
					expertEvaluationStep.setApplyReason(reason.toString());
					expertEvaluationStepService.updateAssignProperty(expertEvaluationStep, new String[]{"applyStatus", "applyReason"});
					getShell().close();
//				}
			}else {
				MessageDialog.openShortMessage(MessageFormat.format(Messages.Tips_pleaseEnter, Messages.Title_reBackReason));
			}
		}
	
	}
	

	/**
	 * Return the initial size of the dialog.
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(650, 400);
	}
}
