package yem.wmc.ydn.formplugin.dynamic;

import com.alibaba.nacos.shaded.com.google.common.collect.Maps;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.form.chart.*;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import yem.base.common.utils.DynamicObjectUtil;

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

/**
 * 首页中部柱状图表单插件
 *  @author  LHB
 */
public class CenterHomebarDynamic extends AbstractFormPlugin {
    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        archivesCommon();
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
//        archivesCommon();
    }

    /**
     * 创建柱状图
     * @Date 2020年11月17日
     * @Description
     */
    private void archivesCommon() {
        Map<String, Map<String,BigDecimal>> inia = inia();
        HistogramChart(inia);
    }

    /**
     * 初始化数据
     * @return
     */
    public static Map<String, Map<String, BigDecimal>> inia() {
        // 获取当前年份
        int currentYear = Calendar.getInstance().get(Calendar.YEAR);

        // 用于存储每月和对应矿区的数量映射
        Map<String, Map<String, BigDecimal>> resultMap = new LinkedHashMap<>();

        // 中文月份名称
        String[] monthNames = {"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"};

        String selectfields = DynamicObjectUtil.getSelectfields("yem_ca_homedate", false);
        DynamicObject[] load = BusinessDataServiceHelper.load("yem_ca_homedate", selectfields, null);

        for (DynamicObject dynamicObject : load) {
            Date yemDate = dynamicObject.getDate("yem_date");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(yemDate);

            int year = calendar.get(Calendar.YEAR); // 获取年
            int month = calendar.get(Calendar.MONTH); // 获取月份，0-11

            // 仅处理当前年份的数据
            if (year == currentYear) {
                // 获取数量
                BigDecimal yemQty = dynamicObject.getBigDecimal("yem_qty"); // 获取数量
                String diggings = dynamicObject.getString("yem_diggings"); // 获取矿区

                // 将月份数字转换为中文名称
                String monthName = monthNames[month];

                // 获取或创建该月的矿区数量映射
                Map<String, BigDecimal> diggingsMap = resultMap.computeIfAbsent(monthName, k -> new HashMap<>());

                // 累加当前矿区的数量
                diggingsMap.put(diggings, diggingsMap.getOrDefault(diggings, BigDecimal.ZERO).add(yemQty));
            }
        }

        return resultMap;
    }

    /**
     * 柱状图
     * @param equtypeMap
     * @Date 2020年11月14日
     * @Description
     */
    private void HistogramChart(Map<String, Map<String,BigDecimal>> equtypeMap) {
        List<String> keysList = new ArrayList<>();
        for (Map.Entry<String, Map<String,BigDecimal>> entry : equtypeMap.entrySet()) {
            keysList.add(entry.getKey());    // 添加键
        }
        Correctorder(keysList);
        HistogramChart customchart = this.getControl("yem_histogramchartap");
        customchart.clearData(); // 清除数据 避免重复增加数据
        customchart.clearGraphic();
        customchart.setMerge(false) ;
        customchart. setMargin (Position. left, "15px") ;
        customchart. setMargin(Position. right ,"15px") ;
        customchart. setMargin(Position.top, "55px");
        customchart. setMargin (Position.bottom,"55px");
        // 设置图例
        customchart.setShowLegend(true);
        // true纵向显示 false不纵向显示
        customchart.setLegendVertical(false);
        // 获取默认x轴数据
        List<String> materiaName = keysList;
        // 设置柱状图类别数据
        Map<Group, List<Number>> sortedData = this.getData02(materiaName,equtypeMap);
        // 利用lambda表达式遍历sortedData
        sortedData.forEach((group, data) -> {
            this.createBarSeries(group, data, customchart);
        });
        // 创建X轴
        Axis xAxis = this.createCategoryAxis("", true, customchart);

        // 设置X轴坐标数据
        xAxis.setCategorys(keysList);
        // X轴指示器属性设置
        Map<String, Object> xAxisPointer = Maps.newHashMap();
        xAxisPointer.put("show", true);
        xAxisPointer.put("type", "shadow");
        // X轴文本标签设置
        Label xAxisLabel = new Label();
        // 显示文本标签
        xAxisLabel.setShow(true);
//        xAxisLabel.setColor("white");

        // 背景色黑色
        xAxisLabel.setBackgroundColor("black");
        // xAxisPointer.put("nameGap", "2");
        xAxisPointer.put("label", xAxisLabel);
        // 坐标轴名字
         xAxis.setName("月份");
        xAxis.setPropValue("axisPointer", xAxisPointer);

//        Map<String, Object> axisLabelMap = new HashMap<>();
//        axisLabelMap.put("color", "#ffffff");
//        xAxis.setPropValue("axisLabel", axisLabelMap);



        // 创建Y轴
        Axis yAxis = this.createValueAxis("", false, customchart);
        // yAxis.setMax(200);
        // 设置Y轴数据显示格式
        Map<String, Object> axisLabel1 = Maps.newHashMap();
        axisLabel1.put("formatter", "{value} ");
        yAxis.setPropValue("axisLabel", axisLabel1);
        // Y轴设置最小刻度
        yAxis.setPropValue("minInterval", 1);
        // Y轴指示器属性
        Map<String, Object> yAxisPointer = Maps.newHashMap();
        yAxisPointer.put("show", true);
        yAxisPointer.put("type", "line");
        // Y轴文本标签设置
        Label yAxisLabel = new Label();
        yAxisLabel.setShow(true);
        yAxisLabel.setBackgroundColor("black");
//        yAxisLabel.setColor("white");
        yAxisPointer.put("label", xAxisLabel);
        // Y轴设置指示线类型
        Map<String, Object> lineStyle = Maps.newHashMap();
        lineStyle.put("type", "dotted");
        yAxisPointer.put("lineStyle", lineStyle);
        // 设置Y轴不触发悬浮提示信息
        yAxisPointer.put("triggerTooltip", false);
        yAxis.setPropValue("axisPointer", yAxisPointer);

//        Map<String, Object> Map = new HashMap<>();
//        Map.put("color", "#ffffff");
//        yAxis.setPropValue("axisLabel", Map);
        customchart.refresh();

    }

    private Axis createValueAxis(String name, boolean isX, HistogramChart customchart) {
        Axis axis = null;
        if (isX) {
            // X轴
            axis = customchart.createXAxis(name, AxisType.value);
        } else {
            // Y轴
            axis = customchart.createYAxis(name, AxisType.value);
        }

        // 坐标轴刻度相关设置
        Map<String, Object> axisTick = new HashMap<>();
        // 坐标轴刻度设置为不显示
        // axisTick.put("show", false);
        // 设置坐标轴的属性-刻度
        axis.setPropValue("axisTick", axisTick);

        //
        Map<String, Object> splitLine = new HashMap<>();
        Map<String, Object> lineStyle = new HashMap<>();
        // 分隔线的类型
        lineStyle.put("type", "dotted");
        // 分隔线的颜色
        lineStyle.put("color", "#E2E2E2");
        splitLine.put("lineStyle", lineStyle);
        // 设置坐标轴的属性-分隔线
        axis.setPropValue("splitLine", splitLine);
        // 设置坐标轴轴线颜色
        this.setLineColor(axis, "black");
        // 显示悬浮提示框
        customchart.setShowTooltip(true);
        return axis;
    }



    private Map<Group, List<Number>> getData02(List<String> materiaName, Map<String, Map<String, BigDecimal>> equtypeMap) {
        // TODO Auto-generated method stub
        Map<Group, List<Number>> summaryResult = new LinkedHashMap<Group, List<Number>>();
        List<Number> list01=new ArrayList<>();
        List<Number> list02=new ArrayList<>();
        // 得到默认groups
        List<Group> groups = this.getDefaultGroups();
        Correctorder(materiaName);
        for (Map.Entry<String, Map<String, BigDecimal>> outerEntry : equtypeMap.entrySet()) {
            String outerKey = outerEntry.getKey(); // 获取外层 Map 的键
            Map<String, BigDecimal> innerMap = outerEntry.getValue(); // 获取内层 Map
            // 遍历内层 Map 的键
            for (String innerKey : innerMap.keySet()) {
                BigDecimal value = innerMap.get(innerKey); // 获取内层 Map 中与 innerKey 相关的值
                if("TFM".equals(innerKey)){
                    list01.add(value);
                }
                if("KFM".equals(innerKey)){
                    list02.add(value);
                }
            }
        }

        summaryResult.put(groups.get(0), list01);

        summaryResult.put(groups.get(1), list02);

        return summaryResult;
    }

    private List<Group> getDefaultGroups() {
        List<Group> defaultGroupList = new ArrayList<>(2);
        defaultGroupList.add(new Group("项目", "length", "#22a2c3", true, ChartType.bar, 0));
        defaultGroupList.add(new Group("运营", "width", "#57c3c2", true, ChartType.bar, 0));
        return defaultGroupList;
    }
    public class Group {
        private String groupName;       // 组的名称
        private String width;      // 宽度
        private String color;      // 颜色
        private boolean isActive;   // 是否活动
        private ChartType chartType; // 图表类型
        private int someValue;     // 其他整数值（根据需要命名）

        // 构造函数
        public Group(String name, String width, String color, boolean isActive, ChartType chartType, int someValue) {
            this.groupName = name;
            this.width = width;
            this.color = color;
            this.isActive = isActive;
            this.chartType = chartType;
            this.someValue = someValue;
        }

        // 访问器（Getter）方法
        public String getName() {
            return groupName;
        }

        // 修改器（Setter）方法（可选）
        public void setName(String name) {
            this.groupName = name;
        }

    }
    private Axis createCategoryAxis(String name, boolean isX, HistogramChart customchart) {

        Map<String, Object> splitLine = new HashMap<>();
        splitLine.put("show", false);

        Axis axis = null;
        if (isX) {
            // X轴
            axis = customchart.createXAxis(name, AxisType.category);
        } else {
            // Y轴
            axis = customchart.createYAxis(name, AxisType.category);
        }
//        axis.setPropValue("splitLine", splitLine);
        // axis.setCategorys(x);
        // 坐标轴刻度相关设置
        Map<String, Object> axisTick = new HashMap<>();
        // 坐标轴刻度的显示间隔为0
        axisTick.put("interval", 0);
        // 坐标轴刻度设置为不显示
        // axisTick.put("show", true);
        // 设置坐标轴的属性-刻度
        axis.setPropValue("axisTick", axisTick);
        // 设置坐标轴轴线颜色
        this.setLineColor(axis, "black");
        return axis;
    }

    private void setLineColor(Axis axix, String color) {
        Map<String, Object> axisLineMap = new HashMap<>();
        Map<String, Object> lineStyleMap = new HashMap<>();
        // 坐标轴轴线的颜色
        lineStyleMap.put("color", color);
        axisLineMap.put("lineStyle", lineStyleMap);
        // 设置坐标轴的属性-轴线
        axix.setPropValue("axisLine", axisLineMap);
    }

    private void Correctorder(List<String> keysList) {
        // 按月份顺序排序
        List<String> orderedMonths = Arrays.asList(
                "一月", "二月", "三月", "四月", "五月",
                "六月", "七月", "八月", "九月", "十月",
                "十一月", "十二月"
        );

        // 使用自定义排序
        keysList.sort(Comparator.comparingInt(month ->
                orderedMonths.indexOf(month) == -1 ? Integer.MAX_VALUE : orderedMonths.indexOf(month)
        ));
    }

    private void createBarSeries(Group group, List<Number> data, HistogramChart customchart) {
        // TODO Auto-generated method stub
        BarSeries barSeries = customchart.createBarSeries(group.groupName);

        /**
         * 不设置柱宽度 让其随类目宽度自适应
         */
        // 设置柱宽度
         barSeries.setBarWidth("25px");

        // 设置柱颜色
        barSeries.setColor(group.color);
        // 设置类别展示类型
        barSeries.setType(group.chartType);
        // 动画过度时间
        barSeries.setAnimationDuration(2000);
        // 设置相同的stack会堆叠显示
//       barSeries.setStack("stack");
        // 设置所属坐标轴
//        barSeries.setPropValue("yAxisIndex", group.yAxisIndex);
        // 设置类别对应的数据包
        barSeries.setData((Number[]) data.toArray(new Number[0]));

    }
}
