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

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.swtchart.Chart;
import org.swtchart.IAxis;
import org.swtchart.IAxisSet;
import org.swtchart.IAxisTick;
import org.swtchart.ILineSeries;
import org.swtchart.ISeries.SeriesType;

import com.gx.obe.business.entity.BidPriceRound;
import com.gx.obe.common.widget.utils.ColorUtils;
import com.gx.obe.components.core.enumeration.BidPriceEnum;
import com.gx.obe.message.Messages;
import com.gx.obe.util.utils.NumericChineseUtils;
import com.gx.obe.util.utils.ObjectUtils;
import com.gx.obe.util.utils.StringUtils;
import com.gx.obe.web.entity.Supplier;
import com.gx.obe.web.entity.price.BidPriceHisResult;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.service.BidPriceHisResultService;
import com.gx.obe.web.service.BidPriceRoundStatusService;
import com.gx.obe.web.service.ReBidPriceRoundService;
import com.swtdesigner.SWTResourceManager;

public class MultiBidPriceResultChartComposite extends Composite {
//	private Composite supplierComposite;
	private TenderProjectEntity tenderProjectEntity;
	private ReBidPriceRoundService reBidPriceRoundService;
	private Supplier supplier;
	private Chart chart;
	private int maxAngleCount = 5;// X轴显示的角度
	private boolean showComplateOnly = true;
	private BidPriceHisResultService bidPriceHisResultService;
	private BidPriceRound curbidPriceRound;
	private BidPriceRoundStatusService bidPriceRoundStatusService;
 	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public MultiBidPriceResultChartComposite(Composite parent, int style) {
		super(parent, style);
		GridLayout gridLayout = new GridLayout(2, false);
		gridLayout.horizontalSpacing = 0;
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 0;
		gridLayout.verticalSpacing = 0;
		setLayout(gridLayout);
		chart = new Chart(this, SWT.NONE);
		chart.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		chart.getTitle().setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		bidPriceHisResultService = new BidPriceHisResultService();
		reBidPriceRoundService = new ReBidPriceRoundService();
		bidPriceRoundStatusService = new BidPriceRoundStatusService();
	}

	/**
	 * @Description: 刷新
	 * @author guoyr
	 */
	public void refresh(TenderProjectEntity tenderProjectEntity, Supplier supplier, boolean legendTop, boolean showComplateOnly,BidPriceRound curbidPriceRound) {
		this.tenderProjectEntity = tenderProjectEntity;
		this.supplier = supplier;
		this.showComplateOnly = showComplateOnly;
		this.curbidPriceRound = curbidPriceRound;
		if(null == supplier){
			return;
		}
		if(legendTop){
			chart.getLegend().setPosition(SWT.TOP);
		}
		chart.getTitle().setText(supplier.getSupplierName());
		refreshBidPriceChart();
	}
	

	/**
	 * @Description: 设置 X轴显示的角度最大数
	 * @author guoyr
	 * @param maxAngleCount 
	 */
	public void setMaxAngleCount(int maxAngleCount){
		this.maxAngleCount = maxAngleCount;
		
	}
	/**
	 * @Description: 刷新报价的图标
	 * @author wangxiang
	 */
	private void refreshBidPriceChart() {
//		List<BidPrice> bidPriceList = bidPriceService.getTenderBidPriceList(tenderProjectEntity.getId());
//		if(null == bidPriceList || bidPriceList.size() == 0){
//			bidPriceList = new ArrayList<BidPrice>();
//		}
		List<BidPriceRound> bidPriceRoundList = reBidPriceRoundService.getBidPriceRoundList(tenderProjectEntity.getId());
		if(null == bidPriceRoundList || bidPriceRoundList.size() == 0){
			BidPriceRound lastBidPriceRound = new BidPriceRound();
			lastBidPriceRound.setRoundName(Messages.OriginalBidPrice);
			lastBidPriceRound.setRoundNo(0);
			bidPriceRoundList.add(lastBidPriceRound);
		}
		final IAxis xAxis = chart.getAxisSet().getXAxis(0);
		final IAxis yAxis = chart.getAxisSet().getYAxis(0);
		DecimalFormat dataFormat = new DecimalFormat("###,##0.00####");
		yAxis.getTick().setFormat(dataFormat);
		int axisId = yAxis.getId();
		xAxis.getTitle().setText("轮次");
		xAxis.getTitle().setVisible(false);
		xAxis.getTitle().setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		xAxis.enableCategory(true);
		yAxis.getTick().setTickMarkStepHint(5);
		yAxis.getTitle().setText(Messages.QuotedPrice);
		yAxis.getTitle().setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		
		List<BidPriceHisResult> lastBidPriceResultList= bidPriceHisResultService.getSupplierBidPriceHisResultListByRound(tenderProjectEntity.getId(), supplier.getId(),curbidPriceRound.getRoundNo()) ;
		int bidPriceCount = 0;
		if(null != lastBidPriceResultList && lastBidPriceResultList.size() > 0){
			for(BidPriceHisResult bidPriceHisResult : lastBidPriceResultList){
				if(BidPriceEnum.IS_PRICE_ITEM.equals(bidPriceHisResult.getBidPriceType())){
					bidPriceCount ++;
				}
			}
		}
		List<String> bidpriceRoundNameList = new ArrayList<String>();
		BigDecimal lowPrice =  null;
		BigDecimal hightPrice = null;
		String priceUnit = null;
		// 只显示全部完成的报价，只判断最后一轮报价
		if(showComplateOnly && bidPriceRoundList.size() > 1){
			BidPriceRoundStatusService BidPriceRoundStatusService = new BidPriceRoundStatusService();
			if(!BidPriceRoundStatusService.isCompletePrice(curbidPriceRound.getId())){
				bidPriceRoundList.remove(bidPriceRoundList.size() -1);
			}
		};
		// key  value 线
		Map<String, ILineSeries> bidPriceLineSeries = new HashMap<String, ILineSeries>();
		// key  value {线的点数}
		Map<String, List<Double>> lineSeriesValues = new HashMap<String, List<Double>>();
		
		int index = 1;
		
		//所有轮次
		for(BidPriceRound bidPriceRound : bidPriceRoundList){
			List<BidPriceHisResult> bidPriceResultList= null;
			if(bidPriceRound.getRoundNo() == bidPriceRoundList.size()){
//				bidPriceResultList= lastBidPriceResultList;
				if(!valSupplierComplateBidPrice(bidPriceRound.getId())){
					continue;
				}
			}
 			bidPriceResultList= bidPriceHisResultService.getSupplierBidPriceHisResultListByRound(tenderProjectEntity.getId(), supplier.getId(), bidPriceRound.getRoundNo()) ;
			
			
			if(null != bidPriceResultList && bidPriceResultList.size() > 0){
				
				if (index == 1) {
//					bidpriceRoundNameList.add(bidPriceRound.getRoundName());
					bidpriceRoundNameList.add(Messages.OriginalBidPrice);
				} else {
					bidpriceRoundNameList.add("第".concat(NumericChineseUtils.getChinese(index)).concat("次报价"));
				}
				index++;
				int priceIndex = 0;
				for(BidPriceHisResult bidPriceHisResult : bidPriceResultList){
					if(BidPriceEnum.IS_PRICE_ITEM.equals(bidPriceHisResult.getBidPriceType())&& StringUtils.hasLength(bidPriceHisResult.getBidPriceName())){
						ILineSeries lineSeries = bidPriceLineSeries.get(bidPriceHisResult.getBidPriceId());
						if(null == lineSeries){
							String bidPriceName = null != bidPriceHisResult.getBidPriceName() ? bidPriceHisResult.getBidPriceName() : "投标报价";
							lineSeries = (ILineSeries) chart.getSeriesSet().createSeries(SeriesType.LINE, ObjectUtils.getObjString(bidPriceName));
							lineSeries.setDescription(ObjectUtils.getObjString(bidPriceHisResult.getBidPriceName()));
							Color color = ColorUtils.getRandomColor(priceIndex ++, bidPriceCount);
							lineSeries.setLineColor(color);// 设置线颜色
							lineSeries.setSymbolColor(color);// 设置值点颜色
							lineSeries.setSymbolSize(3);
							lineSeries.setLineWidth(1);
							lineSeries.getLabel().setVisible(true);
							lineSeries.getLabel().setFormat("###,##0.00####");
							lineSeries.setAntialias(SWT.ON);// 消除锯齿 当数据量特别大时，不适用
							// 设置最是否显示区域
							lineSeries.enableArea(true);
							bidPriceLineSeries.put(bidPriceHisResult.getBidPriceId(), lineSeries);
						}
						
						if(null != bidPriceHisResult.getPriceUnit()){
							priceUnit = bidPriceHisResult.getPriceUnit() + (null != bidPriceHisResult.getCurrencyName() ? "("+bidPriceHisResult.getCurrencyName()+")" : "");
							
						}
						BigDecimal bidPriceValue = null != bidPriceHisResult.getBidPrice()? bidPriceHisResult.getBidPriceByUnit(null) : BigDecimal.ZERO;
						if(null == lowPrice){
							lowPrice = bidPriceValue;
							hightPrice = bidPriceValue;
						}else {
							if (bidPriceValue.compareTo(lowPrice) < 0) {
								lowPrice = bidPriceValue;
							}
							if (bidPriceValue.compareTo(hightPrice) > 0) {
								hightPrice = bidPriceValue;
							}
						}
						List<Double> lineSeriesValue = lineSeriesValues.get(bidPriceHisResult.getBidPriceId());
						if(null == lineSeriesValue){
							lineSeriesValue = new ArrayList<Double>();
							lineSeriesValues.put(bidPriceHisResult.getBidPriceId(), lineSeriesValue);
						}
						lineSeriesValue.add(bidPriceValue.doubleValue());
					}
				}
			}else {
//				ILineSeries lineSeries = bidPriceLineSeries.get(BidPriceEnum.IS_PRICE_ITEM);
//				if(null == lineSeries) {
//					lineSeries = (ILineSeries) chart.getSeriesSet().createSeries(SeriesType.LINE, "");
//					lineSeries.setDescription("");
//					Color color = ColorUtils.getRandomColor(1 , bidPriceCount);
//					lineSeries.setLineColor(color);// 设置线颜色
//					lineSeries.setSymbolColor(color);// 设置值点颜色
//					lineSeries.setSymbolSize(3);
//					lineSeries.setLineWidth(1);
//					lineSeries.getLabel().setVisible(true);
//					lineSeries.getLabel().setFormat("###,##0.00####");
//					lineSeries.setAntialias(SWT.ON);// 消除锯齿 当数据量特别大时，不适用
//					// 设置最是否显示区域
//					lineSeries.enableArea(true);
// 
//					bidPriceLineSeries.put(BidPriceEnum.IS_PRICE_ITEM, lineSeries);
//				}
//				List<Double> lineSeriesValue = lineSeriesValues.get(BidPriceEnum.IS_PRICE_ITEM);
//				if(null == lineSeriesValue){
//					lineSeriesValue = new ArrayList<Double>();
//					lineSeriesValues.put(BidPriceEnum.IS_PRICE_ITEM, lineSeriesValue);
//				}
//				lineSeriesValue.add(new Double(0));
			}
		}
		for (IAxis axis : chart.getAxisSet().getYAxes()) {
//			axis.zoomOut(hightPrice.doubleValue() -badspace.doubleValue());
			axis.zoomOut();
		}
		int lineCount = 0;
		for(Entry<String, ILineSeries> lineSeriesEntry : bidPriceLineSeries.entrySet()){
			ILineSeries lineSeries = lineSeriesEntry.getValue();
			List<Double> lineSeriesValue = lineSeriesValues.get(lineSeriesEntry.getKey());
			if(null != hightPrice && null != lowPrice) {
				lineSeriesValue.add(lowPrice.doubleValue() - (hightPrice.doubleValue() - lowPrice.doubleValue()) * 0.1);
				lineSeriesValue.add(hightPrice.doubleValue() + (hightPrice.doubleValue() - lowPrice.doubleValue()) * 0.1);
			}
			double[] ySeries = new double[lineSeriesValue.size()];
			for(int i = 0; i < lineSeriesValue.size(); i++){
				ySeries[i] = lineSeriesValue.get(i);
			}
			lineSeries.setYSeries(ySeries);
			lineSeries.setYAxisId(axisId);
			lineCount++;
		}
		if(lineCount < 2){
			chart.getLegend().setVisible(false);
		}
		// 当超过最大报价轮次数后为保证名称能显示完整 ，则采用一定的倾斜角度
		if(bidpriceRoundNameList.size() > maxAngleCount){
			xAxis.getTick().setTickLabelAngle(30);
		} else {
			xAxis.getTick().setTickLabelAngle(0);
		}
		chart.getAxisSet().getXAxis(0).setCategorySeries(bidpriceRoundNameList.toArray(new String[bidpriceRoundNameList.size()]));
 		yAxis.getTitle().setText(null != priceUnit ? priceUnit : Messages.QuotedPrice);
		chart.getAxisSet().adjustRange();
		IAxisSet axisSet = chart.getAxisSet();
		IAxisTick yTick = axisSet.getYAxis(0).getTick();
		yTick.setFormat(new DecimalFormat("#,##0.00####"));
		yTick.setTickMarkStepHint(30);
		chart.redraw();
		chart.getPlotArea().setFocus();
	}
	
	/**
	 * @Description: 验证是否全部完成报价
	 * @author guoyr
	 * @return 
	 */
	private boolean valSupplierComplateBidPrice(String roundId){
		// 这里判断最新轮次供应商有没有全部完成报价并进行提示
	 return bidPriceRoundStatusService.isCompletePrice(roundId);
	}

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