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

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

  final callback;
  final InspectionRecordFilter inspectionRecordFilter;

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

class _FilterPageState extends State<FilterPage> {
  String _startDate = '';
  String _endDate = '';
  String _departmentName = '';
  int _departmentId = -1;
  String _planName = '';
  int _planId = -1;
  String _checkPoint = '';
  int _checkPointId = -1;
  String _contactName = '';
  int _contactId = -1;

  List<NameValue> departmentData = [];

  bool _checkboxSelected = false;
  String theme = 'blue';

  @override
  void initState() {
    super.initState();
    if (widget.inspectionRecordFilter != null) {
      _checkboxSelected = widget.inspectionRecordFilter.isOnlyMyInspection ?? false;
      _startDate = widget.inspectionRecordFilter.beginDate.substring(0, 10) ?? '';
      _endDate = widget.inspectionRecordFilter.endDate.substring(0, 10) ?? '';
      _departmentId = widget.inspectionRecordFilter.departmentId ?? -1;
      _planId = widget.inspectionRecordFilter.planTaskId ?? -1;
      _checkPointId = widget.inspectionRecordFilter.pointId ?? -1;
      _contactId = widget.inspectionRecordFilter.userId ?? -1;
      _departmentName = widget.inspectionRecordFilter.bumen ?? '';
      _planName = widget.inspectionRecordFilter.jihua ?? '';
      _contactName = widget.inspectionRecordFilter.renyuan ?? '';
      _checkPoint = widget.inspectionRecordFilter.dian ?? '';
    }
    getDepartment();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const 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>[
              CheckboxListTile(
                activeColor: Theme.of(context).primaryColor,
                  value: _checkboxSelected,
                  title: const Text('只显示我巡检的点'),
                  controlAffinity: ListTileControlAffinity.leading,
                  onChanged: (bool) {
                    setState(() {
                      _checkboxSelected = bool;
                    });
                  }),
              Container(
                padding: const EdgeInsets.only(left: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    const Padding(
                      padding: EdgeInsets.only(top: 15),
                    ),
                    const Text("开始时间"),
                    const Padding(
                      padding: EdgeInsets.only(top: 5),
                    ),
                    GestureDetector(
                      child: Container(
                        height: 40,
                        width: MediaQuery.of(context).size.width - 20,
                        padding: const EdgeInsets.only(bottom: 5),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                        ),
                        child: Stack(
                          children: <Widget>[
                            Container(
                              alignment: Alignment.centerLeft,
                              padding: const EdgeInsets.only(left: 5),
                              child: Text(_startDate),
                            ),
                            Container(
                              alignment: Alignment.centerRight,
                              child: Image.asset(
                                'assets/images/icons/calendar_' + theme + '.png',
                                package: ExternalAssetsPackageKey.BASE,
                                width: 18,
                                height: 18,
                              ),
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        DatePicker.showDateTimePicker(context,
                            showTitleActions: true,
                            theme: const DatePickerTheme(),
                            onChanged: (date) {}, onConfirm: (date) {
                          setState(() {
                            _startDate = date.toString().substring(0, 10);
                          });
                        }, currentTime: DateTime.now(), locale: LocaleType.zh);
                      },
                    ),
                    const Padding(
                      padding: EdgeInsets.only(top: 15),
                    ),
                    const Text("结束时间"),
                    const Padding(
                      padding: EdgeInsets.only(top: 5),
                    ),
                    GestureDetector(
                      child: Container(
                        height: 40,
                        width: MediaQuery.of(context).size.width - 20,
                        padding: const EdgeInsets.only(bottom: 5),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                        ),
                        child: Stack(
                          children: <Widget>[
                            Container(
                              alignment: Alignment.centerLeft,
                              padding: const EdgeInsets.only(left: 5),
                              child: Text(_endDate),
                            ),
                            Container(
                              alignment: Alignment.centerRight,
                              child: Image.asset(
                                'assets/images/icons/calendar_' + theme + '.png',
                                package: ExternalAssetsPackageKey.BASE,
                                width: 18,
                                height: 18,
                              ),
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        DatePicker.showDateTimePicker(context,
                            showTitleActions: true,
                            theme: const DatePickerTheme(),
                            onChanged: (date) {}, onConfirm: (date) {
                          setState(() {
                            _endDate = date.toString().substring(0, 10);
                          });
                        }, currentTime: DateTime.now(), locale: LocaleType.zh);
                      },
                    ),
                    const Padding(
                      padding: EdgeInsets.only(top: 15),
                    ),
                    const Text("巡检部门"),
                    const Padding(
                      padding: EdgeInsets.only(top: 5),
                    ),
                    GestureDetector(
                      child: Container(
                        height: 40,
                        width: MediaQuery.of(context).size.width - 20,
                        padding: const EdgeInsets.only(bottom: 5),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                        ),
                        child: Stack(
                          children: <Widget>[
                            Container(
                              alignment: Alignment.centerLeft,
                              padding: const 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;
                                      });
                                    },
                                  ),
                                  const Divider(
                                    height: 1,
                                  )
                                ],
                              );
                            }).toList());
                          },
                        );
                      },
                    ),
                    const Padding(
                      padding: EdgeInsets.only(top: 15),
                    ),
                    const Text("巡检计划"),
                    const Padding(
                      padding: EdgeInsets.only(top: 5),
                    ),
                    GestureDetector(
                      child: Container(
                        height: 40,
                        width: MediaQuery.of(context).size.width - 20,
                        padding: const EdgeInsets.only(bottom: 5),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                        ),
                        child: Stack(
                          children: <Widget>[
                            Container(
                              alignment: Alignment.centerLeft,
                              padding: const EdgeInsets.only(left: 5),
                              child: Text(_planName),
                            ),
                            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 SelectPlanPage();
                        })).then((value) {
                          setState(() {
                            _planName = value.name;
                            _planId = value.value;
                          });
                        });
                      },
                    ),
                    const Padding(
                      padding: EdgeInsets.only(top: 15),
                    ),
                    const Text("巡检人员"),
                    const Padding(
                      padding: EdgeInsets.only(top: 5),
                    ),
                    GestureDetector(
                      child: Container(
                        height: 40,
                        width: MediaQuery.of(context).size.width - 20,
                        padding: const EdgeInsets.only(bottom: 5),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                        ),
                        child: Stack(
                          children: <Widget>[
                            Container(
                              alignment: Alignment.centerLeft,
                              padding: const 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 const ContactPage(
                            type: '1',
                          );
                        })).then((value) {
                          setState(() {
                            if (value != null) {
                              ChildInfo model = value;
                              _contactName = model.name;
                              _contactId = int.parse(model.id);
                            } else {
                              _contactName = "";
                              _contactId = -1;
                            }
                          });
                        });
                      },
                    ),
                    const Padding(
                      padding: EdgeInsets.only(top: 15),
                    ),
                    const Text('巡检点'),
                    const Padding(
                      padding: EdgeInsets.only(top: 5),
                    ),
                    GestureDetector(
                      child: Container(
                        height: 40,
                        width: MediaQuery.of(context).size.width - 20,
                        padding: const EdgeInsets.only(bottom: 5),
                        decoration: BoxDecoration(
                          color: Colors.grey[100],
                        ),
                        child: Stack(
                          children: <Widget>[
                            Container(
                              alignment: Alignment.centerLeft,
                              padding: const EdgeInsets.only(left: 5),
                              child: Text(_checkPoint),
                            ),
                            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 SelectInspectionSpot();
                        })).then((value) {
                          setState(() {
                            _checkPoint = value.name;
                            _checkPointId = value.value;
                          });
                        });
                      },
                    ),
                  ],
                ),
              )
            ],
          );
        },
      ),
      persistentFooterButtons: <Widget>[
        Row(
          children: <Widget>[
            Container(
              width: (MediaQuery.of(context).size.width / 2) - 10,
              height: 50,
              color: const Color.fromRGBO(242, 246, 249, 1),
              child: MaterialButton(
                  onPressed: () {
                    setState(() {
                      _startDate = DateTime.now().toString().substring(0, 10);
                      _endDate = DateTime.now().toString().substring(0, 10);
                      _departmentName = "";
                      _departmentId = -1;
                      _planName = "";
                      _planId = -1;
                      _checkPoint = "";
                      _checkPointId = -1;
                      _contactName = "";
                      _contactId = -1;
                      _checkboxSelected = false;
                    });
                  },
                  child: const Text("重置", style: 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: () {
                  InspectionRecordFilter filter = InspectionRecordFilter();
                  filter.isOnlyMyInspection = _checkboxSelected;
                  filter.beginDate = _startDate;
                  filter.endDate = _endDate;
                  filter.departmentId = _departmentId;
                  filter.planTaskId = _planId;
                  filter.pointId = _checkPointId;
                  filter.userId = _contactId;
                  filter.bumen = _departmentName;
                  filter.jihua = _planName;
                  filter.renyuan = _contactName;
                  filter.dian = _checkPoint;
                  widget.callback(filter);
                  Navigator.pop(context);
                },
                child: const Text("确定", style: 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)));
        });
      });
    });
  }
}
