package yem.wmc.ca.chart;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.EventObject;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.nacos.api.utils.StringUtils;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.form.chart.Axis;
import kd.bos.form.chart.AxisType;
import kd.bos.form.chart.BarSeries;
import kd.bos.form.chart.HistogramChart;
import kd.bos.form.control.Button;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.events.RowClickEvent;
import kd.bos.form.control.events.RowClickEventListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
@SuppressWarnings("unchecked")
/**
 * 月度出口额同比统计柱状图
 * @author zlp
 *
 */
public class AmountOfExports extends AbstractFormPlugin implements RowClickEventListener {

	private final static String start_key = "yem_starttime";
	private final static String end_key = "yem_endtime";
	private final static String button_key  = "yem_select";
	//存储cif等三个数据
	private static Map<String,BigDecimal>[] cifMaps = null;
	private static Map<String,BigDecimal>[] fobMaps = null;
	private static Map<String,BigDecimal>[] exwMaps = null;
	private static int endYear = 0;
	private static int startYear = 1;
	private DecimalFormat df = new DecimalFormat("#,##0.00");
	private final static String[] xStr = new String[] {"01月","02月","03月","04月","05月","06月","07月","08月","09月","10月","11月","12月"};
	//记录之前显示过的所有 series名称
	private static Set<String> legendName = new HashSet<String>();
	@Override
	public void registerListener(EventObject e) {
		Button textEdit = this.getControl(button_key);
		EntryGrid  entryGrid = this.getControl("yem_entryentity");
		if(textEdit != null) {
			textEdit.addClickListener(this);
		}
		if(entryGrid != null) {
			entryGrid.addRowClickListener(this);
		}

	}

	@Override
	public void afterCreateNewData(EventObject e) {

		Control control = this.getControl("yem_histogramchartap");
		if(control instanceof HistogramChart) {
			HistogramChart barChart = (HistogramChart) control;

			Calendar cal = Calendar.getInstance();
			Date nowDate = new Date();
			cal.setTime(nowDate);
			endYear = cal.get(Calendar.YEAR);
			startYear = endYear-1;
			int yearDiffer = endYear- startYear;
			cifMaps = new Map[yearDiffer+1];
			fobMaps = new Map[yearDiffer+1];
			exwMaps = new Map[yearDiffer+1];
			BigDecimal cifSum = method(yearDiffer,startYear,"CIF",cifMaps,0);
			BigDecimal fobSum = method(yearDiffer,startYear,"FOB",fobMaps,1);
			BigDecimal exwSum = method(yearDiffer,startYear,"EXW",exwMaps,2);
			this.getModel().setValue("yem_deal","总额",3);
			this.getModel().setValue("yem_outmoney","$"+df.format((cifSum.add(fobSum)).add(exwSum)).toString(),3);
			drawChart(barChart,cifMaps,startYear);
		}

		}

	@Override
	public void entryRowClick(RowClickEvent evt) {
		EntryGrid entryGrid = (EntryGrid)evt.getSource();
		Control control1 = this.getControl("yem_histogramchartap");
		HistogramChart barChart = (HistogramChart) control1;
		if(StringUtils.equals(entryGrid.getKey(), "yem_entryentity")) {
			if(evt.getRow() == 0) {
				drawChart(barChart,cifMaps,startYear,"CIF");
			}
			if(evt.getRow() == 1) {
				drawChart(barChart,fobMaps,startYear,"FOB");
			}
			if(evt.getRow() == 2) {
				drawChart(barChart,exwMaps,startYear,"EXW");
			}
		}

	}

	@Override
	public void click(EventObject evt) {
		
		Control control = (Control) evt.getSource();
		Control control1 = this.getControl("yem_histogramchartap");
			HistogramChart barChart = (HistogramChart) control1;

		if(StringUtils.equals(control.getKey(),button_key)) {
			barChart.clearData();
			String staOb = (String) this.getModel().getValue(start_key);
			String endOb = (String) this.getModel().getValue(end_key);
			//对空处理
			if(StringUtils.isEmpty(staOb) || StringUtils.isEmpty(endOb)) {
				this.getView().showMessage("开始或截止年份为空，无法查询!");
				return;
			}
			//与默认查询年比较
			int startTemp = Integer.valueOf(staOb);
			int endTemp = Integer.valueOf(endOb);
			if(startTemp == startYear && endTemp == endYear) {
				this.getView().showMessage("默认数据为"+startYear+"-"+endYear+" 无需重复查询");
				return;
			}
				endYear = endTemp;
				startYear = startTemp;		
			//年差
			int yearDiffer = endYear- startYear;			
			if((yearDiffer +1) > 3) {
				this.getView().showMessage("最多只允许同时查询3年数据");
				return;
			}
			if(yearDiffer < 0) {
				this.getView().showMessage("起始年份无法大于截止年份");
				return;
			}
			
			//清除旧数据
			Map<String,Object> map = new HashMap<String,Object>();
			for(String name:legendName) {
				map.put(name+"年", false);
				for(int i=0;i<= yearDiffer;i++) {
					if((startYear+i+"").equals(name)) {
						map.put(name+"年", true);
						continue;
					}
				}
			}
			barChart.setLegendPropValue("selected", map);
			barChart.setTitlePropValue("text", "zz");
			barChart.setShowTitle(true);
			
			
			//起始年中的数据
			cifMaps = new Map[yearDiffer+1];
			fobMaps = new Map[yearDiffer+1];
			exwMaps = new Map[yearDiffer+1];
			BigDecimal cifSum = method(yearDiffer,startYear,"CIF",cifMaps,0);
			BigDecimal fobSum = method(yearDiffer,startYear,"FOB",fobMaps,1);
			BigDecimal exwSum = method(yearDiffer,startYear,"EXW",exwMaps,2);
			this.getModel().setValue("yem_deal","总额",3);
			this.getModel().setValue("yem_outmoney","$"+df.format((cifSum.add(fobSum)).add(exwSum)).toString(),3);
			barChart.clearData();
			drawChart(barChart,cifMaps,startYear);
				
		}
	}
	//存储数据、计算金额
	public BigDecimal method(int yearDiffer,int startYear,String type,Map<String,BigDecimal>[] cifMaps,int rowIndex) {
		for(int i=0;i<= yearDiffer;i++) {
			Map<String,BigDecimal> map = dateMakes(startYear+i,type);
			cifMaps[i] = map;
		}
		
		//给列表赋值
		this.getModel().setValue("yem_deal",type,rowIndex);
		//当前总额
		BigDecimal sum = BigDecimal.ZERO;
		for(Map<String,BigDecimal> temp:cifMaps) {
			Collection<BigDecimal> col = temp.values();
			BigDecimal sumTemp = BigDecimal.ZERO;
			for(BigDecimal temp1:col) {
				sumTemp = temp1.add(sumTemp);
			}
			sum = sumTemp.add(sum);
		}
		sum = sum.divide(new BigDecimal(1.0), 2, BigDecimal.ROUND_HALF_UP);
		this.getModel().setValue("yem_outmoney", "$"+df.format(sum).toString(),rowIndex);
		return sum;
	}
	//数据处理方法
	public Map<String,BigDecimal> dateMakes(int years,String type){
		Map<String,BigDecimal> datas = new LinkedHashMap<String,BigDecimal>();
		int[] months = new int[] {0,1,2,3,4,5,6,7,8,9,10,11};
		Calendar startCal = Calendar.getInstance();
		Calendar endCal = Calendar.getInstance();
		for(int month:months) {
			startCal.set(years, month, 1, 0, 0, 0);
			endCal.set(Calendar.YEAR, years);
			endCal.set(Calendar.MONTH, month+1);
			endCal.set(Calendar.DATE,0);
			endCal.set(Calendar.HOUR, 23);
			endCal.set(Calendar.MINUTE, 59);
			endCal.set(Calendar.SECOND, 59);
			List<QFilter> cifList = new ArrayList<QFilter>(); 
			cifList.add(QFilter.of("yem_transmodbase.name = ?",type));
			cifList.add(new QFilter("yem_fiedatets",QCP.large_equals,startCal.getTime()));
			cifList.add(new QFilter("yem_fiedatets",QCP.less_equals,endCal.getTime()));
			cifList.add(QFilter.of("yem_cusdecstatusname = ?","结关"));
			Map<Object, DynamicObject> map = BusinessDataServiceHelper.loadFromCache("yem_ca_cusdec","yem_sumlocdecltotal",cifList.toArray(new QFilter[0]));
			//出口总额
			BigDecimal sum = BigDecimal.ZERO;
			for(Object temp:map.keySet()) {
				DynamicObject dy = map.get(temp);
				BigDecimal db = dy.getBigDecimal("yem_sumlocdecltotal");
				sum = sum.add(db);
			}
			datas.put(month+1+"", sum);
		}
		return datas;
	}
	//首次渲染
	public void drawChart(HistogramChart barChart,Map<String,BigDecimal>[] cifMaps,int startYear) {
		String type = "CIF";
		Axis y = barChart.createYAxis("金额(万元)", AxisType.value);
		Map<String,Object> nameTextStyle = new HashMap<>();
		Number[] padding = new Number[] {0,0,0,100};
		nameTextStyle.put("padding",padding);
		y.setPropValue("nameTextStyle", nameTextStyle);
		
		Axis x = barChart.createXAxis("",AxisType.category);
		x.setPropValue("data", xStr);
		if(cifMaps.length == 1) {

			singleDrawChar(barChart,cifMaps[0],startYear,"#EC6114");
			
		}else {
		
			String[] colors = new String[] {"#6890FB","#A3FEB5","#F4DE6C"};
			for(int i=0;i<cifMaps.length;i++) {
				singleDrawChar(barChart,cifMaps[i],startYear+i,colors[i]);
			}

		}
		barChart.setShowTitle(false);
		barChart.setTitlePropValue("text", "成交方式("+type+")月度出口额(美元)同比统计");
		Map<String,Object> textStyle = new HashMap<String,Object>();
		textStyle.put("fontSize", 27);
		barChart.setTitlePropValue("textStyle", textStyle);
		barChart.setTitlePropValue("left",20);
		barChart.setShowTooltip(true);
		barChart.setShowLegend(true);
		barChart.setLegendVertical(false);
		barChart.setLegendPropValue("right", 20);
		barChart.setLegendPropValue("top", 40);
		
		
		barChart.refresh();
	}
	//列表按钮跳转新类型
	public void drawChart(HistogramChart barChart,Map<String,BigDecimal>[] cifMaps,int startYear,String type) {
		Axis y = barChart.createYAxis("金额/(万元)", AxisType.value);
		Map<String,Object> nameTextStyle = new HashMap<>();
		y.setPropValue("nameTextStyle", nameTextStyle);
		Axis x = barChart.createXAxis("月份",AxisType.category);
		x.setPropValue("data", xStr);
		if(cifMaps.length == 1) {

			singleDrawChar(barChart,cifMaps[0],startYear,"#6890FB");
			
		}else {
		
			String[] colors = new String[] {"#6890FB","#A3FEB5","#F4DE6C"};
			for(int i=0;i<cifMaps.length;i++) {
				singleDrawChar(barChart,cifMaps[i],startYear+i,colors[i]);
			}

		}
		barChart.setShowTitle(false);
		barChart.setTitlePropValue("text", "成交方式("+type+")月度出口额(美元)同比统计");
		Map<String,Object> textStyle = new HashMap<String,Object>();
		textStyle.put("fontSize", 27);
		barChart.setTitlePropValue("textStyle", textStyle);
		barChart.setTitlePropValue("left",20);
		barChart.setShowTooltip(true);
		barChart.setShowLegend(true);
		barChart.setLegendVertical(false);
		barChart.setLegendPropValue("right", 20);
		barChart.setLegendPropValue("top", 40);
		barChart.refresh();
	}
	
	//子drawChar
	public void singleDrawChar(HistogramChart barChart,Map<String,BigDecimal> map,int startYear,String color) {
		Number[] values = new Number[xStr.length];
		for(int i=0;i<xStr.length;i++) {
			if(i < 9) {			
			values[i] = map.get(String.valueOf((xStr[i].charAt(1)))).divide(BigDecimal.valueOf(10000.0),2,BigDecimal.ROUND_HALF_UP);
			}else {
			values[i] = map.get(xStr[i].substring(0, 2)).divide(BigDecimal.valueOf(10000.0),2,BigDecimal.ROUND_HALF_UP);	
			}
		}
		BarSeries barSeries =  barChart.createBarSeries(startYear+"年");
		legendName.add(startYear+"");
		barSeries.setData(values);
		barSeries.setColor(color);
		Map<String,Object> label = new HashMap<String,Object>();
		label.put("show", false);
		barSeries.setPropValue("label", label);

	}
	
	
}
