package com.yem.tws.chart;

import com.alibaba.druid.util.StringUtils;

import java.util.Date;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
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.field.DateRangeEdit;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.servicehelper.QueryServiceHelper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

public class Query extends AbstractFormPlugin implements RateListener {

    private String[] mapPlaces = new String[0];
    private Map<String, Object> mapDate = new HashMap<>();
    private DynamicObjectCollection dy = QueryServiceHelper
            .query("yem_ca_cusdec",
                    "yem_ciqentyportcodename," +//海关口岸
                            "yem_sumdecltotal," +//金额
                            "yem_fiedatets",//日期
                    null, "yem_sumdecltotal");

    private BigDecimal totalAmount = BigDecimal.ZERO.setScale(2);

    private Map<String, BigDecimal> amountMap = new HashMap<>();//创建一个map存所有金额数据

    private Date beginDay = new Date(0);//缺省日期范围起始日期
    private Date endDay = new Date(123, 11, 31);//缺省日期范围截止日期
    private String[] colors = {"#6890FB", "#A3FEB5", "#F4DE6C", "#E87278", "#87D8F7", "#5FBF92"};


    /**
     * 点击查询按钮后，获取页面填写内容
     *
     * @param evt
     */
    @Override
    public void click(EventObject evt) {
        //如果点击查询按钮
        if (StringUtils.equals("yem_query", ((Control) evt.getSource()).getKey())) {
            //获取单据体的数据包
            DynamicObject dataEntity = this.getModel().getDataEntity(true);
            // 获取海关口岸

            DynamicObjectCollection rows = (DynamicObjectCollection) this.getModel().getValue("yem_haiguankouan");

            if (rows != null) {
                mapPlaces = new String[rows.size()];
                int i = 0;
                for (DynamicObject row : rows) {
                    // 基础资料：存储每条基础资料的数据包，属性名是个常量fbasedataid
                    DynamicObject basedataObj = row.getDynamicObject("fbasedataid");
                    String basedataName = basedataObj.get("name").toString();
                    mapPlaces[i] = basedataName;
                    i++;
                }
            }
            // 获取日期
            // 需要通过如下方式，获取日期范围字段，开始、结束属性对象的标识
            DateRangeEdit headFieldEdit = this.getView().getControl("yem_daterangefield");
            String key_headdatestart = headFieldEdit.getStartDateFieldKey();
            String key_headdateend = headFieldEdit.getEndDateFieldKey();
            // 获取单据头日期范围，开始时间、结束时间
            Date headdatestart = (Date) this.getModel().getValue(key_headdatestart);//开始时间
            Date headdateend = (Date) this.getModel().getValue(key_headdateend);//结束时间
            if (headdatestart != null) {
                beginDay = headdatestart;
            }
            if (headdateend != null) {
                endDay = headdateend;
            }
        }

        // TODO Auto-generated method stub
        PieChart pieChart = this.getControl("yem_piechartap");
        this.drawChart(pieChart);
        //必须刷新，否则不触发签到渲染
        pieChart.refresh();


    }


    @Override
    public void registerListener(EventObject e) {
        // TODO Auto-generated method stub
        super.registerListener(e);
//        Button textEdit = this.getControl("yem_query");
//        textEdit.addClickListener(this);


    }

    @Override
    public void afterCreateNewData(EventObject e) {///******1111111111
        // TODO Auto-generated method stub
        super.afterCreateNewData(e);
        PieChart pieChart = this.getControl("yem_piechartap");
        this.drawChart(pieChart);
    }

    @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) {///******222222222
        pieChart.clearData();
        pieChart.setLegendVertical(true);
        pieChart.setShowTooltip(true);
        pieChart.setLegendPropValue("right", 0);//600
        pieChart.setLegendPropValue("bottom", 100);//200
//        pieChart.setShowLegend(false);
        //设置为位置
//        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", "100%");

        for (DynamicObject temp : dy) {

            String haiguankouan = temp.getString("yem_ciqentyportcodename");
            BigDecimal amount = temp.getBigDecimal("yem_sumdecltotal").stripTrailingZeros();
            Date date = temp.getDate("yem_fiedatets");
            if (date != null && date.compareTo(beginDay) >= 0 && date.compareTo(endDay) <= 0) {
                if (amountMap.containsKey(haiguankouan)) {
                    BigDecimal currentAmount = amountMap.get(haiguankouan);
                    amountMap.put(haiguankouan, currentAmount.add(amount));
                } else {
                    amountMap.put(haiguankouan, amount);
                }

                totalAmount = totalAmount.add(amount);
            }
        }

        if (mapPlaces.length > 10) {//选择口岸超过十条
            ItemValue[] data = new ItemValue[6];
            Map<String, BigDecimal> queryAmountMap = new HashMap<>();//创建一个map存查询关口金额数据
            for (int i = 0; i < mapPlaces.length; i++) {
                queryAmountMap.put(mapPlaces[i], amountMap.get(mapPlaces[i]));
            }
            List<Map.Entry<String, BigDecimal>> top6Entries = queryAmountMap.entrySet()
                    .stream()
                    .map(entry -> {
                        if (entry.getValue() == null) {
                            entry.setValue(BigDecimal.ZERO);
                        }
                        return entry;
                    })
                    .sorted(Map.Entry.<String, BigDecimal>comparingByValue().reversed())
                    .limit(6)
                    .collect(Collectors.toList());
            for (int i = 0; i < 6; i++) {
                BigDecimal a = top6Entries.get(i).getValue();
                BigDecimal b = totalAmount;
                BigDecimal c = a.divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP);
                String randomColor = colors[i];
                ItemValue data2 = new ItemValue(top6Entries.get(i).getKey(), c.setScale(2, RoundingMode.DOWN), randomColor);
                data[i] = data2;
            }
            Label label = new Label();
            label.setShow(true);
            label.setFormatter("{b}\n{c}");
            series.setLabel(label);
            series.setData(data);


        } else if (mapPlaces.length == 0) {//没有选择口岸，缺省
            DynamicObjectCollection dy1 = QueryServiceHelper
                    .query("yem_ca_cusdec",
                            "yem_ciqentyportcodename," +//海关口岸
                                    "yem_sumdecltotal",//
                            null, "yem_sumdecltotal");
            for (DynamicObject temp : dy) {
                String haiguankouan = temp.getString("yem_ciqentyportcodename");
                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);
                }
            }
            List<Map.Entry<String, BigDecimal>> top6Entries = new ArrayList<>(amountMap.entrySet())
                    .stream()
                    .sorted(Map.Entry.<String, BigDecimal>comparingByValue().reversed())
                    .limit(6)
                    .collect(Collectors.toList());
            ItemValue[] data = new ItemValue[top6Entries.size()];
            for (int i = 0; i < top6Entries.size(); i++) {
                BigDecimal a = top6Entries.get(i).getValue();
                BigDecimal b = totalAmount;
                BigDecimal c = a.divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP);
                String randomColor = colors[i];
                ItemValue data2 = new ItemValue(top6Entries.get(i).getKey(), c.setScale(2, RoundingMode.DOWN), randomColor);
                data[i] = data2;
            }
            Label label = new Label();
            label.setShow(true);
            label.setFormatter("{b}\n{c}");
            series.setLabel(label);
            series.setData(data);

//            boolean isEmpty = true;
//            for (int i = 0; i < data.length; i++) {
//                if (data[i] != null) {
//                    isEmpty = false;
//                    break;
//                }
//            }
//            if (!isEmpty){
////            if (data.length>0) {
//                Label label = new Label();
//                label.setShow(true);
//                label.setFormatter("{b}\n{c}");
//                series.setLabel(label);
//                series.setData(data);
//            }

        } else {//选择口岸十条以内

            ItemValue[] data = new ItemValue[mapPlaces.length];
            Map<String, BigDecimal> queryAmountMap = new HashMap<>();//创建一个map存查询关口金额数据

            for (int i = 0; i < mapPlaces.length; i++) {
                if (amountMap.containsKey(mapPlaces[i])) {
                    queryAmountMap.put(mapPlaces[i], amountMap.get(mapPlaces[i]));
                } else {
                    queryAmountMap.put(mapPlaces[i], BigDecimal.ZERO);
                }

            }


            List<Map.Entry<String, BigDecimal>> top6Entries = queryAmountMap.entrySet()
                    .stream()
                    .sorted(Map.Entry.<String, BigDecimal>comparingByValue().reversed())
                    .limit(mapPlaces.length)
                    .collect(Collectors.toList());

            for (int i = 0; i < mapPlaces.length; i++) {
                BigDecimal a = top6Entries.get(i).getValue();
                BigDecimal b = totalAmount;
                BigDecimal c = a.divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP);
                String randomColor = colors[i];
                ItemValue data2 = new ItemValue(top6Entries.get(i).getKey(), c.setScale(2, RoundingMode.DOWN), randomColor);
                data[i] = data2;
            }
            Label label = new Label();
            label.setShow(true);
            label.setFormatter("{b}\n{c}");
            series.setLabel(label);
            series.setData(data);
        }

    }
}
