import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_iot_ui/charts/annular_chart.dart';
import 'package:amos_iot_ui/listItem/list_view_item.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/consts/colors.dart';
import 'package:jcs_airport/consts/malfunction_report_const.dart';
import 'package:jcs_airport/consts/styles.dart';
import 'package:jcs_airport/entity/page.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/utils/convert_date.dart';
import 'package:jcs_airport/view/common/choose_person_malfunction_report.dart';
import 'package:jcs_airport/view/common/no_data.dart';
import 'package:jcs_airport/view/workBench/malfunctionReport/reportTask/report_task_detail.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class ReportTask extends StatefulWidget {
  final int tabIndex;

  const ReportTask(this.tabIndex);

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

class _ReportTaskState extends State with SingleTickerProviderStateMixin {
  int tabIndex;
  TabController _tabController;
  Map<String, String> filterData = {};
  Map choosePerson = {};

  _ReportTaskState(this.tabIndex);

  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: 4);
    _tabController.animateTo(tabIndex);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('报修任务'),
        bottom: TabContainer(
          color: Colors.white,
          child: Row(
            children: [
              Expanded(
                child: TabBar(
                  isScrollable: true,
                  labelColor: Theme.of(context).primaryColor,
                  unselectedLabelColor: Colors.black54,
                  indicatorColor:Theme.of(context).primaryColor,
                  tabs: const [
                    Tab(text: '全部'),
                    Tab(text: '待处理'),
                    Tab(text: '我接收'),
                    Tab(text: '我发起'),
                  ],
                  controller: _tabController,
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 10),
                child: Transform.translate(
                  offset: const Offset(0, -1),
                  child: InkWell(
                    child: Row(
                      children:  [
                        const Text(
                          '筛选',
                          style: TextStyle(color: Colors.black54, fontSize: 15),
                        ),
                        Icon(
                          Icons.filter_alt_outlined,
                          size: 15,
                          color: Theme.of(context).primaryColor,
                        )
                      ],
                    ),
                    onTap: () async {
                      var data = await Get.to(_ReportTaskFilter(filterData, choosePerson));
                      print(filterData);
                      if (data != null && data.isNotEmpty) {
                        choosePerson = data;
                        filterData['submissionName'] = choosePerson['bizOrgName'];
                        filterData['userId'] = choosePerson['amosOrgId'];
                      } else {
                        filterData.remove('submissionName');
                        filterData.remove('userId');
                      }
                      setState(() {});
                    },
                  ),
                ),
              )
            ],
          ),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          TaskList(MalfunctionReportConst.SELECY_ALL, filterData),
          TaskList(MalfunctionReportConst.SELECY_STATUS, filterData),
          TaskList(MalfunctionReportConst.SELECY_RECEIVE, filterData),
          TaskList(MalfunctionReportConst.SELECY_ISUBMIT, filterData),
        ],
      ),
    );
  }
}

class TaskList extends StatefulWidget {
  int type;
  Map<String, String> filterData;

  TaskList(this.type, this.filterData);

  @override
  _TaskListState createState() => _TaskListState();
}

class _TaskListState extends State<TaskList> {
  final List<Map<String, Object>> _data = [];
  final List<Map<String, Object>> _dataCount = [];
  final RefreshController _refreshController = RefreshController(initialRefresh: false);
  final AmosPage _page = AmosPage(current: 0);

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

  @override
  void didUpdateWidget(TaskList oldWidget) {
    super.didUpdateWidget(oldWidget);
    _initData();
  }

  @override
  Widget build(BuildContext context) {
    if (_data.isEmpty) {
      return Column(
        children: const [NoData()],
      );
    }
    return Column(
      children: [
        _dataCount.isNotEmpty
            ? Row(
                children: [
                  Expanded(
                    child: Card(
                      margin: const EdgeInsets.all(5),
                      child: SizedBox(
                          height: 200,
                          child: AnnularChart(_dataCount
                              .map((element) => SeriesData(
                                  element['cutrentStatusCount'], element['cutrentStatusName'], element['color']))
                              .toList())),
                    ),
                  )
                ],
              )
            : Container(),
        Expanded(
          child: SmartRefresher(
            enablePullDown: true,
            enablePullUp: true,
            controller: _refreshController,
            header: const WaterDropMaterialHeader(),
            footer: const ClassicFooter(),
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: ListView.builder(
              itemCount: _data.length,
              shrinkWrap: true,
              itemBuilder: (BuildContext context, int index) {
                Map<String, Object> item = _data[index];
                ListViewItemModel listViewItemModel = ListViewItemModel(
                    hasState: true,
                    stateColor: AMOSColors.malfunctionStatusColor(item['currentStatusName'].toString()),
                    title: item['failureEquipment'],
                    onclick: () async {
                      await Get.to(ReportTaskDetail(_data[index]['sequenceNbr']));
                    });
                return ListViewItem(
                  listViewItemModel: listViewItemModel,
                  contentWidget: Padding(
                    padding: const EdgeInsets.all(5.0),
                    child: Column(
                      children: [
                        Row(
                          children: [
                            const Text('报修人：'),
                            const SizedBox(
                              width: 5,
                            ),
                            Text(item['submissionName']),
                            const SizedBox(
                              width: 40,
                            ),
                            Text(
                              item['currentStatusName'].toString(),
                              style: TextStyle(
                                  color: AMOSColors.malfunctionStatusColor(item['currentStatusName'].toString())),
                            ),
                          ],
                        ),
                        const SizedBox(
                          height: 5,
                        ),
                        Row(
                          children: [
                            const Text('报修时间：'),
                            const SizedBox(
                              width: 5,
                            ),
                            Text(item['submissionTime']),
                          ],
                        )
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
        )
      ],
    );
  }

  void _onRefresh() {
    _page.current = 0;
    _data.clear();
    _getData();
    _refreshController.refreshCompleted();
  }

  void _onLoading() {
    _page.current += 1;
    _getData();
    _refreshController.loadComplete();
  }

  void _initData() {
    _page.current = 0;
    _data.clear();
    _dataCount.clear();

    Future.delayed(const Duration(milliseconds: 200), () {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      Future.wait([_getDataCount(), _getData()]).catchError((error) {
        ToastUtils.showToast(error?.toString());
      }).whenComplete(() => Get.back());
    });
  }

  Future<void> _getData() async {
    var data = await API.failureDetailsPage(_page.current, _page.size, widget.type, widget.filterData);
    if (data != null) {
      if ((data['records'] ?? []).length == 0) {
        _refreshController.loadNoData();
        return;
      }
      if (mounted) {
        setState(() {
          _data.addAll(data['records'].cast<Map<String, Object>>());
        });
      }
      _refreshController.refreshCompleted();
      _refreshController.loadComplete();
    }
  }

  Future<void> _getDataCount() async {
    var data = await API.failureDetailsListCount(widget.type, widget.filterData);
    if (data != null) {
      if (mounted) {
        setState(() {
          List<Map<String, Object>> castData = data.cast<Map<String, Object>>();
          castData.forEach((element) {
            if (int.parse(element['cutrentStatusCount'].toString()) > 0) {
              element['color'] = AMOSColors.malfunctionStatusColor(element['cutrentStatusName']);
              _dataCount.add(element);
            }
          });
        });
      }
    }
  }
}

///筛选页面
class _ReportTaskFilter extends StatefulWidget {
  final Map<String, String> filterData;
  Map choosePerson;

  _ReportTaskFilter(this.filterData, this.choosePerson);

  @override
  _ReportTaskFilterState createState() => _ReportTaskFilterState();
}

class _ReportTaskFilterState extends State<_ReportTaskFilter> {
  List status = [];
  List<String> dates = ['今天', '昨天', '本周', '上周', '本月', '上月'];
  TextEditingController statusController;
  TextEditingController dateController;

  @override
  void initState() {
    super.initState();
    statusController = TextEditingController(text: widget.filterData['currentStatusName'] ?? '');
    dateController = TextEditingController(text: widget.filterData['date'] ?? '');
    _getStatus();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('筛选'),
      ),
      body: Column(
        children: [
          Expanded(
            child: Form(
                child: Column(
              children: [
                const SizedBox(
                  height: 10,
                ),
                GestureDetector(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 15),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text('任务状态：'),
                        const SizedBox(
                          height: 5,
                        ),
                        TextField(
                          controller: statusController,
                          enabled: false,
                          style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                          decoration: InputDecoration(
                            filled: true,
                            fillColor: FormStyles.CONTENT_COLOR,
                            border: InputBorder.none,
                            suffixIcon: Transform.translate(
                              offset: const Offset(5, 0),
                              child: const Icon(
                                Icons.arrow_right,
                                color: Colors.black87,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  onTap: () {
                    buildStatusDialog(context);
                  },
                ),
                const SizedBox(
                  height: 10,
                ),
                GestureDetector(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 15),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text('提交时间段：'),
                        const SizedBox(
                          height: 5,
                        ),
                        TextField(
                          controller: dateController,
                          enabled: false,
                          style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                          decoration: InputDecoration(
                            filled: true,
                            fillColor: FormStyles.CONTENT_COLOR,
                            border: InputBorder.none,
                            suffixIcon: Transform.translate(
                              offset: const Offset(5, 0),
                              child: const Icon(
                                Icons.arrow_right,
                                color: Colors.black87,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  onTap: () {
                    buildDateDialog(context);
                  },
                ),
                const SizedBox(
                  height: 10,
                ),
                FormItem(
                    layout: FormLayout.vertical,
                    label: '提交人员:',
                    formfield: SelectFormNewPage(
                        value: widget.choosePerson['bizOrgName'] ?? '',
                        selectPage: ChoosePersonMalfunctionReport(
                          person: widget.choosePerson,
                        ),
                        onChanged: (val) {
                          if (val != null) {
                            setState(() {
                              widget.choosePerson = val;
                            });
                          }
                        })),
              ],
            )),
          ),
          Padding(
            padding: const EdgeInsets.all(15.0),
            child: Row(
              children: [
                Expanded(
                    child: FlatButton(
                  color: const Color.fromRGBO(242, 246, 249, 1),
                  height: 40,
                  onPressed: () {
                    setState(() {
                      widget.filterData.clear();
                      widget.choosePerson = {};
                      statusController.text = '';
                      dateController.text = '';
                    });
                  },
                  child: const Text(
                    '重置',
                    style: TextStyle(color: Colors.black87),
                  ),
                )),
                const SizedBox(
                  width: 5,
                ),
                Expanded(
                    child: FlatButton(
                  color: Theme.of(context).primaryColor,
                  height: 40,
                  onPressed: () {
                    Get.back(result: widget.choosePerson);
                  },
                  child: const Text(
                    '确定',
                    style: TextStyle(color: Colors.white),
                  ),
                )),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void buildDateDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return SimpleDialog(
            contentPadding: const EdgeInsets.symmetric(vertical: 10),
            children: dates
                .map((element) => Column(
                      children: [
                        SimpleDialogOption(
                          child: Center(child: Text(element)),
                          onPressed: () {
                            DateRange date = ConvertDate.convertDateTextToRealValue(element);
                            widget.filterData['startTime'] = date.startTime;
                            widget.filterData['endTime'] = date.endTime;
                            widget.filterData['date'] = element;
                            dateController.text = element;
                            Get.back();
                          },
                        ),
                        const Divider(
                          height: 1,
                        ),
                      ],
                    ))
                .toList(),
          );
        });
  }

  void buildStatusDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return SimpleDialog(
              contentPadding: const EdgeInsets.symmetric(vertical: 10),
              children: status
                  .map((element) => Column(
                        children: [
                          SimpleDialogOption(
                            child: Center(child: Text(element.keys.first ?? '')),
                            onPressed: () {
                              widget.filterData['currentStatus'] = element.values.first;
                              widget.filterData['currentStatusName'] = element.keys.first;
                              statusController.text = element.keys.first;
                              Get.back();
                            },
                          ),
                          const Divider(
                            height: 1,
                          ),
                        ],
                      ))
                  .toList());
        });
  }

  Future<void> _getStatus() async {
    var data = await API.failureDetailsListStatus();
    if (data != null) {
      setState(() {
        status.addAll(data);
      });
    }
  }
}
