package yem.wmc.ydn.formplugin.dynamic;

import kd.bos.algo.DataSet;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.form.BindingContext;
import kd.bos.form.IFormView;
import kd.bos.form.chart.*;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.sdk.plugin.Plugin;
import yem.base.common.utils.DateUtil;

import java.math.BigDecimal;
import java.util.*;

/**
 * 首页人员需求执行TOP界面插件
 * @author  lib
 */
public class UserExecuteTop extends AbstractBillPlugIn implements Plugin {

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        String className = this.getClass().getName();
        IFormView view = this.getView();
        List<DynamicObject> data = queyData(className, "A");
        Map<String, Double> equtypeMap = new HashMap<>();
        for(DynamicObject object:data){
            equtypeMap.put(object.getString("yem_operator"),
                    object.getBigDecimal("yem_qty").doubleValue());
        }
        if (equtypeMap.size() > 0)HistogramChart(equtypeMap);

    }


    private List<DynamicObject> queyData(String className,String yem_needtype){
        Date yearFirst = DateUtil.getYearFirst(new Date());
        Date yearLast = DateUtil.getYearLast(new Date());
        String selectFiles = "yem_operator.name yem_operator,yem_qty";
        DataSet data = ORM.create().queryDataSet(className,"yem_ca_homedate",selectFiles,
                new QFilter[]{
                        new QFilter("yem_needtype", QCP.equals,yem_needtype),
                        new QFilter("yem_isfinish", QCP.equals,true),
                        new QFilter("yem_date",QCP.large_equals,yearFirst),
                        new QFilter("yem_date",QCP.less_equals,yearLast)});
        data = data.groupBy(new String[]{"yem_operator"}).sum("yem_qty").finish()
                .orderBy(new String[]{"yem_qty"});
        DynamicObjectCollection datas = ORM.create().toPlainDynamicObjectCollection(data.copy());
        List<DynamicObject> result = datas.subList(0, 10);

        return result;
    }

    /**
     * 柱状图
     * @param equtypeMap
     * @Date 2020年11月14日
     * @Description
     */
    private void HistogramChart(Map<String, Double> equtypeMap) {
        List<String> keysList = new ArrayList<>();
        List<Number> valuesList = new ArrayList<>();
        for (Map.Entry<String, Double> entry : equtypeMap.entrySet()) {
            keysList.add(entry.getKey());    // 添加键
            valuesList.add(entry.getValue()); // 添加值
        }
        Collections.sort(valuesList, (a, b) -> Double.compare(a.doubleValue(), b.doubleValue()));
        BarChart barchart = this.getControl("yem_barchartap");
        //设置是否显示图例
        barchart.setShowLegend(true);
        barchart.setLegendVertical(true);
        boolean isLegendVertical = true;
        barchart.setLegendVertical(isLegendVertical);
        Map<String, Object> titlePropValue = new HashMap<>();
        // 主标题内容：text
        titlePropValue.put("text", "区域信息");
        // 设置触发提示框的类型为axis：坐标轴触发
        barchart.addTooltip("trigger", "axis");
        // 字符串模板格式
        List<Object> toolTipFuncPath = new ArrayList<>();
        String formatter = "{b0}: {c0}";
        barchart.addTooltip("formatter", formatter);
        toolTipFuncPath.add("tooltip");
        toolTipFuncPath.add("formatter");
        barchart.addFuncPath(toolTipFuncPath);
        barchart.setShowTooltip(true);
        // 设置图例位置为中上
        barchart.setLegendAlign(XAlign.center, YAlign.top);
        //AxisType可以调整纵轴或横轴显示数据
        Axis x = barchart.createYAxis("人员", AxisType.category);
        Axis y = barchart.createXAxis("数量", AxisType.value);
        Map<String, Object> axisTick = new HashMap<>();
        axisTick.put("interval", 0);

        y.setPropValue("minInterval", 1);
        x.setPropValue("data", keysList);
        x.setPropValue("axisTick", axisTick);
        BarSeries barseries = barchart.createSeries("");
        // 设置系列中数据的内容
        createBarSeries(barseries,valuesList);
//        barseries.setBarWidth("25px");
        barchart.refresh();


    }
    private void createBarSeries(BarSeries barSeries,List<Number> values) {

        barSeries.setAnimationDuration(2000);// 动画2秒
        List<ItemValue> itemValuesList = new ArrayList<>();
        //根据数据建立不同据条的颜色数据信息
        for (int i = 0; i < values.size(); i++) {
            Number num = values.get(i);
            // 偶数基数使用 #496283，奇数基数使用 #1BC85E
            String color = (i % 2 == 0) ? "#496283" : "#1BC85E"; // 根据索引而不是值来选择颜色
            ItemValue data = new ItemValue(num, color); // 创建 ItemValue 实例
            itemValuesList.add(data); // 将 ItemValue 添加到列表
        }
        ItemValue[] itemValuesArray = itemValuesList.toArray(new ItemValue[0]);
        barSeries.setData(itemValuesArray);

    }



}