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

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

import org.dom4j.Document;
import org.dom4j.Element;
import org.eclipse.nebula.widgets.grid.Grid;
import org.eclipse.nebula.widgets.grid.GridColumn;
import org.eclipse.nebula.widgets.grid.GridItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.core.MessageDialog;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;

import com.gx.obe.ColorConstants;
import com.gx.obe.business.entity.BidPriceRound;
import com.gx.obe.common.file.download.infer.FileDownloadListener.DOWN_STATUS;
import com.gx.obe.common.file.enumeration.FileConstants;
import com.gx.obe.common.file.http.HttpURLDownload;
import com.gx.obe.common.file.utils.ZipUtils;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.common.widget.thread.SyncRunnable;
import com.gx.obe.common.widget.thread.SyncThread;
import com.gx.obe.components.core.Constants;
import com.gx.obe.config.ConfigConstants;
import com.gx.obe.config.utils.PropertiesUtils;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.RuntimeUtils;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.util.utils.XmlUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.price.BidPriceRoundStatus;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.service.BidPriceRoundStatusService;
import com.gx.tools.ole.dianju.DianJuConstant;
import com.gx.tools.ole.jinge.JingeConstant;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/** 
 * @Description: 多轮报价折线图、详细
 * @author mazc 
 */
public class MultiBidPriceResultDetailComposite extends Composite {
	
	private BidPriceRoundStatusService bidPriceRoundStatusService = new BidPriceRoundStatusService();
	
//	private Composite supplierComposite;
	private TenderProjectEntity tenderProjectEntity;
	private Supplier supplier;
	private MultiBidPriceResultChartComposite multiBidPriceResultChartComposite;
	private Composite datailComposite;
	private Grid dataiGrid;
	private BidPriceRound curbidPriceRound;

	private SyncThread syncThread;
	private Composite composite;
	
 	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public MultiBidPriceResultDetailComposite(Composite parent, int style) {
		super(parent, style);
		setBackground(ColorConstants.BORDER_LINE_COLOR);
		GridLayout gridLayout = new GridLayout(2, false);
		gridLayout.horizontalSpacing = 1;
		gridLayout.marginHeight = 1;
		gridLayout.marginWidth = 1;
		gridLayout.verticalSpacing = 1;
		setLayout(gridLayout);
		
		addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent e) {
				if(null != syncThread) {
					syncThread.stop();
				}
			}
		});
		
		multiBidPriceResultChartComposite = new MultiBidPriceResultChartComposite(this, SWT.NONE);
		multiBidPriceResultChartComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		GridData gd_multiBidPriceResultChartComposite = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
		gd_multiBidPriceResultChartComposite.widthHint = 800;
		multiBidPriceResultChartComposite.setLayoutData(gd_multiBidPriceResultChartComposite);
		
		
		datailComposite = new Composite(this, SWT.NONE);
		datailComposite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		GridLayout gl_datailComposite = new GridLayout(1, false);
		gl_datailComposite.verticalSpacing = 0;
		gl_datailComposite.marginHeight = 0;
		gl_datailComposite.marginWidth = 0;
		datailComposite.setLayout(gl_datailComposite);
		GridData gd_datailComposite = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1);
		gd_datailComposite.widthHint = 200;
		datailComposite.setLayoutData(gd_datailComposite);
		
		dataiGrid = new Grid(datailComposite, SWT.H_SCROLL | SWT.V_SCROLL);
		dataiGrid.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		dataiGrid.addSelectionListener(new SelectionAdapter() {
			public void widgetDefaultSelected(SelectionEvent e) {
				GridItem[] items = dataiGrid.getSelection();
				doubleClickItem(items);
			}
		});
		dataiGrid.setHeaderVisible(true);
		dataiGrid.setAutoWidth(true);
		
		GridColumn gridColumn_1 = new GridColumn(dataiGrid, SWT.LEFT);
		gridColumn_1.setText(Messages.AboutAttachment);
		gridColumn_1.setWidth(200);
		
		composite = new Composite(datailComposite, SWT.NONE);
		composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		composite.setLayout(new GridLayout(1, false));
		composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		CLabel lblNewLabel = new CLabel(composite, SWT.NONE);
		lblNewLabel.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		lblNewLabel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/tips_blue.png"));
		lblNewLabel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1));
		lblNewLabel.setText("双击打开文件");
		lblNewLabel.setFont(SWTResourceManager.getFont("微软雅黑", 12, SWT.BOLD));
		lblNewLabel.setForeground(ColorConstants.SKIN_BG);
 	}

	/**
	 * @Description: 刷新
	 * @author guoyr
	 */
	public void refresh(TenderProjectEntity tenderProjectEntity, Supplier supplier, int maxRound, BidPriceRound curbidPriceRound, boolean showComplateOnly) {
		this.tenderProjectEntity = tenderProjectEntity;
		this.supplier = supplier;
		dataiGrid.setItemHeight(Constants.ROW_HIGHT);
		this.curbidPriceRound = curbidPriceRound;
		// 刷新报价的图标
		multiBidPriceResultChartComposite.setMaxAngleCount(5);
		multiBidPriceResultChartComposite.refresh(tenderProjectEntity, supplier, false, showComplateOnly,curbidPriceRound);
		loadDatailGrid();
	}
	
	/**
	 * 加载报价明细附件
	 */
	private void  loadDatailGrid(){
		dataiGrid.removeAll();
		//C:\bidFile\7bc4ad9f86af4a578f737dfcc332dcf9\reBidPrice\13\91110108MA006QXT8E
		//c:\bidFile\7bc4ad9f86af4a578f737dfcc332dcf9\reBidPrice\14\91110108MA006QXT8E\BidFileIndex.xml
		
		String roundPath = FileConstants.getReBidPriceFilePath(tenderProjectEntity.getId()).concat(curbidPriceRound.getRoundNo()+"").concat(File.separator).concat(supplier.getOrgCode()).concat(File.separator);
		
		String bidPriceIndexXmlPath = roundPath.concat(FileConstants.BID_FILE_INDEX_XML);
		File xmlFile = new File(bidPriceIndexXmlPath);
		if (xmlFile.exists() && xmlFile.isFile()) {
			Document document = XmlUtils.getXmlDocument(bidPriceIndexXmlPath);
			if (null != document) {
				Element rootElement = document.getRootElement();
				List<?> objectList = rootElement.elements("fileItem");
				if (null != objectList && objectList.size() > 0) {
					for (Object object : objectList) {
						Element fileItem = (Element) object;
						String fileId = fileItem.elementTextTrim("fileId");
						String fileName = fileItem.elementTextTrim("fileName");
						String endStr = fileName.substring(fileName.lastIndexOf(".") + 1);
						GridItem gridItem = new GridItem(dataiGrid, SWT.LEFT);
						gridItem.setText(0, fileName);
						gridItem.setData("file", roundPath.concat(fileId).concat("."+endStr));
					}
				}
			}
		} else {
			GridItem gridItem = new GridItem(dataiGrid, SWT.LEFT);
			gridItem.setText(0, "正在同步附件中......");
			downloadMultiBidPriceFile(roundPath);
		}
		
		datailComposite.layout();
	}
	

	
	/**
	 * @Description: 启动下载线程
	 * @author chenxw 
	 */
	private void downloadMultiBidPriceFile(String roundPath) {
		if (syncThread != null) {
			syncThread.stop();
		}
		syncThread = new SyncThread(new SyncRunnable(dataiGrid) {
			boolean downFlag = false;
			
			public void threadRun() {
				BidPriceRoundStatus bidPriceRoundStatus = bidPriceRoundStatusService.getBidPriceRoundStatus(curbidPriceRound.getId(), supplier.getId());
				if (bidPriceRoundStatus == null) return;
				String bidPriceFileUrl = bidPriceRoundStatus.getBidPriceFileUrl();
				if (StringUtils.isEmpty(bidPriceFileUrl)) return;
				String bidPriceFileName = bidPriceRoundStatus.getBidPriceFileName();
				if (StringUtils.isEmpty(bidPriceFileName)) return;
				File downFile = new File(roundPath.concat(bidPriceFileName));
				
				if (multiBidPriceFileDownload(bidPriceFileUrl, 0, downFile.getAbsolutePath())) {
					downFlag = ZipUtils.unZipFile(downFile.getAbsolutePath(), downFile.getParent());
				}
			}
			
			public void asyncExec() {
				if (downFlag) {
					loadDatailGrid();
				} else {
					dataiGrid.removeAll();
				}
			}
		});
		syncThread.showMessage(Messages.Tips_loading);
		syncThread.start();
	}

	/**
	 * @Description: 下载多轮报价文件
	 * @author chenxw
	 * @param urlPath
	 * @param saveFile
	 * @return 
	 */
	private boolean multiBidPriceFileDownload(String urlPath, long fileSize, String saveFile) {
		HttpURLDownload download = new HttpURLDownload(urlPath, fileSize, saveFile, null) {
			public DOWN_STATUS downloadStatus() {
				return syncThread.finish ? DOWN_STATUS.CANCEL : null;
			}
		};
		download.setMessageStartName("多轮报价文件");
		return download.downLoad();
	}

	/**
	 * @Description: 双击打开文件
	 * @param items 
	 * @author wangxiang
	 */
	private void doubleClickItem(GridItem[] items) {
		if(null != items && items.length > 0){
			String fileName = (String) items[0].getData("file");
			if (fileName == null) {
				return;
			}
			final File bidFile = new File(fileName);
			if (!bidFile.exists() || bidFile.isDirectory() ) {
				MessageDialog.openShortMessage("文件不存在");
				return;
			} else {
				openFile(bidFile);
			}
		}
	}
	
	/**
	 * @Description:双击打开文件 
	 * @author wangxiang
	 * @param file 
	 */
	public void openFile(File file) {
		if (file.getName().endsWith(".pdf")) {
			String pdfExe = "explorer.exe";
			String signaturePdf = PropertiesUtils.getProperty(ConfigConstants.PDF_ACTIVE_TYPE, "");
			if (signaturePdf.equals(DianJuConstant.PDF_TYPE)) {
				pdfExe = DianJuConstant.EXE;
			} else if (signaturePdf.equals(JingeConstant.PDF_TYPE)) {
				pdfExe = JingeConstant.EXE;
			}
			RuntimeUtils.openFIle(file, pdfExe);
		} else {
			RuntimeUtils.openFIle(file);
		}
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
}
