import 'package:base/consts/color.dart';
import 'package:base/consts/external_assets_package_key.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';
import 'package:flutter_calendar_carousel/classes/event.dart';
import 'package:flutter_calendar_carousel/classes/event_list.dart';
import 'package:flutter_calendar_carousel/flutter_calendar_carousel.dart' show CalendarCarousel;
import 'package:flutter_circular_chart/flutter_circular_chart.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../model/task_calendar/calendar_main_model.dart';
import '../../services/calendar_main_services.dart';
import '../../view/inspection_record/record_list_screen.dart';
import '../../view/task_calendar/select_route_calendar.dart';

class CalendarMainPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _CalendarMainPageState();
}

class _CalendarMainPageState extends State<CalendarMainPage> {
  CalendarCarousel _calendarCarouselNoHeader;
  final EventList<Event> _markedDateMap = EventList<Event>();
  DateTime _currentDate = DateTime.now();
  String _routeName = '全部线路';
  int _routeId = -1;
  String titleYear = DateTime.now().toString().substring(0, 4);
  String titleMonth = DateTime.now().toString().substring(5, 7);
  bool isAnimating = false;
  CalendarModel initData;
  String theme = '';
  int myUserId;

  @override
  void initState() {
    super.initState();
    initConfig();
  }

  Future<void> initConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        myUserId = num.tryParse(preferences.get('user_id'));
        theme = preferences.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
        loadData();
      });
    });
  }

  List<Widget> getContainer(CalendarDataModel calendarDataModel) {
    List<Container> container = [];
    if (calendarDataModel.omission > 0) {
      container.add(Container(
        height: 3,
        color: Colors.yellow,
      ));
    }
    if (calendarDataModel.qualified > 0) {
      container.add(Container(
        height: 3,
        color: Colors.green,
      ));
    }
    if (calendarDataModel.unqualified > 0) {
      container.add(Container(
        height: 3,
        color: Colors.red,
      ));
    }

    return container;
  }

  Future<void> loadData() async {
    setState(() {
      isAnimating = true;
    });
    await checkCalendar(titleYear + '-' + titleMonth, _routeId, myUserId).then((data) {
      setState(() {
        initData = data;
        isAnimating = false;
        _markedDateMap.clear();
        for (final _detail in initData.calendarData) {
          Widget _eventIcon = Container(
            child: Column(
              children: getContainer(_detail),
            ),
          );
          _markedDateMap.add(DateTime.parse(_detail.date),
              Event(date: DateTime.parse(_detail.date), title: _detail.date, icon: _eventIcon));
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (theme.isEmpty) {
      return const Scaffold(body: Text(''));
    }
    _calendarCarouselNoHeader = CalendarCarousel<Event>(
      onDayPressed: (DateTime date, List<Event> events) {
        setState(() {
          _currentDate = date;
          if (titleYear != date.toString().substring(0, 4) || titleMonth != date.toString().substring(5, 7)) {
            if (titleYear != date.toString().substring(0, 4)) {
              if (int.parse(date.toString().substring(0, 4)) > int.parse(titleYear)) {
                _calendarCarouselNoHeader.rightButtonIcon;
              } else {
                _calendarCarouselNoHeader.leftButtonIcon;
              }
            }
            if (titleMonth != date.toString().substring(5, 7)) {
              if (int.parse(date.toString().substring(5, 7)) > int.parse(titleMonth)) {
                _calendarCarouselNoHeader.rightButtonIcon;
              } else {
                _calendarCarouselNoHeader.leftButtonIcon;
              }
            }
            titleYear = date.toString().substring(0, 4);
            titleMonth = date.toString().substring(5, 7);

            loadData();
          }
        });
        events.forEach((event) => {
              Navigator.push(context, MaterialPageRoute(builder: (context) {
                return RecordListScreen(currentDate: _currentDate);
              }))
            });
      },
      weekendTextStyle: const TextStyle(
        color: Colors.red,
      ),
      weekFormat: false,
      markedDatesMap: _markedDateMap,
      height: 420.0,
      selectedDateTime: _currentDate,
      targetDateTime: _currentDate,
      customGridViewPhysics: const NeverScrollableScrollPhysics(),
      markedDateShowIcon: true,
      markedDateIconMaxShown: 3,
      markedDateMoreShowTotal: true,
      showHeader: false,
      daysHaveCircularBorder: false,
      isScrollable: false,
      markedDateIconBuilder: (event) {
        return event.icon;
      },
      selectedDayTextStyle: const TextStyle(
        color: Colors.red,
      ),
      selectedDayBorderColor: Colors.grey[100],
      selectedDayButtonColor: Colors.grey[100],
      todayBorderColor: Colors.greenAccent,
      todayButtonColor: Colors.greenAccent,
      todayTextStyle: const TextStyle(
        color: Colors.black,
      ),
      onCalendarChanged: (DateTime date) {
        setState(() {
          if (titleYear != date.toString().substring(0, 4) || titleMonth != date.toString().substring(5, 7)) {
            titleYear = date.toString().substring(0, 4);
            titleMonth = date.toString().substring(5, 7);
            loadData();
          }
        });
      },
      locale: 'zh',
    );
    if (initData == null) {
      return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: Text(
            titleYear + '年' + titleMonth + '月',
          ),
          centerTitle: true,
          elevation: 0.2,
          brightness: Brightness.light,
          actions: <Widget>[
            IconButton(
              icon:const Icon(Icons.switch_left),
              onPressed: () {
                DatePicker.showDatePicker(context,
                    showTitleActions: true, theme: const DatePickerTheme(), onChanged: (date) {}, onConfirm: (date) {
                  setState(() {
                    _currentDate = date;
                    if (titleYear != date.toString().substring(0, 4) || titleMonth != date.toString().substring(5, 7)) {
                      titleYear = date.toString().substring(0, 4);
                      titleMonth = date.toString().substring(5, 7);
                      loadData();
                    }
                  });
                }, currentTime: DateTime.now(), locale: LocaleType.zh);
              },
            )
          ],
        ),
      );
    }
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: Text(
            titleYear + '年' + titleMonth + '月',
            //'巡检日历',
          ),
          centerTitle: true,
          elevation: 0.2,
          brightness: Brightness.light,
          actions: <Widget>[
            IconButton(
              icon:const Icon(Icons.switch_left),
              onPressed: () {
                DatePicker.showDatePicker(context,
                    showTitleActions: true,
                    theme: const DatePickerTheme(),
                    maxTime: DateTime.now(),
                    onChanged: (date) {}, onConfirm: (date) {
                  setState(() {
                    _currentDate = date;
                    if (titleYear != date.toString().substring(0, 4) || titleMonth != date.toString().substring(5, 7)) {
                      titleYear = date.toString().substring(0, 4);
                      titleMonth = date.toString().substring(5, 7);
                      loadData();
                    }
                  });
                }, currentTime: DateTime.now(), locale: LocaleType.zh);
              },
            )
          ],
        ),
        body: ModalProgressHUD(
          child: Column(
            children: <Widget>[
              Container(
                  margin: const EdgeInsets.only(top: 20, bottom: 10),
                  child: GestureDetector(
                      onTap: () {
                        Navigator.push(context, MaterialPageRoute(builder: (context) {
                          return SelectRouteCalendarPage();
                        })).then((value) {
                          if (value != null) {
                            setState(() {
                              _routeName = value.name;
                              _routeId = value.value;
                            });
                            loadData();
                          }
                        });
                      },
                      child: Stack(
                        children: <Widget>[
                          Container(
                            child: Text(
                              _routeName,
                              style: const TextStyle(color: Colors.grey),
                            ),
                            alignment: Alignment.center,
                          ),
                          Container(
                            child: Icon(Icons.chevron_right, color: Theme.of(context).primaryColor),
                            alignment: Alignment.centerRight,
                          )
                        ],
                      ))),
              const Divider(
                height: 1,
              ),
              Expanded(
                child: initData.count == 0
                    ? Container(
                        width: 200,
                        child: Stack(
                          children: <Widget>[
                            AnimatedCircularChart(
                              size: const Size(260.0, 260.0),
                              initialChartData: <CircularStackEntry>[
                                const CircularStackEntry(
                                  <CircularSegmentEntry>[
                                    CircularSegmentEntry(
                                      100.0,
                                      Colors.grey,
                                      rankKey: 'completed',
                                    ),
                                  ],
                                ),
                              ],
                              chartType: CircularChartType.Radial,
                              edgeStyle: SegmentEdgeStyle.round,
                              holeRadius: 60,
                              percentageValues: true,
                            ),
                            Container(
                              padding: const EdgeInsets.only(top: 90),
                              child: Column(
                                children: <Widget>[
                                  Text(
                                    initData.count.toString(),
                                    style: const TextStyle(fontSize: 18),
                                  ),
                                  const Text('计划巡检')
                                ],
                              ),
                              alignment: Alignment.center,
                            )
                          ],
                        ),
                      )
                    : Container(
                        width: 300,
                        child: Stack(
                          children: <Widget>[
                            charts.PieChart(_createSampleData(initData),
                                animate: false,
                                defaultRenderer: charts.ArcRendererConfig(
                                    arcWidth: 20, arcRendererDecorators: [charts.ArcLabelDecorator()])),
                            Positioned(
                              top: 90,
                              left: 130,
                              child: Column(
                                children: <Widget>[
                                  Text(
                                    initData.count.toString(),
                                    style: const TextStyle(fontSize: 18),
                                  ),
                                  const Text('计划巡检')
                                ],
                              ),
                            )
                          ],
                        )),
                flex: 3,
              ),
              Expanded(
                child: Container(
                    margin: const EdgeInsets.symmetric(horizontal: 16.0),
                    padding: const EdgeInsets.only(top: 10),
                    child: _calendarCarouselNoHeader),
                flex: 5,
              )
            ],
          ),
          inAsyncCall: isAnimating,
          // demo of some additional parameters
          opacity: 0.7,
          progressIndicator: const CircularProgressIndicator(),
        ));
  }

  List<charts.Series<LinearSales, String>> _createSampleData(CalendarModel initData) {
    List<LinearSales> data = [];
    if (initData.unqualified > 0) {
      data.add(LinearSales('不合格', initData.unqualified, charts.MaterialPalette.red.shadeDefault));
    }

    if (initData.omission > 0) {
      data.add(LinearSales('漏检', initData.omission, charts.MaterialPalette.yellow.shadeDefault));
    }

    if (initData.qualified > 0) {
      data.add(LinearSales('合格', initData.qualified, charts.MaterialPalette.green.shadeDefault));
    }

    return [
      charts.Series<LinearSales, String>(
        id: 'Sales',
        colorFn: (LinearSales data, _) => data.color,
        domainFn: (LinearSales data, _) => data.year,
        measureFn: (LinearSales data, _) => data.sales,
        data: data,
        labelAccessorFn: (LinearSales row, _) => '${row.year}: ${row.sales}',
      )
    ];
  }
}

class LinearSales {
  final String year;
  final int sales;
  final charts.Color color;

  LinearSales(this.year, this.sales, this.color);
}
