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

import java.text.MessageFormat;
import java.util.List;

import org.eclipse.nebula.widgets.grid.Grid;
import org.eclipse.nebula.widgets.grid.GridColumn;
import org.eclipse.nebula.widgets.grid.GridItem;
import org.eclipse.nebula.widgets.grid.listener.GridCheckedListener;
import org.eclipse.swt.SWT;
import org.eclipse.swt.core.CallBack;
import org.eclipse.swt.core.ImageResolver;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.core.listener.TextHintListener;
import org.eclipse.swt.core.listener.VerifyRequiredListener;
import org.eclipse.swt.core.utils.ValidateUtils;
import org.eclipse.swt.core.utils.WidgetUtils;
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.custom.CLabel;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
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 org.eclipse.swt.widgets.Text;

import com.gx.obe.ColorConstants;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.common.widget.button.Tips;
import com.gx.obe.components.core.I18NEnum;
import com.gx.obe.components.core.enumeration.CommonEnum;
import com.gx.obe.components.core.enumeration.EvaluationFactorEnum;
import com.gx.obe.components.core.enumeration.EvaluationStepEnum;
import com.gx.obe.config.utils.PropertiesUtils;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.CollectionUtils;
import com.gx.obe.util.utils.LogUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.web.entity.evaluation.EvaluationFactor;
import com.gx.obe.web.entity.evaluation.EvaluationStep;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.service.evaluation.EvaluationFactorService;
import com.gx.obe.web.service.evaluation.EvaluationStepFactorService;
import com.gx.obe.web.service.evaluation.EvaluationStepService;
import org.eclipse.swt.core.utils.GridUtils;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/**
 * @Description: 工程量步骤
 * @author chenxw
 */
public class EngineeringStepDialog extends EDialog {
	
	private EvaluationFactorService evaluationFactorService = new EvaluationFactorService();
	private EvaluationStepService evaluationStepService = new EvaluationStepService();
	private EvaluationStepFactorService evaluationStepFactorService ;
	
	private final ImageResolver imageResolver = ImageResolver.RESOLVER_INSTANCE;
	
	private final Image tree_expend = imageResolver.loadImage(IconsActivator.PLUGIN_ID, "icons/tree_expend.png");
	private final Image tree_close = imageResolver.loadImage(IconsActivator.PLUGIN_ID, "icons/tree_close.png");
	
	private final Image menuOpenImage = imageResolver.loadImage(IconsActivator.PLUGIN_ID, "icons/tree_parent.png");
	private final Image menuImage = imageResolver.loadImage(IconsActivator.PLUGIN_ID, "icons/tree_item.png");
	
	private final String ROLE_TYPE = "roleType";
	private final String EVALUATION_FACTOR = "evaluationFactor";
	
	private TenderProjectEntity tenderProjectEntity;
	private EvaluationStep evaluationStep;
	
	private Text stepNameText;
	private Text stepMemoText;
	private Composite roleTypeComposite;
	private Grid factorGrid;
	private EButton save_btn;
	
	private List<Object> selectionFactorIdList;
	private CallBack callBack;
	
	{
		LogUtils.logClass(EngineeringStepDialog.class);
	}
	
	/**
	 * Create the dialog.
	 * @param parentShell
	 */
	public EngineeringStepDialog(Shell parentShell, TenderProjectEntity tenderProjectEntity, EvaluationStep evaluationStep) {
		super(parentShell);
		this.setTitle(Messages.Step_step);
		this.setOperator(SWT.MAX | SWT.CLOSE);
		
		this.tenderProjectEntity = tenderProjectEntity;
		this.evaluationStep = evaluationStep;
	}
	
	/**
	 * Create contents of the dialog.
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		Composite topContainer = (Composite) super.createDialogArea(parent);
		GridLayout gl_topContainer = new GridLayout(1, false);
		gl_topContainer.verticalSpacing = 0;
		gl_topContainer.horizontalSpacing = 0;
		gl_topContainer.marginHeight = 0;
		gl_topContainer.marginWidth = 0;
		topContainer.setLayout(gl_topContainer);
		
		Composite container = new Composite(topContainer, SWT.NONE);
		container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		GridLayout gl_container = new GridLayout(3, false);
		gl_container.marginHeight = 10;
		gl_container.marginWidth = 10;
		container.setLayout(gl_container);
		
		Tips label_6 = new Tips(container, SWT.WRAP);
		label_6.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1));
		label_6.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, EvaluationStepEnum.getEvaluationStepIco(EvaluationStepEnum.BILL)));
		label_6.setText(MessageFormat.format(Messages.Tips_factorStep, Messages.Factor_bill));
		label_6.setSurroundColor(SWTResourceManager.getColor(60, 138, 226));
		
		Composite composite = new Composite(container, SWT.NONE);
		GridLayout gl_composite = new GridLayout(2, false);
		gl_composite.verticalSpacing = 10;
		composite.setLayout(gl_composite);
		GridData gd_composite = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
		gd_composite.widthHint = 414;
		composite.setLayoutData(gd_composite);
		
		Label step_name = new Label(composite, SWT.NONE);
		step_name.setFont(SWTResourceManager.getFont("微软雅黑", 9, SWT.NORMAL));
		step_name.setAlignment(SWT.RIGHT);
		step_name.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		step_name.setText(Messages.StepName + ": ");
		
		Composite composite_2 = new Composite(composite, SWT.NONE);
		composite_2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		GridLayout gl_composite_2 = new GridLayout(1, false);
		gl_composite_2.marginWidth = 0;
		gl_composite_2.verticalSpacing = 1;
		gl_composite_2.marginHeight = 0;
		composite_2.setLayout(gl_composite_2);
		
		stepNameText = new Text(composite_2, SWT.NONE);
		stepNameText.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false, 1, 1));
		stepNameText.setFont(SWTResourceManager.getFont("微软雅黑", 9, SWT.NORMAL));
		stepNameText.setText(PropertiesUtils.getEnum(I18NEnum.BILL_FACTOR, "清单") + "评审");
		stepNameText.setTextLimit(20);
		stepNameText.addPaintListener(new TextHintListener(Messages.Tips_EnterEvaluationStepName));
		stepNameText.addVerifyListener(new VerifyRequiredListener(stepNameText,  MessageFormat.format(Messages.Tips_required, Messages.StepName)));
		
		ESepator label = new ESepator(composite_2, SWT.NONE);
		label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		label.setBackground(ColorConstants.SEP_LIGHT_COLOR);
		
		CLabel label_1 = new CLabel(composite, SWT.NONE);
		label_1.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false, 1, 1));
		label_1.setText(Messages.EvalExpert + "：");
		
		roleTypeComposite = new Composite(composite, SWT.NONE);
		roleTypeComposite.setLayout(new RowLayout(SWT.HORIZONTAL));
		roleTypeComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
		
		Button button = new Button(roleTypeComposite, SWT.RADIO);
		button.setText(Messages.ExpertLeader);
		button.setData(ROLE_TYPE, EvaluationStepEnum.EXPERT_LEADER);
		
		Label label_5 = new Label(composite, SWT.NONE);
		label_5.setFont(SWTResourceManager.getFont("微软雅黑", 9, SWT.NORMAL));
		label_5.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, true, 1, 1));
		label_5.setText(Messages.Note + ": ");
		
		stepMemoText = new Text(composite, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
		stepMemoText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
		stepMemoText.setTextLimit(100);
		
		Composite table_border_composite = new Composite(container, SWT.NONE);
		table_border_composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		GridLayout gl_composite_table = new GridLayout(1, false);
		gl_composite_table.marginHeight = 1;
		gl_composite_table.marginWidth = 1;
		table_border_composite.setLayout(gl_composite_table);
		table_border_composite.setBackground(ColorConstants.BORDER_LINE_COLOR);
		
		Composite table_composite = new Composite(table_border_composite, SWT.NONE);
		table_composite.setBackground(SWTResourceManager.getColor(255, 255, 255));
		table_composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		GridLayout gl_table_composite = new GridLayout(1, false);
		gl_table_composite.marginWidth = 0;
		gl_table_composite.marginBottom = 5;
		gl_table_composite.marginHeight = 0;
		gl_table_composite.verticalSpacing = 0;
		table_composite.setLayout(gl_table_composite);
		
		factorGrid = new Grid(table_composite, SWT.H_SCROLL | SWT.V_SCROLL);
		GridData gd_grid = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
		gd_grid.widthHint = 200;
		factorGrid.setLayoutData(gd_grid);
		factorGrid.setAutoHeight(true);
		factorGrid.addListener(SWT.Selection, new GridCheckedListener(false));
		
		GridColumn gridColumn = new GridColumn(factorGrid, SWT.CHECK);
		gridColumn.setWidth(150);
		gridColumn.setWordWrap(true);
		gridColumn.setShowTreeTogglePic(true);
		gridColumn.setTreeTogglePic(tree_expend, tree_close);
		gridColumn.setTree(true);
		
		ESepator but_sep = new ESepator(topContainer, SWT.SEPARATOR | SWT.HORIZONTAL);
		but_sep.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		but_sep.setBackground(ColorConstants.SEP_LIGHT_COLOR);
		
		Composite composite_1 = new Composite(topContainer, 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(2, false);
		composite_1.setLayout(gl_composite_1);
		
		save_btn = new EButton(composite_1, SWT.NONE);
		save_btn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				saveEvaluationStepAction();
			}
		});
		GridData gd_confirmBtn = new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1);
		gd_confirmBtn.widthHint = 90;
		save_btn.setLayoutData(gd_confirmBtn);
		save_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/save.png"));
		save_btn.setText(Messages.Button_save);
		
		EButton cancel_btn = new EButton(composite_1, SWT.NONE);
		cancel_btn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				cancelAction();
			}
		});
		GridData gd_button = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		gd_button.widthHint = 90;
		cancel_btn.setLayoutData(gd_button);
		cancel_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/close.png"));
		cancel_btn.setText(Messages.Button_close);
		
		init();
		return container;
	}
	
	/**
	 * @Description: 初始化
	 * @author chenxw
	 */
	private void init() {
		evaluationStepFactorService = new EvaluationStepFactorService();
		boolean isCheckable = true;
		boolean isCheckAll = true;
		if (null == evaluationStep) {
			evaluationStep = new EvaluationStep();
			evaluationStep.setStepType(EvaluationStepEnum.BILL);
			evaluationStep.setStepName(PropertiesUtils.getEnum(I18NEnum.BILL_FACTOR, "清单") + "评审");
			evaluationStep.setRoleType(EvaluationStepEnum.EXPERT_LEADER);
			evaluationStep.setStepStatus(CommonEnum.NOT_START);
			this.setTitle(MessageFormat.format(Messages.Title_create, Messages.Step_step));
		} else {
			if (ObjectUtils.equals(evaluationStep.getStepStatus(), CommonEnum.COMPLETE)) {
				stepNameText.setEnabled(false);
				stepMemoText.setEnabled(false);
				roleTypeComposite.setEnabled(false);
				save_btn.setEnabled(false);
				isCheckable = false;
			} else if (evaluationStepService.isInEvaluationStep(tenderProjectEntity.getId(), evaluationStep.getId())) {
				roleTypeComposite.setEnabled(false);
				isCheckable = false;
			}
	 
			selectionFactorIdList = evaluationStepFactorService.getFactorIdLsitByStepId(evaluationStep.getId());
			this.setTitle(MessageFormat.format(Messages.Title_edit, Messages.Step_step));
			isCheckAll = false;
		}
		refreshEvaluationStepForm();
		refreshFactorTree(isCheckable, isCheckAll);
	}
	
	/**
	 * @Description: 刷新评标步骤表单
	 * @author chenxw
	 */
	private void refreshEvaluationStepForm() {
		stepNameText.setText(ObjectUtils.getObjString(evaluationStep.getStepName()));
		stepMemoText.setText(ObjectUtils.getObjString(evaluationStep.getStepMemo()));
		WidgetUtils.setRadioChecked(roleTypeComposite, ObjectUtils.getObjString(evaluationStep.getRoleType()), ROLE_TYPE);
	}
	
	/**
	 * @Description: 刷新指标树
	 * @author chenxw
	 * @param isCheckable 是否可点击
	 * @param isCheckAll 是否全选
	 */
	public void refreshFactorTree(boolean isCheckable, boolean isCheckAll) {
		factorGrid.removeAll();
		
		List<EvaluationFactor> factorList = evaluationFactorService.getFactorListOfEvaluationStep(tenderProjectEntity.getId(), EvaluationFactorEnum.AUDIT_BILL, evaluationStep.getId());
		
		if (CollectionUtils.isNull(factorList)) {
			return;
		}
		
		GridItem topGridItem = new GridItem(factorGrid, SWT.NONE);
		topGridItem.setText(PropertiesUtils.getEnum(I18NEnum.BILL_FACTOR, "工程量") + "指标");
		topGridItem.setImage(0, menuOpenImage);
		topGridItem.setExpanded(true);
		topGridItem.setCheckable(0, isCheckable);
		
		if (factorList.size() == 1) {
			topGridItem.setText(factorList.get(0).getFactorName());
			topGridItem.setData(EVALUATION_FACTOR, factorList.get(0));
			factorList = factorList.get(0).getChildFactorList();
		} else {
			topGridItem.setText(PropertiesUtils.getEnum(I18NEnum.BILL_FACTOR, "工程量") + "指标");
		}
		
		for (EvaluationFactor factor : factorList) {
			GridItem gridItem = new GridItem(topGridItem, SWT.NONE);
			gridItem.setCheckable(0, isCheckable);
			initChildGridItem(factor, gridItem);
		}
		
		if (isCheckAll) {
			GridUtils.checkAll(factorGrid, 0, true);
		} else {
			GridUtils.refreshGridCheckedStatus(factorGrid, 0);
		}
	}
	
	/**
	 * @Description: 递归实现指标树
	 * @author chenxw
	 * @param factor
	 * @param parentGridItem
	 */
	private void initChildGridItem(EvaluationFactor factor, GridItem parentGridItem) {
		parentGridItem.setText(0, factor.getFactorName());
		parentGridItem.setToolTipText(0, parentGridItem.getText());
		parentGridItem.setData(EVALUATION_FACTOR, factor);
		if (null != selectionFactorIdList && selectionFactorIdList.contains(factor.getId())) {
			parentGridItem.setChecked(0, true);
		}
		List<EvaluationFactor> childFactorList = factor.getChildFactorList();
		if (CollectionUtils.isNull(childFactorList)) {
			parentGridItem.setImage(0, menuImage);
		} else {
			for (EvaluationFactor childFactor : childFactorList) {
				if (ObjectUtils.equals(childFactor.getFactorType(), EvaluationFactorEnum.FACTOR_FLOAT)) {
					continue;
				}
				GridItem gridItem = new GridItem(parentGridItem, SWT.NONE);
				gridItem.setCheckVisible(0, false);
				initChildGridItem(childFactor, gridItem);
			}
			parentGridItem.setExpanded(true);
			parentGridItem.setImage(0, menuOpenImage);
		}
	}
	
	/**
	 * @Description: 保存事件
	 * @author chenxw
	 */
	private void saveEvaluationStepAction() {
		if (!save_btn.getEnabled()) {
			return;
		}
		if (!ValidateUtils.checkInput(stepNameText.getParent())) {
			return;
		}
		
		// 验证评标步骤名称是否已经存在
		if (evaluationStepService.valEvaluationStepNameExist(tenderProjectEntity.getId(), evaluationStep.getId(), stepNameText.getText().trim())) {
			MessageDialog.openWarning(getShell(), Messages.Step_step +"[" + stepNameText.getText().trim() + "]" + Messages.Tips_AlreadyExistsPleaseRetype);
			stepNameText.setFocus();
			stepNameText.setSelection(stepNameText.getText().length());
			return;
		}
		
		evaluationStep.setTenderId(tenderProjectEntity.getId());
		evaluationStep.setStepName(stepNameText.getText().trim());
		evaluationStep.setStepMemo(stepMemoText.getText().trim());
		evaluationStep.setRoleType(ObjectUtils.getObjString(WidgetUtils.getRadioVal(roleTypeComposite, ROLE_TYPE)));
		
		List<EvaluationFactor> checkedFactorList = GridUtils.getRealCheckedValues(factorGrid, 0, EVALUATION_FACTOR);
		if (CollectionUtils.isNull(checkedFactorList)) {
			MessageDialog.openWarning(getShell(), Messages.Tips_select + stepNameText.getText().trim() + "的评审指标！");
			return;
		}
		
		evaluationStep = evaluationStepService.saveEvaluationStepAndFactors(evaluationStep, checkedFactorList, null, null);
		if (null != evaluationStep && null != callBack) {
			callBack.callBackObject(evaluationStep);
		} else {
			MessageDialog.openWarning(getShell(), stepNameText.getText() + Messages.Tips_saveFail);
		}
		this.getShell().close();
	}
	
	/**
	 * @Description: 取消
	 * @author guoyr
	 */
	private void cancelAction() {
		this.getShell().close();
	}
	
	public CallBack getCallBack() {
		return callBack;
	}
	
	public void setCallBack(CallBack callBack) {
		this.callBack = callBack;
	}
	
	/**
	 * Return the initial size of the dialog.
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(650, 500);
	}
}
