package com.yem.tws.chart;

import com.alibaba.druid.util.StringUtils;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.chart.*;
import kd.bos.form.container.Tab;
import kd.bos.form.container.TabPage;
import kd.bos.form.control.Control;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.control.events.TabSelectEvent;
import kd.bos.form.control.events.TabSelectListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.servicehelper.QueryServiceHelper;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class Histogram extends AbstractFormPlugin implements TabSelectListener {

    private static LocalDate today = LocalDate.now();//当前日期
    private static LocalDate MonthAgo = today.minusDays(30); // 当前日期前一个月
    private final static String SELECTBYDAY = "yem_tabpageap";//按日查询按钮
    private final static String SELECTBYMONTH = "yem_tabpageap1";//按月查询按钮
    private Map<Date, Integer> dataCountMap = new HashMap<>();
    private Map<String, Integer> monthCountMap = new HashMap<>();
    private DynamicObjectCollection dy = QueryServiceHelper
            .query("yem_ca_cusdec",
                    "yem_fiedatets",//日期
                    null);

    @Override
    public void registerListener(EventObject e) {
        TabPage searchByDate = this.getView().getControl(SELECTBYDAY);
        TabPage  searchByMonth = this.getView().getControl(SELECTBYMONTH);
        Tab  search = this.getView().getControl("yem_tabap");
        searchByDate.addClickListener(this);
        searchByMonth.addClickListener(this);
        search.addTabSelectListener(this);


    }


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

        //如果点击按日查询按钮
        if (StringUtils.equals("yem_tabpageap", ((TabPage) evt.getSource()).getKey())) {
            this.afterCreateNewData(evt);

        } else if (StringUtils.equals("yem_tabpageap1", ((TabPage) evt.getSource()).getKey())) {
            this.drawChartByMonth(barchart);

        }
        barchart.refresh();
    }

    @Override
    public void tabSelected(TabSelectEvent tabSelectEvent) {
        Control control = this.getControl("yem_histogramchartap");
        HistogramChart barchart = (HistogramChart) control;

        String subTabKey = tabSelectEvent.getTabKey();

        //如果点击按日查询按钮
        if (StringUtils.equals("yem_tabpageap", subTabKey)) {
//            this.afterCreateNewData(tabSelectEvent);
            this.drawChartByMonth(barchart);

        } else if (StringUtils.equals("yem_tabpageap1",subTabKey)) {
//            this.drawChartByMonth(barchart);
            this.drawChart(barchart);

        }
        barchart.refresh();

    }

    @Override
    public void afterCreateNewData(EventObject e) {///******1111111111
        super.afterCreateNewData(e);
        //获取柱状图控件
        Control control = this.getControl("yem_histogramchartap");
        HistogramChart barchart = (HistogramChart) control;
//        this.drawChart(barchart);
        this.drawChartByMonth(barchart);

    }

    @Override
    public void beforeBindData(EventObject e) {///******44444444
        super.beforeBindData(e);
    }

    //按日期查询
    public void drawChart(HistogramChart barchart) {
        //设置条形图样式
        this.setHistogram(barchart);
        barchart.setShowTooltip(true);
        barchart.setLegendVertical(true);
        //设置坐标轴名称
        Axis x = barchart.createXAxis("日期", AxisType.category);
        Axis y = barchart.createYAxis("数量", AxisType.value);

        // 设置X轴类目数据（如果没有设置，则需要再series中设置）
        String[] date = new String[30];
        LocalDate today = LocalDate.now();
        // 从今日起向前推算30天，并填充日期数据
        for (int i = 0; i < 30; i++) {
            LocalDate localdate = today.minusDays(i);
            String formattedDate = localdate.format(DateTimeFormatter.ofPattern("M月d日"));
            date[i] = formattedDate;
        }

        //添加数据
        BarSeries barSeries = barchart.createBarSeries("报关数量");

        for (DynamicObject temp : dy) {
            Date d = temp.getDate("yem_fiedatets");
            if (d != null && d.compareTo(Date.from(MonthAgo.atStartOfDay(ZoneId.systemDefault()).toInstant())) >= 0 && d.compareTo(Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant())) <= 0) {
                dataCountMap.put(d, dataCountMap.getOrDefault(date, 0) + 1);
            }
        }

        // 从今天往前数30天，包含今天在内的日期
        LocalDate[] dates = new LocalDate[30];
        for (int i = 0; i < 30; i++) {
            dates[i] = today.minusDays(i);
        }

        // 根据dataCountMap的键来赋值values
        Number[] values = new Number[30];
        for (int i = 0; i < 30; i++) {
            Integer value = dataCountMap.get(Timestamp.valueOf(dates[i].atStartOfDay()));
            values[i] = value != null ? value : 0;
        }

//        this.addDataZoom(barchart);
        x.setPropValue("data", date);
        String randomColor = "#6890FB";
        barSeries.setData(values);
        barSeries.setColor(randomColor);
        barSeries.setBarWidth("50%");
        barchart.refresh();
    }


    //按月份查找
    public void drawChartByMonth(HistogramChart barchart) {
        this.setHistogram(barchart);//设置柱状图图例
        Axis x = barchart.createXAxis("日期", AxisType.category);
        Axis y = barchart.createYAxis("数量", AxisType.value);

        // 设置X轴类目数据（如果没有设置，则需要再series中设置）
        String[] dates = new String[12];
        List<String> months = new ArrayList<>(Arrays.asList(
                "一月", "二月", "三月", "四月", "五月", "六月",
                "七月", "八月", "九月", "十月", "十一月", "十二月"
        ));
        LocalDate today = LocalDate.now();
        for (int i = 0; i < 12; i++) {
            dates[i] = months.get(i);
        }
        // 获取当前年份和月份
        int currentYear = today.getYear();
        int currentMonth = today.getMonthValue();

        List<String> displayedMonths = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            int year = currentYear;
            int month = currentMonth - i;
            if (month <= 0) {
                month += 12;
                year--;
            }
            String key = year + "年" + month + "月";
            displayedMonths.add(months.get(month - 1));
            dates[i] = key;
        }

        // 添加数据
        BarSeries barSeries = barchart.createBarSeries("报关数量");

        for (DynamicObject temp : dy) {
            Date d = temp.getDate("yem_fiedatets");
            if (d != null) {
                LocalDate localDate = d.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                String formattedDate = localDate.format(DateTimeFormatter.ofPattern("yyyy年M月"));
                for (String date : dates) {
                    if (formattedDate.equals(date)) {
                        monthCountMap.merge(date, 1, Integer::sum);
                        break;
                    }
                }
            }
        }

        for (String date : dates) {
            if (!monthCountMap.containsKey(date)) {
                monthCountMap.put(date, 0);
            }
        }

        Number[] values = new Number[12];
        for (int i = 0; i < values.length; i++) {
            LocalDate date = today.minusMonths(i); // 从当前日期往前推i个月
            String formattedDate = date.format(DateTimeFormatter.ofPattern("yyyy年M月"));

            if (monthCountMap.containsKey(formattedDate)) {
                values[i] = monthCountMap.get(formattedDate);
            }
        }

        dates = Arrays.stream(dates)
                .filter(monthCountMap::containsKey)
                .toArray(String[]::new);


//        this.addDataZoom(barchart);
        x.setPropValue("data", dates);
        barSeries.setData(values);
        String randomColor = "#6890FB";
        barSeries.setColor(randomColor);
        barSeries.setBarWidth("50%");
        barchart.refresh();


    }


    //---------------------------------------------------------------------------------
    //----------------------------------私有方法类--------------------------------------
    //---------------------------------------------------------------------------------

    //方法：随机生成一个16进制的RGB字符串
    public static String generateRandomColor() {
        Random random = new Random();
        // 生成 RGB 值
        int red = random.nextInt(256);
        int green = random.nextInt(256);
        int blue = random.nextInt(256);
        // 将 RGB 值转换为十六进制字符串
        String color = String.format("#%02x%02x%02x", red, green, blue);
        return color;
    }


    //方法：如果该日期没有成交单数，不显示该日期
    private static String[] filterDates(String[] date, Map<Date, Integer> dataCountMap) {
        // 创建一个SimpleDateFormat对象，用于解析输入的日期字符串
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("M月d日");
        // 创建一个列表，用于存储筛选后的日期
        List<String> filteredDates = new ArrayList<>();
        // 获取当前的日历实例，并提取当前年份
        Calendar currentCalendar = Calendar.getInstance();
        int currentYear = currentCalendar.get(Calendar.YEAR);
        // 遍历日期数组
        for (String dateString : date) {
            try {
                // 解析日期字符串为Date对象
                Date parsedDate = inputDateFormat.parse(dateString);
                // 创建一个日历实例，并设置解析出的日期对象
                Calendar parsedCalendar = Calendar.getInstance();
                parsedCalendar.setTime(parsedDate);
                // 将当前年份设置为解析出的日期对象的年份
                parsedCalendar.set(Calendar.YEAR, currentYear);
                // 如果dataCountMap中包含解析后的日期对象，则将日期字符串添加到filteredDates列表中
                if (dataCountMap.containsKey(parsedCalendar.getTime())) {
                    filteredDates.add(dateString);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        // 将filteredDates列表转换为字符串数组并返回
        return filteredDates.toArray(new String[0]);
    }


    //方法：设置柱状图图例
    public static void setHistogram(HistogramChart barchart) {
        barchart.clearData();
        //设置是否显示标题
        boolean isShowTitle = true;
        barchart.setShowTitle(isShowTitle);
        barchart.setTitlePropValue("text", "报关数量统计");
        //设置是否显示图例
        boolean isShowLegend = true;
        barchart.setShowLegend(isShowLegend);
        //设置图例纵向展示
        boolean isLegendVertical = true;
        barchart.setLegendVertical(isLegendVertical);
        //设置图例右侧展示
        barchart.setLegendPropValue("right", 20);

    }


}
