package com.yem.tws.chart;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.nacos.shaded.com.google.common.collect.Maps;
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.chart.*;
import kd.bos.form.control.Button;
import kd.bos.form.control.Control;
import kd.bos.form.control.events.RateEvent;
import kd.bos.form.control.events.RateListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;

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

/**
 * 国家排名
 *
 * @author lipan
 */
public class countryranking extends AbstractFormPlugin implements RateListener {

    private String[] mapPlaces = new String[0];
    boolean yem_checkboxfield = false;//是否显示图例


    @Override
    public void afterCreateNewData(EventObject e) {
        // TODO Auto-generated method stub
        super.afterCreateNewData(e);
        yem_checkboxfield = (boolean) this.getModel().getValue("yem_checkboxfield");//是否显示图例
        PieChart pieChart = this.getControl("yem_piechartap");//全部
        this.drawChart(pieChart, "yem_tabpageap");
        //必须刷新，否则不触发签到渲染
        pieChart.refresh();
        PieChart pieChartis = this.getControl("yem_piechartapis");//进口
        this.drawChart(pieChartis, "yem_tabpageapis");
        //必须刷新，否则不触发签到渲染
        pieChartis.refresh();
        PieChart pieChartes = this.getControl("yem_piechartapes");//出口
        this.drawChart(pieChartes, "yem_tabpageapes");
        //必须刷新，否则不触发签到渲染
        pieChartes.refresh();
    }

    @Override
    public void registerListener(EventObject e) {
        // TODO Auto-generated method stub
        super.registerListener(e);
    }

    @Override
    public void click(EventObject evt) {
    }

    @Override
    public void beforeBindData(EventObject e) {///******44444444
        // TODO Auto-generated method stub
        super.beforeBindData(e);
    }


    @Override
    public void update(RateEvent evt) {
        // TODO Auto-generated method stub
        PieChart pieChart = this.getControl("yem_piechartap");
        //this.drawChart(pieChart);
        //必须刷新，否则不触发签到渲染
        pieChart.refresh();
    }


    public void drawChart(PieChart pieChart, String button) {
        Map<String, BigDecimal> amountMap = new HashMap<>();//创建一个map存所有金额数据
        DynamicObjectCollection dy = null;
        pieChart.clearData();
        pieChart.setShowTitle(true);//是否显示标题
        pieChart.setShowLegend(yem_checkboxfield);//设置是否显示图例
        pieChart.setLegendVertical(yem_checkboxfield);//设置是否显示图例
        pieChart.setShowTooltip(true);
        pieChart.setDraggable(true);
        pieChart.setName(new LocaleString(""));
        pieChart.setTitlePropValue("x", (Object) 10);
        pieChart.setTitlePropValue("y", (Object) 0);
        pieChart.setLegendPropValue("right", (Object) 10);//设置图例组件数据
        pieChart.setLegendPropValue("top", (Object) "30");
        pieChart.setLegendPropValue("itemWidth", (Object) 10);
        pieChart.setLegendPropValue("itemHeight", (Object) 10);
        //设置为位置
        //       pieChart.setMargin(Position.right, "30px");//30
        pieChart.setMargin(Position.top, "20px");//30
//        pieChart.setMargin(Position.bottom, "10px");//10
//        pieChart.setMargin(Position.left, "20px");//20
        PieSeries series = pieChart.createPieSeries("国家排名");
        series.setRadius("60%", "80%");
        series.setCenter("50%","60%");
        series.setPropValue("height", "90%");
        // 设置折线上文本的相关属性
        Label label = new Label();
        label.setShow(true);
        //label.setColor("#000000");
        //label.setPosition(Position.inside);
        label.setFormatter("{b}\n{c}");
        series.setLabel(label);

        if (StringUtils.equals("yem_tabpageap", button)) {
            //国家排名
            dy = QueryServiceHelper.query("yem_ca_cusdec", "yem_custradecodbase.name Subleasestrategy ," +//贸易国别
                            "yem_sumdecltotal," +//金额合计
                            "yem_sumlocdecltotal",//金额本位币合计
                    null, "yem_custradecodbase");//获取显示数据

        }
        if (StringUtils.equals("yem_tabpageapis", button)) {
            //国家排名
            dy = QueryServiceHelper.query("yem_ca_cusdec", "yem_custradecodbase.name Subleasestrategy ," +//贸易国别
                            "yem_sumdecltotal," +//金额合计
                            "yem_sumlocdecltotal",//金额本位币合计
                    new QFilter("yem_billtypefield.number", QCP.equals, "I").toArray()
                    , "yem_custradecodbase");//获取显示数据
        }
        if (StringUtils.equals("yem_tabpageapes", button)) {
            //国家排名
            dy = QueryServiceHelper.query("yem_ca_cusdec", "yem_custradecodbase.name Subleasestrategy ," +//贸易国别
                            "yem_sumdecltotal," +//金额合计
                            "yem_sumlocdecltotal",//金额本位币合计
                    new QFilter("yem_billtypefield.number", QCP.equals, "E").toArray(),
                    "yem_custradecodbase");//获取显示数据
        }

        if (dy != null) {
            //对数据进行分组
            for (DynamicObject temp : dy) {
                String haiguankouan = temp.getString("Subleasestrategy");
                BigDecimal amount = temp.getBigDecimal("yem_sumdecltotal").stripTrailingZeros();
                if (amountMap.containsKey(haiguankouan)) {
                    BigDecimal currentAmount = amountMap.get(haiguankouan);
                    amountMap.put(haiguankouan, currentAmount.add(amount));
                } else {
                    amountMap.put(haiguankouan, amount);
                }
            }
        }
        //1：把map转换成entryset，再转换成保存Entry对象的list。
        List<Map.Entry<String, BigDecimal>> entrys = new ArrayList<>(amountMap.entrySet());
        //2：调用Collections.sort(list,comparator)方法把Entry-list排序
        Collections.sort(entrys, new MyComparator());
        ItemValue[] data;
        //只获取前10名
        if (entrys.size() > 10) {
            data = new ItemValue[10];
        } else {

            data = new ItemValue[entrys.size()];
        }
        int i = 0;
        for (Map.Entry<String, BigDecimal> entry : entrys) {
            String randomColor = generateRandomColor(i);
            ItemValue data2 = new ItemValue(ResManager.loadKDString((String) entry.getKey(), (String) "PieChartCardDemoPlugin_2", (String) "bos-portal-plugin", (Object[]) new Object[0]), (Number)((BigDecimal)entry.getValue().divide(BigDecimal.valueOf(10000)).setScale(2,BigDecimal.ROUND_HALF_UP)), randomColor);
            data[i] = data2;
            if (i == 9) {
                break;
            }
            i++;
        }
        series.setData(data);
    }
    //随机生成颜色
    public static String generateRandomColor(int i) {
        Map<String,String> map=new HashMap<>();
        map.put("0", "#6890FB");
        map.put("1", "#A3FEB5");
        map.put("2", "#F4DE6C");
        map.put("3", "#E87278");
        map.put("4", "#87D8F7");
        map.put("5", "#5FBF92");
        return map.get(i%6+"");
    }
}

