package com.gx.obe.management.dialog;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.core.ImageResolver;
import org.eclipse.swt.core.utils.FileDialogUtils;
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.custom.CLabel;
import org.eclipse.swt.custom.StackLayout;
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.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.gx.obe.common.file.enumeration.FileConstants;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.config.ConfigConstants;
import com.gx.obe.config.utils.PropertiesUtils;
import com.gx.obe.util.utils.FileUtils;
import com.gx.obe.util.utils.LogUtils;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.web.entity.BidOpeningRoom;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.entity.tender.TenderProjectRuleEntity;
import com.gx.obe.web.service.BidOpeningRoomService;
import com.gx.obe.web.service.ProjectRuleService;
import com.gx.obe.web.service.TenderProjectService;
import com.gx.tools.ole.DocumentFactory;
import com.gx.tools.ole.DocumentLoader;
import com.gx.tools.tts.ITTS;
import com.gx.tools.tts.TTSEnginUtil;
import com.gx.utils.PdfPoiUtil;
import com.gx.utils.WordPoiUtil;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/**
 * @Description: 
 * @author guoyr
 */
public class ShowEvalDisciplineDialog extends EDialog {
	private TenderProjectEntity tenderProjectEntity;
	private TenderProjectRuleEntity tenderProjectRuleEntity;
	private ImageResolver imageResolver = new ImageResolver();
	public boolean isDisabled = false;
	private TenderProjectService tenderProjectService ;
	private ProjectRuleService projectRuleService ;
 	private ELabel projectNameLabel;
	private ELabel packageNameLabel;
	private Composite openPlanComposite;
	private Composite noOpenPlanComposite;
	private Composite openPlanContentComposite;
	private StackLayout openPlanStaticLayout;
	private Text text_1;
	private ITTS tts;
	private Logger LOG = Logger.getLogger(ShowEvalDisciplineDialog.class);
	private String openPlanContent = null;
	private ELabel speakBtn;
	private ELabel stopSpeekLabel;
	private boolean isSpeakTTS;
	private BidOpeningRoomService bidOpeningRoomService ;
	{
		LogUtils.logClass(ShowEvalDisciplineDialog.class);
	}
	
	/**
	 * Create the dialog.
	 * @param parentShell
	 */
	public ShowEvalDisciplineDialog(Shell parentShell, TenderProjectEntity tenderProjectEntity, TenderProjectRuleEntity tenderProjectRuleEntity) {
		super(parentShell);
		this.setTitle("评标纪律、承诺书");
		this.setOperator(SWT.MAX | SWT.CLOSE);
		this.tenderProjectEntity = tenderProjectEntity;
		if(null == tenderProjectRuleEntity){
			tenderProjectRuleEntity = new TenderProjectRuleEntity();
		}
		this.tenderProjectRuleEntity = tenderProjectRuleEntity;
	}

	/**
	 * 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.marginHeight = 0;
		gl_container.marginWidth = 0;
		gl_container.horizontalSpacing = 0;
		container.setLayout(gl_container);
		container.addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent e) {
				imageResolver.disposite();
				isDisabled = true;
				if(null != tts){
					tts.stop();
				}
			}
		});
		
		Composite composite_9 = new Composite(container, SWT.NONE);
		composite_9.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
		composite_9.setLayout(new GridLayout(4, false));
		
		Composite composite_4 = new Composite(composite_9, SWT.NONE);
		composite_4.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1));
		RowLayout rl_composite_4 = new RowLayout(SWT.HORIZONTAL);
		rl_composite_4.marginWidth = 10;
		rl_composite_4.marginHeight = 15;
		composite_4.setLayout(rl_composite_4);
		
		projectNameLabel = new ELabel(composite_4, SWT.WRAP);
		projectNameLabel.setFont(SWTResourceManager.getFont("宋体", 15, SWT.BOLD));
		projectNameLabel.setText("二○一二年国家基础航空航天遥感影像获取项目（二期）");
		
		Composite composite_5 = new Composite(composite_4, SWT.NONE);
		GridLayout gl_composite_5 = new GridLayout(2, false);
		gl_composite_5.horizontalSpacing = 0;
		gl_composite_5.marginHeight = 0;
		gl_composite_5.marginWidth = 0;
		composite_5.setLayout(gl_composite_5);
		
		Label label_11 = new Label(composite_5, SWT.SEPARATOR | SWT.HORIZONTAL);
		GridData gd_label_11 = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		gd_label_11.widthHint = 30;
		label_11.setLayoutData(gd_label_11);
		
		packageNameLabel = new ELabel(composite_5, SWT.WRAP);
		packageNameLabel.setFont(SWTResourceManager.getFont("宋体", 12, SWT.NORMAL));
		packageNameLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		packageNameLabel.setText("二○一二年国家基础航空航天遥感影像获取项目（A标段）");
		
		CLabel label = new CLabel(composite_9, SWT.NONE);
		label.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				uploadReviewDisciplineFileAction();
			}
		});
		label.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		label.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/upload.png"));
		label.setText("");
		
		speakBtn = new ELabel(composite_9, SWT.NONE | SWT.SELECTED);
		speakBtn.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		speakBtn.setTopMargin(0);
		speakBtn.setBottomMargin(0);
		speakBtn.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/sound_24 .png"));
		speakBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				speakTTSAction();
			}
		});
		speakBtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		speakBtn.setText("");
		
		stopSpeekLabel = new ELabel(composite_9, SWT.NONE | SWT.SELECTED);
		stopSpeekLabel.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
		stopSpeekLabel.setBottomMargin(0);
		stopSpeekLabel.setTopMargin(0);
		stopSpeekLabel.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				stopTTS();
			}
		});
		stopSpeekLabel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/dis_sound_24.png"));
		stopSpeekLabel.setText("");
		
		Label label_1 = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
		label_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		
		openPlanComposite = new Composite(container, SWT.NONE);
		openPlanComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		openPlanComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		openPlanStaticLayout = new StackLayout();
		openPlanComposite.setLayout(openPlanStaticLayout);
		
		noOpenPlanComposite = new Composite(openPlanComposite, SWT.NONE);
		noOpenPlanComposite.setLayout(new GridLayout(1, false));
		
		CLabel label_3 = new CLabel(noOpenPlanComposite, SWT.NONE);
		label_3.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
		label_3.setFont(SWTResourceManager.getFont("宋体", 15, SWT.NORMAL));
		label_3.setLayoutData(new GridData(SWT.CENTER, SWT.BOTTOM, true, true, 1, 1));
		label_3.setText("未找到评标纪律、承诺书！");
		
		Composite composite_1 = new Composite(noOpenPlanComposite, SWT.NONE);
		composite_1.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, true, 1, 1));
		composite_1.setLayout(new GridLayout(2, false));
		
		text_1 = new Text(composite_1, SWT.BORDER);
		GridData gd_text_1 = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		gd_text_1.widthHint = 246;
		text_1.setLayoutData(gd_text_1);
		
		EButton button = new EButton(composite_1, SWT.NONE);
		button.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				uploadReviewDisciplineFileAction();
			}
		});
		button.setText("导入评标纪律、承诺书");
		button.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/btn/blue/search.png"));
		
		openPlanContentComposite = new Composite(openPlanComposite, SWT.NONE);
		openPlanContentComposite.setLayout(new FillLayout(SWT.HORIZONTAL));
		init();
		return container;
	}

	/**
	 * @Description: 初始化
	 * @author guoyr
	 */
	private void init(){
		projectRuleService = new ProjectRuleService();
		tenderProjectService = new TenderProjectService();
		this.setShellStyle(SWT.CLOSE);
		Thread thread = new Thread(){
			public void run(){	
				tenderProjectEntity = (TenderProjectEntity) tenderProjectService.getById(tenderProjectEntity.getId());
				tenderProjectRuleEntity = projectRuleService.getProjectRule(tenderProjectEntity.getId());
				if(null == tenderProjectRuleEntity){tenderProjectRuleEntity = new TenderProjectRuleEntity();}
				BidOpeningRoom bidOpeningRoom = bidOpeningRoomService.getBidOpeningRoomById(tenderProjectEntity.getBidOpeningRoomId());
				if(null == bidOpeningRoom){bidOpeningRoom = new BidOpeningRoom();}
		//		tenderProjectRuleEntity.setOpenBidStartTime(DateTimeUtil.add(NowDateUtil.getNowDate(), DateTimeUtil.SECOND, 10));
				if(StringUtils.isNotEmpty(tenderProjectEntity.getParentId())){
					TenderProjectEntity parent = (TenderProjectEntity) tenderProjectService.getById(tenderProjectEntity.getParentId());
					if(null != parent){
						projectNameLabel.setText("["+parent.getTenderNo()+"]"+parent.getTenderName());
					}
					packageNameLabel.setText("["+tenderProjectEntity.getTenderNo()+"]"+tenderProjectEntity.getTenderName());
				}else {
					projectNameLabel.setText("["+tenderProjectEntity.getTenderNo()+"]"+tenderProjectEntity.getTenderName());
					packageNameLabel.getParent().dispose();
				}
				File openPlanFile = getReviewDisciplineFile();
				if(null != openPlanFile){
					loadOpenPlanAction(openPlanFile);
				}else {
					openPlanStaticLayout.topControl = noOpenPlanComposite;
				}
			}
		};
		thread.start();
		try {
			thread.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @Description: 加载评标纪律、承诺书
	 * @author guoyr
	 */
	private void loadOpenPlanAction(final File openPlanFile){
		for(Control control : openPlanContentComposite.getChildren()){
			control.dispose();
		}
		speakBtn.setEnabled(false);
		stopSpeekLabel.setEnabled(false);
		openPlanStaticLayout.topControl = openPlanContentComposite;
		DocumentLoader documentLoader = DocumentFactory.getDocumentLoader(openPlanFile.getAbsolutePath(), PropertiesUtils.getProperty(ConfigConstants.PDF_ACTIVE_TYPE, DocumentFactory.DEFAULT_PDF_TYPE));
		documentLoader.setShowMenu(false);
		documentLoader.openDocument(openPlanContentComposite, true, false, false, false, false);
		documentLoader.activate();
		openPlanComposite.layout();
		
		// 如果上传时已经在播放，则先停止
		if(isSpeakTTS){
			stopSpeekLabel.notifyListeners(SWT.MouseUp, null);
		}
		new Thread(new Runnable(){
			public void run(){
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
				String fileType = openPlanFile.getName().substring(openPlanFile.getName().lastIndexOf(".")).toLowerCase();
				if(fileType.startsWith(".doc")){
					openPlanContent = WordPoiUtil.getText(openPlanFile.getAbsolutePath());
				}else if(fileType.startsWith(".pdf")){
					openPlanContent = PdfPoiUtil.getText(openPlanFile.getAbsolutePath());
				}
				Display.getDefault().syncExec(new Runnable(){
					public void run(){
						if(!speakBtn.isDisposed()){
							// 默认开始语音
							speakBtn.notifyListeners(SWT.MouseUp, null);
						}
					}
				});
			}
		}).start();
	}
	
	/**
	 * @Description: 启动语音
	 * @author guoyr
	 */
	private void speakTTSAction(){
		if(null == tts){
			tts = TTSEnginUtil.getTTSEngin();
		}
		if(null != tts && null != openPlanContent && openPlanContent.length() > 0){
			speakBtn.setEnabled(true);
		}else {
			speakBtn.setEnabled(false);
			stopSpeekLabel.setEnabled(false);
		}
		if(!speakBtn.getEnabled()){
			return ;
		}
		isSpeakTTS = true;
		stopSpeekLabel.setEnabled(true);
		tts.speak(openPlanContent);
	}

	/**
	 * @Description: 停止语音
	 * @author guoyr
	 */
	private void stopTTS(){
		isSpeakTTS = false;
		stopSpeekLabel.setEnabled(false);
		if(null != tts){
			tts.stop();
		}
	}
	
	/**
	 * @Description: 上传评标纪律
	 * @author guoyr
	 */
	private void uploadReviewDisciplineFileAction(){
		
		File openPlanFile = getReviewDisciplineFile();
		if(null != openPlanFile){
			openPlanFile.delete();
		}
		FileDialog fileDialog = new FileDialog(getShell(), SWT.OPEN|SWT.SINGLE);
		fileDialog.setText("请选择评标纪律、承诺书");
		fileDialog.setFilterPath("SystemDrive");  
		fileDialog.setFilterExtensions(new String[] {"*.doc;*.docx;*.pdf"});
		fileDialog.setFilterNames(new String[] {"所有评标纪律、承诺书(*.doc;*.docx;*.pdf)"});
		fileDialog.open();
		
		if(fileDialog.getFileNames().length > 0 ){
			String openPlanFilePath = FileConstants.getBiddingFilePath(tenderProjectEntity.getId());
			text_1.setText(FileDialogUtils.getTransfFilePath(fileDialog.getFilterPath(), fileDialog.getFileNames()));
			openPlanFile = new File(text_1.getText());
			if(null != openPlanFile && openPlanFile.exists()){
				try {
					if(FileUtils.copyOrCreateFiles(openPlanFile.getAbsolutePath(),openPlanFilePath)){
						if(!openPlanFile.getName().startsWith(FileConstants.EVAL_DISCIPLINE)){
							File newOpenPlanFile =  new File(openPlanFilePath + FileConstants.EVAL_DISCIPLINE + openPlanFile.getName().substring(openPlanFile.getName().lastIndexOf(".")));
							FileUtils.rename(openPlanFilePath+openPlanFile.getName(), newOpenPlanFile.getAbsolutePath());
							loadOpenPlanAction(newOpenPlanFile);
						}
					}
					
				} catch (Exception e) {
					LOG.error("", e);
				}
			}
			
		}
	}
	
	/**
	 * @Description: 获得评标纪律文件
	 * @author guoyr
	 * @return
	 */
	private File getReviewDisciplineFile(){
		String openPlanFilePath = FileConstants.getBiddingFilePath(tenderProjectEntity.getId());
		String[] openPlanFileType = new String[]{".doc",".docx",".pdf"};
		File openPlanFile = null;
		for(String fileEndWidth : openPlanFileType){
			openPlanFile = new File(openPlanFilePath + FileConstants.EVAL_DISCIPLINE + fileEndWidth);
			if(null != openPlanFile && openPlanFile.exists()){
				return openPlanFile;
			}
		}
		
		String reviewDisciplineFilePath = FileConstants.PRODUCT_ROOT + File.separator + FileConstants.RESOURCE_FOLDER + File.separator + FileConstants.REVIEW_DISCIPLINE_FILE;
		if(new File(reviewDisciplineFilePath+FileConstants.DOC).exists()){
			return new File(reviewDisciplineFilePath+FileConstants.DOC);
		}else if(new File(reviewDisciplineFilePath+FileConstants.DOCX).exists()){
			return new File(reviewDisciplineFilePath+FileConstants.DOCX);
		}else if(new File(reviewDisciplineFilePath+FileConstants.PDF).exists()){
			return new File(reviewDisciplineFilePath+FileConstants.PDF);
		}
		return null;
	}

	/**
	 * 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(w, h);
//		return new Point(w -100, h -100);
	}
}
