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/utils/GetConfig.dart';
import 'package:base/view/my/contact/contact_page.dart';
import 'package:date_utils/date_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../model/Task/TaskContentInput.dart';
import '../../model/name_value.dart';

class TaskScreenPage extends StatefulWidget {
  final callback;

  TaskScreenPage(this.callback);

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

class _TaskScreenPageState extends State<TaskScreenPage> {
  String _timeName = '';
  int _timeId = -1;
  String _startDate = '';
  String _endDate = '';
  String _departmentName = '';
  int _departmentId = -1;
  String _contactName = '';
  int _contactId = -1;
  bool onlyMeCheck = false;
  bool _checkboxSelected = true;
  List<NameValue> departmentData = List();
  List<NameValue> timeSelect = [
    NameValue('所有', -1),
    NameValue('今天', 0),
    NameValue('昨天', 1),
    NameValue('本周', 2),
    NameValue('上周', 3),
    NameValue('本月', 4),
    NameValue('上月', 5)
  ];
  TaskContentInput filter = TaskContentInput();
  String theme = '';

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

  initConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        theme = preferences.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (theme.isEmpty) {
      return const Scaffold(body: Text(''));
    }

    return Scaffold(
      backgroundColor: Colors.white,
      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(_timeName),
                            ),
                            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: timeSelect.map((f) {
                              return Column(
                                children: <Widget>[
                                  SimpleDialogOption(
                                    child: Text(f.name),
                                    onPressed: () {
                                      Navigator.of(context).pop();
                                      setState(() {
                                        _timeName = f.name;
                                        _timeId = f.value;
                                      });
                                      getDateByTimeSelected(_timeId);
                                    },
                                  ),
                                  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(_startDate),
                            ),
                            Container(
                              alignment: Alignment.centerRight,
                              child:  Icon(
                                Icons.calendar_today_outlined,
                                color: Theme.of(context).primaryColor,
                              ),
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        DatePicker.showDateTimePicker(context,
                            showTitleActions: true,
                            theme: const DatePickerTheme(),
                            onChanged: (date) {}, onConfirm: (date) {
                          setState(() {
                            _startDate = date.toString().substring(0, 16);
                            if (_startDate.isNotEmpty) {
                              filter.startTime = _startDate;
                            }
                          });
                        }, 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: Icon(
                                Icons.calendar_today_outlined,
                                color: Theme.of(context).primaryColor,
                              ),
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        DatePicker.showDateTimePicker(context,
                            showTitleActions: true,
                            theme: const DatePickerTheme(),
                            onChanged: (date) {}, onConfirm: (date) {
                          setState(() {
                            _endDate = date.toString().substring(0, 16);
                            if (_endDate.isNotEmpty) {
                              filter.endTime = _endDate;
                            }
                          });
                        }, 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(_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) {
                          if (value != null) {
                            setState(() {
                              ChildInfo model = value;
                              _contactName = model.name;
                              _contactId = int.parse(model.id);
                            });
                          }
                        });
                      },
                    ),
                    const Padding(
                      padding: EdgeInsets.only(top: 15),
                    ),
                  ],
                ),
              )
            ],
          );
        },
      ),
      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 = '';
                      _endDate = '';
                      _departmentName = '';
                      _departmentId = -1;
                      _contactId = -1;
                      _contactName = '';
                      _timeName = '';
                      _timeId = -1;
                      _checkboxSelected = true;
                    });
                  },
                  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: () {
                  filter.departmentId = _departmentId;
                  filter.executorId = _contactId;
                  widget.callback(filter, _checkboxSelected);
                  Navigator.pop(context);
                },
                child: const Text('确定', style: TextStyle(color: Colors.white, fontSize: 18)),
              ),
            )
          ],
        )
      ],
      resizeToAvoidBottomPadding: false,
    );
  }

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

  void getDateByTimeSelected(int timeSelectId) {
    setState(() {
      if (timeSelectId == -1) return;
      if (timeSelectId == 0) {
        DateTime now = DateTime.now();
        filter.startTime = now.toString().substring(0, 10) + ' 00:00';
        filter.endTime = now.toString().substring(0, 16);
      } else if (timeSelectId == 1) {
        DateTime now = DateTime.now();
        filter.startTime = (now.add(const Duration(days: -1))).toString().substring(0, 10) + ' 00:00';
        filter.endTime = (now.add(const Duration(days: -1))).toString().substring(0, 10) + ' 23:59';
      } else if (timeSelectId == 2) {
        DateTime now = DateTime.now();
        DateTime firstDayOfWeek = Utils.firstDayOfWeek(now);
        filter.startTime = firstDayOfWeek.toString().substring(0, 10) + ' 00:00';
        filter.endTime = now.toString().substring(0, 16);
      } else if (timeSelectId == 3) {
        DateTime now = DateTime.now();
        DateTime firstDayOfWeek = Utils.firstDayOfWeek(now);
        filter.startTime = (firstDayOfWeek.add(const Duration(days: -7))).toString().substring(0, 10) + ' 00:00';
        filter.endTime = (firstDayOfWeek.add(const Duration(days: -1))).toString().substring(0, 10) + ' 23:59';
      } else if (timeSelectId == 4) {
        DateTime now = DateTime.now();
        filter.startTime = now.toString().substring(0, 8) + '01 00:00';
        filter.endTime = now.toString().substring(0, 16);
      } else if (timeSelectId == 5) {
        DateTime now = DateTime.now();
        DateTime now1 = DateTime.parse(now.toString().substring(0, 8) + '01');
        filter.startTime = (now1.add(const Duration(days: -1))).toString().substring(0, 8) + '01 00:00';
        filter.endTime = (now1.add(const Duration(days: -1))).toString().substring(0, 10) + ' 23:59';
      }
    });
  }
}
