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

import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.core.utils.FileDialogUtils;
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.EMenu;
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.business.entity.SignatureFile;
import com.gx.obe.common.file.enumeration.FileConstants;
import com.gx.obe.common.file.service.SignatureFileService;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.components.core.Constants;
import com.gx.obe.config.ConfigConstants;
import com.gx.obe.config.utils.LogUtils;
import com.gx.obe.config.utils.PropertiesUtils;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.FileUtils;
import com.gx.obe.util.utils.RuntimeUtils;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.web.entity.auth.AuthUser;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.tools.ole.DocumentFactory;
import com.gx.tools.ole.DocumentLoader;
import com.gx.tools.ole.signature.CircleSignatureDialog;
import com.gx.tools.utils.SignaturePdfUtils;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/**
 * @Description: 打开签到承诺书
 * @author wangx
 */
public class ShowSignNodeDialog extends EDialog {

	private Composite container;
	private File documentFile;
	private DocumentLoader documentLoader;
	private Composite composite;
	private Composite signComposite;
	private EButton import_btn;
	private EButton emport_btn;
	private EButton sign_btn;
	private TenderProjectEntity tenderProject;
	private boolean signatureSelftCommitment = false;;
	
	{
		LogUtils.logClass(ShowSignNodeDialog.class);
	}
	
	/**
	 * @wbp.parser.constructor
	 */
	public ShowSignNodeDialog(Shell parentShell,TenderProjectEntity tenderProject, boolean signatureSelftCommitment) {
		super(parentShell);
		this.setOperator(SWT.MAX | SWT.CLOSE);
		this.tenderProject = tenderProject;
		this.signatureSelftCommitment = signatureSelftCommitment;
		
	}

	/**
	 * Create contents of the dialog.
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		container = (Composite) super.createDialogArea(parent);
		GridLayout gl_container = new GridLayout(1, false);
		gl_container.marginHeight = 1;
		gl_container.marginWidth = 1;
		container.setLayout(gl_container);
		
		composite = new Composite(container, SWT.NONE);
		composite.setLayout(new FillLayout(SWT.HORIZONTAL));
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		signComposite = new Composite(container, SWT.NONE);
		signComposite.setLayout(new GridLayout(4, false));
		signComposite.setLayoutData(new GridData(SWT.CENTER, SWT.FILL, true, false, 1, 1));
		
		import_btn = new EButton(signComposite, SWT.NONE | EButton.CSS_BLUE);
		import_btn.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));
		import_btn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				importSignatureFileAction();
			}
		});
		GridData gd_handSignature_button_1 = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		gd_handSignature_button_1.heightHint = 30;
		import_btn.setLayoutData(gd_handSignature_button_1);
		import_btn.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
		import_btn.setText(MessageFormat.format(Messages.Button_importFormat, Messages.Button_evaluationCommitment));
		import_btn.setLeftMargin(15);
		import_btn.setRightMargin(15);
		import_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/white/import.png"));
		
		emport_btn = new EButton(signComposite, SWT.NONE | EButton.CSS_BLUE);
		emport_btn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				exportSignatureFileAction();
			}
		});
		GridData gd_button_1 = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		gd_button_1.heightHint = 30;
		emport_btn.setLayoutData(gd_button_1);
		emport_btn.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.BOLD));
		emport_btn.setText(MessageFormat.format(Messages.Button_exportFormat, Messages.Button_evaluationCommitment));
		emport_btn.setLeftMargin(15);
		emport_btn.setRightMargin(15);
		emport_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/white/export.png"));
		
		sign_btn = new EButton(signComposite, SWT.NONE | EButton.CSS_GREEN);
		sign_btn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				signFileAction();
			}
		});
		GridData gd_sign = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
		gd_sign.heightHint = 30;
		sign_btn.setLayoutData(gd_sign);
		sign_btn.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		sign_btn.setText(Messages.Button_toSignatureCommitment);
		sign_btn.setLeftMargin(15);
		sign_btn.setRightMargin(15);
		sign_btn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/white/pen.png"));
		
		EButton closeBtn = new EButton(signComposite, SWT.NONE | EButton.CSS_BLUE);
		closeBtn.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				close();
			}
		});
		GridData gd_close = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
		gd_close.heightHint = 30;
		closeBtn.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		closeBtn.setText(Messages.Button_close);
		closeBtn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/white/close.png"));
		closeBtn.setLeftMargin(15);
		closeBtn.setRightMargin(15);
		closeBtn.setLayoutData(gd_close);
		init();
		return container;
	}
	
	/**
	 * @Description: 初始化
	 * @author wangxiang 
	 */
	private void init(){
		loadMyCommitment();
		WidgetUtils.setControlVisible(import_btn, !signatureSelftCommitment);
	}
	
	private void loadMyCommitment() {
		documentFile = getMyCommitment();
		if(null != documentFile && documentFile.exists()) {
			sign_btn.setEnabled(true);
			import_btn.setEnabled(!documentFile.getName().endsWith("pdf"));
			emport_btn.setEnabled(true);
		}else {
			import_btn.setEnabled(true);
			emport_btn.setEnabled(false);
			sign_btn.setEnabled(false);
		}
		reLoadFile();
	}

	/**
	 * @Description: 获得我的承诺书
	 * @author guoyr
	 * @return 
	 */
	private File getMyCommitment() {
		File myCommentFile = null;
		final File myCommitmentDir = new File(FileConstants.getReportFilePath(tenderProject.getId()).concat(File.separator).concat("commitment"));
		if(myCommitmentDir.exists()) {
			File[] myCommentFiles = myCommitmentDir.listFiles();
			if(null != myCommentFiles) {
				for(File _myCommentFile : myCommentFiles) {
					if(_myCommentFile.isFile()) {
						if(_myCommentFile.getName().endsWith("pdf")) {
							if(signatureSelftCommitment) {
								if((_myCommentFile.getName().contains("承诺书") || _myCommentFile.getName().contains("ommitment")) && _myCommentFile.getName().contains(Constants.USER.getUserName())) {
									return _myCommentFile;
								}
							}else {
								if(_myCommentFile.getName().contains("承诺书") || _myCommentFile.getName().contains("ommitment")) {
									myCommentFile = _myCommentFile;
								}
							}
						}
					}
				}
			}
		}
		return myCommentFile;
	}
	
	
	private void signFileAction() {
		final Map<String, String> signaturePdfMap = SignaturePdfUtils.getSignaturePdfMap();
		
		if (signaturePdfMap.isEmpty()) {
			WidgetUtils.setControlVisible(sign_btn, false);
			return;
		}

		EMenu supplierOp = new EMenu(getShell());
		supplierOp.setForeground(ColorConstants.FONT_BLACK_COLOR);
		supplierOp.setFont(SWTResourceManager.getFont("微软雅黑", 12, SWT.NORMAL));
		supplierOp.setAutoClickOnlyOneItem(true);
		for (String signaturePdfKey : signaturePdfMap.keySet()) {
			if (SignaturePdfUtils.CA.equals(signaturePdfKey)) {
				supplierOp.addMenuItem(Messages.Button_caSignature, ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/signature.png"), true, new EMenu.ClickListener() {
					public void click() {
						signFileAction(Messages.Button_caSignature, signaturePdfKey, signaturePdfMap.get(signaturePdfKey));
					}
				});
			} else if (SignaturePdfUtils.HAND.equals(signaturePdfKey)) {
				supplierOp.addMenuItem(Messages.Button_handSignature, ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/pen.png"), true, new EMenu.ClickListener() {
					public void click() {
						signFileAction(Messages.Button_handSignature, signaturePdfKey, signaturePdfMap.get(signaturePdfKey));
					}
				});
			} else if (SignaturePdfUtils.SAOMA.equals(signaturePdfKey)) {
				supplierOp.addMenuItem(Messages.Button_scanSignatrue, ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/sweepCode.png"), true, new EMenu.ClickListener() {
					public void click() {
						signFileAction(Messages.Button_scanSignatrue, signaturePdfKey, signaturePdfMap.get(signaturePdfKey));
					}
				});
			}
		}
		supplierOp.open(sign_btn);
	}
	private void signFileAction(String title, String signatureType, String signaturePdfvalue) {
		if(!sign_btn.isEnabled()) {
			return;
		}
		if(signatureSelftCommitment) {
			// 如果没有我的承诺书的报表，则自己创建一份
			if(null == getMySignatureFile()) {
				if(null != documentFile && documentFile.exists()) {
					if(!documentFile.getName().endsWith("pdf")) {
						MessageDialog.openShortMessage(MessageFormat.format(Messages.Tips_importFileTypeFormat, "pdf"));
						return;
					}
					List<File> fileList = new ArrayList<File>();
					fileList.add(documentFile);
					List<AuthUser> userList = new ArrayList<AuthUser>();
					userList.add(Constants.USER);
					SignatureFileService signatureFileService = new SignatureFileService();
					signatureFileService.saveBatchSignatureFile(tenderProject.getId(),FileConstants.REPORT_FILE_FOLDER, fileList, userList).size();
				}
			}
		}
		close();
		CircleSignatureDialog signatureDialog = new CircleSignatureDialog(getShell(), tenderProject, Constants.USER, signatureType, signaturePdfvalue);
		signatureDialog.setTitle(title);
    	signatureDialog.open();
	}
	
	/**
	 * @Description: 获得流转签章中评标承诺书
	 * @author guoyr
	 * @return 
	 */
	private SignatureFile getMySignatureFile() {
		SignatureFileService signatureFileService = new SignatureFileService();
		List<SignatureFile> signatureFileList = signatureFileService.getSignatureFileList(tenderProject.getId(),FileConstants.REPORT_FILE_FOLDER);
		if(null != signatureFileList && signatureFileList.size() > 0) {
			for(SignatureFile signatureFile : signatureFileList) {
				if((signatureFile.getFileName().contains("承诺书") || signatureFile.getFileName().contains("ommitment"))) {
					if(signatureFile.getFileName().contains(Constants.USER.getUserName())) {
						return signatureFile;
					}
				}
			}
		}
		return null;
	}

	private void exportSignatureFileAction() {
		if(null != documentFile && documentFile.exists()) {
			
			final String selectDir = FileDialogUtils.getDirectorySavePath(Messages.Tips_selectExportDic, "");
			if (!StringUtils.isNotEmpty(selectDir)) {
				return;
			}
			File exportFile = new File(selectDir.concat(File.separator).concat(documentFile.getName()));
			if(FileUtils.copy(documentFile.getAbsolutePath(), exportFile.getAbsolutePath())){
				if (MessageDialog.openConfirm(getShell(), Messages.Button_openFile, Messages.Tips_exportAndOpenFile, new String[]{Messages.Button_open, Messages.Button_close})) {
					RuntimeUtils.openFIle(exportFile);
				}
			}
		}
	}

	private void importSignatureFileAction() {
		if(!import_btn.isEnabled()) {
			return;
		}
		String fileName = FileDialogUtils.getFileNames(SWT.SINGLE, MessageFormat.format(Messages.Title_select, Messages.Button_evaluationCommitment), new String[] { "*.pdf;*" });
		if (StringUtils.isEmpty(fileName)) {
			return;
		}else{
			final File myCommitmentDir = new File(FileConstants.getReportFilePath(tenderProject.getId()).concat(File.separator).concat("commitment"));
			String reportFilePath = myCommitmentDir.getAbsolutePath().concat(File.separator).concat(Messages.Button_evaluationCommitment+"_").concat(Constants.USER.getUserName()).concat(".pdf");
			FileUtils.copy(fileName, reportFilePath);
			File reportFilePathFile = new File(reportFilePath);
			if(reportFilePathFile.exists()) {
				loadMyCommitment();
			}
		}
	}

	
	/**
	 * @Description: 加载文件
	 * @author wangxiang 
	 */
	private void reLoadFile(){
		for(Control control : composite.getChildren()){
			control.dispose();
		}
		if(null != documentFile && documentFile.exists()) {
			String pdfType = PropertiesUtils.getProperty(ConfigConstants.PDF_ACTIVE_TYPE, DocumentFactory.DEFAULT_PDF_TYPE);
			documentLoader = DocumentFactory.getDocumentLoader(null != documentFile&& documentFile.exists()?documentFile.getAbsolutePath():null, pdfType);
			documentLoader.openDocument(composite,true);
		}
		composite.layout();
	}
	
	/**
	 * Return the initial size of the dialog.
	 */
	@Override
	protected Point getInitialSize() {
		Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); // 取得当前屏幕属性
		int w = d.width; // 获取屏幕宽度
		int h = d.height; // 获取屏幕高度
		return new Point((int)(w * (80.0 / 100)),(int)( h * 80.0 / 100));
//		return new Point(w, h);
	}

}
