package com.gx.obe.evaluation.step.composite.struct;

import java.io.File;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.ImageResolver;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.core.widgets.EButton;
import org.eclipse.swt.core.widgets.ELink;
import org.eclipse.swt.core.widgets.ImageButton;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import com.gx.obe.ColorConstants;
import com.gx.obe.business.enumeration.StructEnum;
import com.gx.obe.common.file.enumeration.FileConstants;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.evaluation.step.Activator;
import com.gx.obe.evaluation.step.inter.IStruct;
import com.gx.obe.evaluation.step.listener.AiEvaluationListener;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.CollectionUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.util.utils.RuntimeUtils;
import com.gx.obe.web.entity.AttachmentFile;
import com.gx.obe.web.entity.Struct;
import com.gx.obe.web.service.StructService;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/**
 * @Description: 结构化界面
 * @author chenxw
 */
public class StructComposite extends Composite {
	
	private StructService structService;
	private Label topLabel;
	private Composite fileListComposite;
	private Struct struct;
	private ImageResolver imageResolver = new ImageResolver();
	private Composite fromComposite;
	private ELink nullifyLink;
	private Canvas canvas;
	private Text reasonText;
	private Composite reasonComposite;
	private Label reasonLabel;
	private ELink editLink;
	private IStruct iStruct;
	private SkipListener skipListener;
	private EButton confirmButton;
	private ScrolledComposite scrolledComposite;
	private Composite contentComposite;
	private boolean isLast;
	private int widthHint = 300;
	private String structState;
	private AiEvaluationListener listener;
	private boolean isModified;
	
	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public StructComposite(Composite parent, int style) {
		super(parent, style);
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.verticalSpacing = 0;
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 0;
		setLayout(gridLayout);
		
		addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent e) {
				imageResolver.disposite();
			}
		});
		
		Composite topComposite = new Composite(this, SWT.NONE);
		topComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
		topComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		GridLayout gl_topComposite = new GridLayout(3, false);
		topComposite.setLayout(gl_topComposite);
		
		topLabel = new Label(topComposite, SWT.WRAP);
		topLabel.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		topLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1));
		
		editLink = new ELink(topComposite, SWT.NONE);
		editLink.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				editAction();
			}
		});
		editLink.setText("修正");
		editLink.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/edit.png"));
		
		nullifyLink = new ELink(topComposite, SWT.NONE);
		nullifyLink.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/fail.png"));
		nullifyLink.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				nullifyAction();
			}
		});
		
		Composite composite = new Composite(this, SWT.NONE);
		composite.setLayout(new FormLayout());
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		canvas = new Canvas(composite, SWT.TRANSPARENT);
		canvas.addPaintListener(new PaintListener() {
			public void paintControl(PaintEvent e) {
				e.gc.setAlpha(180);
				Point textSize = e.gc.stringExtent(Messages.Confirm_toBe);
				int textX = canvas.getBounds().width - textSize.x;
				int textY = canvas.getBounds().height - textSize.y;
				if (StructEnum.STATE_EFFECTIVE.equals(structState)) {
					e.gc.drawImage(ResourceManager.getPluginImage(Activator.PLUGIN_ID, "icons/evaluation_yes.png"), 0, 0);
				} else if (StructEnum.STATE_INVALID.equals(structState)) {
					e.gc.drawImage(ResourceManager.getPluginImage(Activator.PLUGIN_ID, "icons/evaluation_waste.png"), 0, 0);
				} else {
					textX = 6;
					textY = 6;
				}
				if (isModified) {
					e.gc.setAlpha(150);
					e.gc.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
					e.gc.fillRoundRectangle(textX - 6, textY - 6, textSize.x + 1, textSize.y + 1, 10, 10);
					e.gc.setAlpha(-1);
					e.gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
					e.gc.drawRoundRectangle(textX - 5, textY - 5, textSize.x + 4, textSize.y + 4, 10, 10);
					e.gc.drawText(Messages.Confirm_toBe, textX - 3, textY - 3, true);
				}
			}
		});
		FormData fd_canvas = new FormData();
		fd_canvas.top = new FormAttachment(0, 10);
		fd_canvas.bottom = new FormAttachment(0, 74);
		fd_canvas.left = new FormAttachment(0, 10);
		fd_canvas.right = new FormAttachment(0, 74);
		canvas.setLayoutData(fd_canvas);
		
		scrolledComposite = new ScrolledComposite(composite, SWT.V_SCROLL);
		FormData fd_scrolledComposite = new FormData();
		fd_scrolledComposite.top = new FormAttachment(0);
		fd_scrolledComposite.bottom = new FormAttachment(100);
		fd_scrolledComposite.left = new FormAttachment(0);
		fd_scrolledComposite.right = new FormAttachment(100);
		scrolledComposite.setLayoutData(fd_scrolledComposite);
		scrolledComposite.setExpandHorizontal(true);
		scrolledComposite.setExpandVertical(true);
		
		contentComposite = new Composite(scrolledComposite, SWT.NONE);
		contentComposite.setLayout(new GridLayout(1, false));
		
		scrolledComposite.setContent(contentComposite);
		
		fromComposite = new Composite(contentComposite, SWT.NONE);
		fromComposite.setLayout(new GridLayout(1, false));
		GridData gd_fromComposite = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
		gd_fromComposite.widthHint = widthHint;
		fromComposite.setLayoutData(gd_fromComposite);
		
		reasonComposite = new Composite(contentComposite, SWT.NONE);
		GridData gd_reasonComposite = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
		gd_reasonComposite.widthHint = widthHint;
		reasonComposite.setLayoutData(gd_reasonComposite);
		GridLayout gl_reasonComposite = new GridLayout(1, false);
		gl_reasonComposite.marginWidth = 10;
		reasonComposite.setLayout(gl_reasonComposite);
		
		reasonLabel = new Label(reasonComposite, SWT.NONE);
		reasonLabel.setForeground(ColorConstants.FONT_BLACK_COLOR);
		
		reasonText = new Text(reasonComposite, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
		GridData gd_nullifyReasonText = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
		gd_nullifyReasonText.heightHint = 80;
		reasonText.setLayoutData(gd_nullifyReasonText);
		reasonText.setTextLimit(100);
		
		fileListComposite = new Composite(contentComposite, SWT.NONE);
		RowLayout rl_fileListComposite = new RowLayout(SWT.HORIZONTAL);
		rl_fileListComposite.fill = true;
		rl_fileListComposite.center = true;
		rl_fileListComposite.justify = true;
		fileListComposite.setLayout(rl_fileListComposite);
		GridData gd_fileListComposite = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1);
		gd_fileListComposite.widthHint = widthHint;
		fileListComposite.setLayoutData(gd_fileListComposite);
		
		Composite buttonComposite = new Composite(contentComposite, SWT.NONE);
		GridData gd_buttonComposite = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
		gd_buttonComposite.widthHint = widthHint;
		buttonComposite.setLayoutData(gd_buttonComposite);
		buttonComposite.setLayout(new GridLayout(1, false));
		
		confirmButton = new EButton(buttonComposite, SWT.NONE | EButton.CSS_GREEN);
		GridData gd_confirmButton = new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1);
		gd_confirmButton.heightHint = 35;
		confirmButton.setLeftMargin(10);
		confirmButton.setRightMargin(10);
		confirmButton.setLayoutData(gd_confirmButton);
		confirmButton.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
		confirmButton.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				confirmAction();
			}
		});
		structService = new StructService();
	}
	
	/**
	 * @Description: 修正事件
	 * @author chenxw
	 */
	private void editAction() {
		if (!editLink.getEnabled()) {
			return;
		}
		editLink.setEnabled(false);
		
		isModified = true;
		iStruct.setEdit(true);
		
		reasonComposite.setVisible(true);
		((GridData) reasonComposite.getLayoutData()).exclude = false;
		reasonLabel.setText("修正原因：");
		reasonComposite.layout();
		
		if (isLast) {
			confirmButton.setEnabled(true);
		}
		
		contentComposite.layout();
		scrolledComposite.setMinSize(contentComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
	}
	
	/**
	 * @Description: 确认事件
	 * @author chenxw
	 */
	private void confirmAction() {
		if (!confirmButton.getEnabled()) {
			return;
		}
		
		if (StructEnum.STATE_UNCONFIRMED.equals(structState)) {
			structState = StructEnum.STATE_EFFECTIVE;
		} else if (StructEnum.STATE_INVALID.equals(structState)) {
			if (reasonText.getText().isEmpty()) {
				MessageDialog.openShortMessage("请输入作废原因！");
				return;
			}
		}
		
		isModified = false;
		canvas.redraw();
		
		refreshNullifyState();
		
		struct.setStructState(structState);
		struct.setReason(reasonText.getText().trim());
		iStruct.refreshEditData();
		
		structService.updateAssignProperty(struct, new String[] { "id","structState", "reason", "structContent" });
		listener.refreshSupplierStruct(struct.getSupplierId());
		
		if (isLast) {
			listener.refreshSupplierResult(struct.getSupplierId());
			confirmButton.setEnabled(false);
			MessageDialog.openShortMessage("当前指标已评审完成！");
		}
		
		if (null != skipListener) {
			skipListener.next();
		}
		
	}
	
	/**
	 * @Description: 作废事件
	 * @author chenxw
	 */
	private void nullifyAction() {
		if (StructEnum.STATE_INVALID.equals(structState)) {
			structState = struct.getStructState().equals(StructEnum.STATE_INVALID) ? StructEnum.STATE_UNCONFIRMED : struct.getStructState();
		} else {
			structState = StructEnum.STATE_INVALID;
		}
		reasonText.setText("");
		
		isModified = true;
		
		if (isLast) {
			confirmButton.setEnabled(true);
		}
		
		refreshNullifyState();
		canvas.redraw();
	}
	
	/**
	 * @Description: 刷新作废状态
	 * @author chenxw
	 */
	private void refreshNullifyState() {
		iStruct.setEdit(false);
		if (StructEnum.STATE_INVALID.equals(structState)) {
			nullifyLink.setText("采用");
			nullifyLink.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/submit.png"));
			if (isLast) {
				confirmButton.setText("   确认作废   ");
			} else {
				confirmButton.setText("确认作废并进入下一项");
			}
			reasonComposite.setVisible(true);
			((GridData) reasonComposite.getLayoutData()).exclude = false;
			reasonLabel.setText("作废原因：");
			editLink.setEnabled(false);
		} else {
			editLink.setEnabled(true);
			nullifyLink.setText("作废");
			nullifyLink.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/fail.png"));
			if (isLast) {
				confirmButton.setText("   确   认   ");
			} else {
				confirmButton.setText("确认并进入下一项");
			}
			if (reasonText.getText().trim().isEmpty()) {
				reasonComposite.setVisible(false);
				((GridData) reasonComposite.getLayoutData()).exclude = true;
			} else {
				reasonComposite.setVisible(true);
				((GridData) reasonComposite.getLayoutData()).exclude = false;
				reasonLabel.setText("修正原因：");
			}
		}
		
		nullifyLink.getParent().layout();
		confirmButton.getParent().layout();
		reasonComposite.layout();
		
		contentComposite.layout();
		scrolledComposite.setMinSize(contentComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
	}
	
	/**
	 * @Description: 刷新
	 * @author chenxw
	 * @param struct
	 * @param isLast
	 */
	public void refresh(Struct struct, boolean isLast) {
		this.struct = struct;
		this.isLast = isLast;
		this.structState = struct.getStructState();
		
		isModified = false;
		reasonText.setText(ObjectUtils.getObjString(struct.getReason()));
		
		refreshFromComposite();
		refreshFileListComposite();
	}
	
	/**
	 * @Description: 刷新表单
	 * @author chenxw
	 */
	private void refreshFromComposite() {
		for (Control control : fromComposite.getChildren()) {
			control.dispose();
		}
		
		String structType = struct.getStructType();
		
		if (structType.equals(StructEnum.EQ_ENTERPRISE_INFO)) {

		} else if (structType.equals(StructEnum.EQ_BUSINESS_LICENSE)) {
			iStruct = new BusinessLicenseComposite(fromComposite, SWT.NONE);
		} else if (structType.equals(StructEnum.EQ_FINANCIAL_REPORT)) {
			iStruct = new FinanceComposite(fromComposite, SWT.NONE);
		} else if (structType.equals(StructEnum.EQ_ACHIEVEMENTS)) {
			iStruct = new PerformanceComposite(fromComposite, SWT.NONE);
		} else if (structType.equals(StructEnum.EQ_QUALIFICATION_ZXDJ)) {
			iStruct = new QualificationZXDJComposite(fromComposite, SWT.NONE);
		} else if (structType.equals(StructEnum.EQ_QUALIFICATION_ZLJX)) {
			iStruct = new QualificationZLJXComposite(fromComposite, SWT.NONE);
		} else if (structType.equals(StructEnum.EQ_QUALIFICATION_ZLJX_SJ)) {
			iStruct = new QualificationZLJXComposite(fromComposite, SWT.NONE);
		} else if (structType.equals(StructEnum.EQ_QUALIFICATION_KJYF)) {
			iStruct = new QualificationKJYFComposite(fromComposite, SWT.NONE);
		} else if (structType.equals(StructEnum.EQ_QUALIFICATION_KJYF_SJ)) {
			iStruct = new QualificationKJYFComposite(fromComposite, SWT.NONE);
		} else if (structType.equals(StructEnum.EQ_QUALIFICATION_HYPM)) {
			iStruct = new QualificationHYPMComposite(fromComposite, SWT.NONE);
		} else if (structType.equals(StructEnum.EQ_QUALIFICATION_XJS)) {
			iStruct = new QualificationComposite(fromComposite, SWT.NONE);
		} else if (structType.equals(StructEnum.EQ_QUALIFICATION_SCXK)) {
			iStruct = new QualificationComposite(fromComposite, SWT.NONE);
		} else if (structType.equals(StructEnum.EQ_QUALIFICATION_CPRZ)) {
			iStruct = new QualificationComposite(fromComposite, SWT.NONE);
		} else if (structType.equals(StructEnum.EQ_QUALIFICATION_HBTX)) {
			iStruct = new QualificationComposite(fromComposite, SWT.NONE);
		} else if (structType.equals(StructEnum.EQ_QUALIFICATION)) {
			iStruct = new QualificationComposite(fromComposite, SWT.NONE);
		}
		
		if (null != iStruct) {
			iStruct.refresh(struct);
		}
		
		iStruct.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		topLabel.setText(iStruct.getTopName());
		
		fromComposite.layout();
		refreshNullifyState();
		
		contentComposite.layout();
		scrolledComposite.setMinSize(contentComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
		
	}
	
	/**
	 * @Description: 刷新文件列表
	 * @author chenxw
	 */
	private void refreshFileListComposite() {
		for (Control control : fileListComposite.getChildren()) {
			control.dispose();
		}
		
		List<AttachmentFile> attachmentList = struct.getAttachmentFileList();
		
		if (CollectionUtils.isNull(attachmentList)) {
			return;
		}
		boolean isShowImageView = attachmentList.size() <= 5;
		for (final AttachmentFile attachmentFile : attachmentList) {
			newFileImageButton(attachmentFile, isShowImageView);
		}
		
		fileListComposite.layout();
		
		contentComposite.layout();
		scrolledComposite.setMinSize(contentComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
	}
	
	/**
	 * @Description: 创建文件按钮
	 * @author chenxw
	 * @param attachmentFile
	 * @param isShowImageView
	 */
	private void newFileImageButton(final AttachmentFile attachmentFile, boolean isShowImageView) {
		ImageButton label = new ImageButton(fileListComposite, isShowImageView ? SWT.NONE | SWT.BOTTOM | SWT.WRAP : SWT.NONE);
		label.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE));
		label.setActiveBgColor(ColorConstants.SKIN_BG);
		label.setActiveBorderColor(ColorConstants.SKIN_BG);
		label.setActiveForeground(SWTResourceManager.getColor(255, 153, 0));
		label.setTopMargin(10);
		label.setBottomMargin(10);
		label.setArcWidth(5);
		label.setAlpha(10);
		final File localFile = new File(FileConstants.getBidFilePath(struct.getTenderId(), struct.getSupplierId()).concat("files").concat(File.separator).concat(attachmentFile.getName()));
		if (isShowImageView) {
			label.setBorderColor(ColorConstants.BORDER_LINE_COLOR);
			String suffix = localFile.getName().substring(localFile.getName().lastIndexOf("."));
			if (".jpg;.bmp;.png".contains(suffix) && localFile.exists()) {
				Image image = imageResolver.loadImage(localFile);
				label.setImage(imageResolver.getZoomImage(image, 180, 100));
				label.setLayoutData(new RowData(200, SWT.DEFAULT));
			} else if (".docx;.doc".contains(suffix) && localFile.exists()) {
				Image image = ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/word_64.png");
				label.setImage(imageResolver.getZoomImage(image, 180, 100));
				label.setLayoutData(new RowData(200, SWT.DEFAULT));
			} else if (".pdf".contains(suffix) && localFile.exists()) {
				Image image = ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/pdf_64.png");
				label.setImage(imageResolver.getZoomImage(image, 180, 100));
				label.setLayoutData(new RowData(200, SWT.DEFAULT));
			} else {
				label.setLayoutData(new RowData(160, SWT.DEFAULT));
				Image image = imageResolver.getSysIcon(localFile, 50);
				label.setImage(image);
			}
		} else {
			label.setLayoutData(new RowData(SWT.DEFAULT, SWT.DEFAULT));
			Image image = imageResolver.getSysIcon(localFile, 24);
			label.setImage(image);
		}
		label.addMouseListener(new MouseAdapter() {
			public void mouseDoubleClick(MouseEvent e) {
				if (localFile.exists() && localFile.isFile()) RuntimeUtils.openFIle(localFile);
				else MessageDialog.openShortMessage(ObjectUtils.getObjString(attachmentFile.getFileName()) + "不存在！");
			}
		});
		label.setText(ObjectUtils.getObjString(attachmentFile.getFileName()));
	}
	
	public void addAiEvaluationListener(AiEvaluationListener listener) {
		this.listener = listener;
	}
	
	public void addSkipListener(SkipListener skipListener) {
		this.skipListener = skipListener;
	}
	
	public interface SkipListener {
		void next();
	}
	
	protected void checkSubclass() {}
	
}
