import 'package:base/consts/color.dart';
import 'package:base/consts/external_assets_package_key.dart';
import 'package:base/model/ContactInfo.dart';
import 'package:base/services/company_services.dart';
import 'package:base/view/my/contact/contact_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../model/name_value.dart';
import '../../model/plan_list_input.dart';
import '../../view/plan_inspection/select_route.dart';

class FilterPage extends StatefulWidget {
  const FilterPage({this.inputFilter, this.callback});

  final callback;
  final PlanListInput inputFilter;

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

class _FilterPageState extends State<FilterPage> {
  String _startDate = "";
  String _endDate = "";
  String _departmentName = '';
  int _departmentId = 0;
  String _routeName = "";
  int _routeId = -1;
  String _contactName = "";
  int _contactId = -1;

  List<NameValue> departmentData = [];
  String theme = "";

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

    getDepartment();
    initConfig();
  }

  @override
  Widget build(BuildContext context) {
    if (this.theme.isEmpty) {
      return Scaffold(body: Text(""));
    }
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text(
          "计划筛选",
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
      ),
      body: ListView.builder(
        itemCount: 1,
        itemBuilder: (BuildContext context, int index) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(left: 10, right: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.only(top: 15),
                    ),
                    Text("开始时间"),
                    Padding(
                      padding: EdgeInsets.only(top: 5),
                    ),
                    GestureDetector(
                      child: Container(
                        height: 40,
                        // width: MediaQuery.of(context).size.width-20,
                        padding: EdgeInsets.only(bottom: 5),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                        ),
                        child: Stack(
                          children: <Widget>[
                            Container(
                              alignment: Alignment.centerLeft,
                              padding: EdgeInsets.only(left: 5),
                              child: Text(_startDate),
                            ),
                            Container(
                              alignment: Alignment.centerRight,
                              child: Icon(
                                Icons.calendar_today_outlined,
                                color: Theme.of(context).primaryColor,
                              ),
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        DatePicker.showDatePicker(context,
                            showTitleActions: true, theme: DatePickerTheme(), onChanged: (date) {}, onConfirm: (date) {
                          setState(() {
                            _startDate = date.toString().substring(0, 10) + ' 00:00:00';
                          });
                        },
                            currentTime: DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day),
                            locale: LocaleType.zh);
                      },
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 15),
                    ),
                    Text("结束时间"),
                    Padding(
                      padding: EdgeInsets.only(top: 5),
                    ),
                    GestureDetector(
                      child: Container(
                        height: 40,
                        // width: MediaQuery.of(context).size.width-20,
                        padding: EdgeInsets.only(bottom: 5),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                        ),
                        child: Stack(
                          children: <Widget>[
                            Container(
                              alignment: Alignment.centerLeft,
                              padding: EdgeInsets.only(left: 5),
                              child: Text(_endDate),
                            ),
                            Container(
                              alignment: Alignment.centerRight,
                              child: Icon(
                                Icons.calendar_today_outlined,
                                color: Theme.of(context).primaryColor,
                              ),
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        DatePicker.showDatePicker(context,
                            showTitleActions: true, theme: DatePickerTheme(), onChanged: (date) {}, onConfirm: (date) {
                          setState(() {
                            _endDate = date.toString().substring(0, 10) + ' 23:59:59';
                          });
                        },
                            currentTime:
                                DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, 23, 59, 59),
                            locale: LocaleType.zh);
                      },
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 15),
                    ),
                    Text("巡检部门"),
                    Padding(
                      padding: EdgeInsets.only(top: 5),
                    ),
                    GestureDetector(
                      child: Container(
                        height: 40,
                        //width: MediaQuery.of(context).size.width-20,
                        padding: EdgeInsets.only(bottom: 5),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                        ),
                        child: Stack(
                          children: <Widget>[
                            Container(
                              alignment: Alignment.centerLeft,
                              padding: EdgeInsets.only(left: 5),
                              child: Text(_departmentName ?? ''),
                            ),
                            Container(
                              alignment: Alignment.centerRight,
                              child: Icon(
                                Icons.keyboard_arrow_down,
                                size: 14,
                                color: Theme.of(context).primaryColor,
                              ),
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        showDialog<Null>(
                          context: context,
                          builder: (BuildContext context) {
                            return SimpleDialog(
                                children: departmentData.map((f) {
                              return Column(
                                children: <Widget>[
                                  SimpleDialogOption(
                                    child: Text(f.name),
                                    onPressed: () {
                                      Navigator.of(context).pop();
                                      setState(() {
                                        _departmentName = f.name;
                                        _departmentId = f.value;
                                      });
                                    },
                                  ),
                                  Divider(
                                    height: 1,
                                  )
                                ],
                              );
                            }).toList());
                          },
                        );
                      },
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 15),
                    ),
                    Text("巡检人员"),
                    Padding(
                      padding: EdgeInsets.only(top: 5),
                    ),
                    GestureDetector(
                      child: Container(
                        height: 40,
                        //width: MediaQuery.of(context).size.width-20,
                        padding: EdgeInsets.only(bottom: 5),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                        ),
                        child: Stack(
                          children: <Widget>[
                            Container(
                              alignment: Alignment.centerLeft,
                              padding: EdgeInsets.only(left: 5),
                              child: Text(_contactName ?? ''),
                            ),
                            Container(
                              alignment: Alignment.centerRight,
                              child: Icon(
                                Icons.keyboard_arrow_right,
                                size: 14,
                                color: Theme.of(context).primaryColor,
                              ),
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        Navigator.push(context, MaterialPageRoute(builder: (context) {
                          return ContactPage(
                            type: '1',
                          );
                        })).then((value) {
                          if (value != null) {
                            setState(() {
                              ChildInfo model = value;
                              _contactName = model.name;
                              _contactId = int.parse(model.id);
                            });
                          }
                        });
                      },
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 15),
                    ),
                    Text("巡检线路"),
                    Padding(
                      padding: EdgeInsets.only(top: 5),
                    ),
                    GestureDetector(
                      child: Container(
                        height: 40,
                        //width: MediaQuery.of(context).size.width-20,
                        padding: EdgeInsets.only(bottom: 5),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                        ),
                        child: Stack(
                          children: <Widget>[
                            Container(
                              alignment: Alignment.centerLeft,
                              padding: EdgeInsets.only(left: 5),
                              child: Text(_routeName),
                            ),
                            Container(
                              alignment: Alignment.centerRight,
                              child: Icon(
                                Icons.keyboard_arrow_right,
                                size: 14,
                                color: Theme.of(context).primaryColor,
                              ),
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        Navigator.push(context, MaterialPageRoute(builder: (context) {
                          return SelectRoutePage();
                        })).then((value) {
                          if (value != null) {
                            setState(() {
                              _routeName = value.name;
                              _routeId = value.value;
                            });
                          }
                        });
                      },
                    ),
                  ],
                ),
              )
            ],
          );
        },
      ),
      persistentFooterButtons: <Widget>[
        Row(
          children: <Widget>[
            Container(
              width: MediaQuery.of(context).size.width / 2 - 10,
              height: 50,
              color: Color.fromRGBO(242, 246, 249, 1),
              child: MaterialButton(
                  onPressed: () {
                    initConfig();
                  },
                  child: Text("重置", style: const TextStyle(color: Colors.black, fontSize: 18))),
            ),
            Container(
              width: MediaQuery.of(context).size.width / 2 - 10,
              height: 50,
              color: Theme.of(context).primaryColor,
              child: MaterialButton(
                onPressed: () {
                  PlanListInput filter = PlanListInput();
                  filter.startTime = _startDate;
                  filter.endTime = _endDate;
                  filter.departmentId = _departmentId;
                  filter.routeId = _routeId;
                  filter.userId = _contactId;
                  filter.bumen = _departmentName;
                  filter.renyuan = _contactName;
                  filter.luxian = _routeName;
                  widget.callback(filter);
                  Navigator.pop(context);
                },
                child: Text("确定", style: const TextStyle(color: Colors.white, fontSize: 18)),
              ),
            )
          ],
        )
      ],
      resizeToAvoidBottomPadding: false,
    );
  }

  getDepartment() {
    getDepartmentInfo().then((data) {
      setState(() {
        data.forEach((deartment) {
          departmentData.add(NameValue(deartment.name, num.tryParse(deartment.id)));
        });
      });
    });
  }

  initConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        this.theme = preferences.getString("theme") ?? KColorConstant.DEFAULT_COLOR;
        final myUserId = num.tryParse(preferences.get('user_id'));
        final name = preferences.get('real_name');
        _startDate = widget.inputFilter.startTime;
        _endDate = widget.inputFilter.endTime;
        if (widget.inputFilter.departmentId != -1) {
          _departmentName = widget.inputFilter.bumen;
          _departmentId = widget.inputFilter.departmentId;
        }
        if (widget.inputFilter.routeId != -1) {
          _routeName = widget.inputFilter.luxian;
          _routeId = widget.inputFilter.routeId;
        }
        if (widget.inputFilter.userId != -1) {
          _contactId = widget.inputFilter.userId;
          if (widget.inputFilter.userId != myUserId) {
            _contactName = widget.inputFilter.renyuan;
          } else {
            _contactName = name;
          }
        }
      });
    });
  }
}
