import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:marking_app/common/model/report/report_histogram_model.dart';
import 'package:marking_app/utils/index.dart';
import 'package:marking_app/utils/my_text.dart';

// ignore: must_be_immutable
class _BarChart extends StatelessWidget {
  List<ReportHistogramModel> tagComparisonList;
  _BarChart(this.tagComparisonList);

  @override
  Widget build(BuildContext context) {
    return BarChart(
      BarChartData(
        barTouchData: barTouchData,
        titlesData: titlesData,

        borderData: borderData,
        barGroups: barGroups,
        gridData: FlGridData(
          show: true,
          drawHorizontalLine: true, // 绘制横线
          drawVerticalLine: false,
          // horizontalInterval: 10, // 设置横线间隔
          getDrawingHorizontalLine: (value) {
            return FlLine(
              color: Color.fromRGBO(229, 234, 255, 1), // 设置横线颜色
              strokeWidth: 0.8, // 设置横线宽度
            );
          },
        ),
        alignment: BarChartAlignment.spaceAround,
        // maxY: 20,
      ),
    );
  }

  BarTouchData get barTouchData => BarTouchData(
        enabled: false,
        touchTooltipData: BarTouchTooltipData(
          tooltipBgColor: Colors.transparent,
          tooltipPadding: EdgeInsets.zero,
          tooltipMargin: 6.h,
          getTooltipItem: (BarChartGroupData group, int groupIndex, BarChartRodData rod, int rodIndex) {
            return BarTooltipItem(
              rod.toY.round().toString(),
              TextStyle(color: const Color.fromRGBO(46, 91, 255, 1), fontWeight: FontWeight.w500, fontSize: 12.sp),
            );
          },
        ),
      );

  Widget getTitles(double value, TitleMeta meta) {
    final style = TextStyle(
      color: const Color.fromRGBO(46, 91, 255, 1),
      fontSize: 12.sp,
    );
    ReportHistogramModel _model = tagComparisonList[value.toInt()];

    String name = _model.name;
    List<String> newNames = [];
    bool multiLine = name.length > 5;
    if (multiLine) {
      List<String> nameList = name.split('');
      int nameListLength = nameList.length;
      int fiveRemainder = nameListLength % 5; // 5数取余
      bool hasFiveRemainder = fiveRemainder > 0; // 是否有余数

      int step = 5;
      int i = 0;
      while (i < nameListLength) {
        int oldI = i;
        i += hasFiveRemainder && i + step > nameListLength ? fiveRemainder : step;
        newNames.add(nameList.sublist(oldI, i).join('') + '\n');
      }
    }

    toPrint(val: '数据：' + newNames.toList().join(''));
    return SizedBox(
      height: 300.h,
      child: SideTitleWidget(
        axisSide: meta.axisSide,
        space: 6,
        child: multiLine
            ?
            // Text(newNames.toList().join(''), style: style, maxLines: null, textAlign: TextAlign.center)
            RichText(
                text: TextSpan(
                    children: newNames.map((e) {
                  toPrint(val: e);
                  return TextSpan(text: e, style: style);
                }).toList()),
              )
            : Text(name, style: style, maxLines: null, textAlign: TextAlign.center),
      ),
    );
  }

  Widget leftTitles(double value, TitleMeta meta) {
    if (value == meta.max) {
      return Container();
    }
    return SideTitleWidget(
      axisSide: meta.axisSide,
      child: Text(
        meta.formattedValue,
        style: TextStyle(
          fontSize: 12.sp,
          color: Color.fromRGBO(148, 163, 182, 1),
          fontWeight: FontWeight.w400,
        ),
      ),
    );
  }

  FlTitlesData get titlesData => FlTitlesData(
        show: true,
        bottomTitles: AxisTitles(
          axisNameSize: 200.w,
          drawBehindEverything: false,
          sideTitles: SideTitles(
            showTitles: true,
            // margin: 16, // 设置底部标题的边距
            reservedSize: 30,
            getTitlesWidget: getTitles,
          ),
        ),
        leftTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            reservedSize: 40,
            getTitlesWidget: leftTitles,
          ),
        ),
        topTitles: AxisTitles(
          sideTitles: SideTitles(showTitles: false),
        ),
        rightTitles: AxisTitles(
          sideTitles: SideTitles(showTitles: false),
        ),
      );

  FlBorderData get borderData => FlBorderData(
        show: false,
      );

  LinearGradient get _barsGradient => LinearGradient(
        colors: [
          Color.fromRGBO(46, 91, 255, 0.1),
          Color.fromRGBO(46, 91, 255, 1),
        ],
        begin: Alignment.bottomCenter,
        end: Alignment.topCenter,
      );

  List<BarChartGroupData> get barGroups => tagComparisonList.asMap().keys.map((i) {
        ReportHistogramModel _model = tagComparisonList[i];
        return BarChartGroupData(
          x: i,
          barRods: [
            BarChartRodData(
              toY: _model.val,
              gradient: _barsGradient,
            )
          ],
          showingTooltipIndicators: [0],
        );
      }).toList();
}

// ignore: must_be_immutable
class BarChartHistogram extends StatefulWidget {
  List<ReportHistogramModel> tagComparisonList;
  bool horizontal;
  double aspectRatio;
  double singleWidth;
  double heightVal;
  BarChartHistogram(this.tagComparisonList, {this.singleWidth = 220, this.aspectRatio = 3, this.horizontal = false, this.heightVal = 200, super.key});

  @override
  State<StatefulWidget> createState() => BarChartSample3State();
}

class BarChartSample3State extends State<BarChartHistogram> {
  @override
  Widget build(BuildContext context) {
    if (!widget.horizontal)
      return Container(
        width: widget.tagComparisonList.length * widget.singleWidth.w,
        height: widget.heightVal,
        child: _BarChart(widget.tagComparisonList),
      );

    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Container(
        width: widget.tagComparisonList.length * widget.singleWidth.w,
        child: AspectRatio(
          aspectRatio: widget.aspectRatio,
          child: _BarChart(widget.tagComparisonList),
        ),
      ),
    );
  }
}
