import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';

import '../../model/message/SubscribeInfo.dart';
import '../../model/name_value.dart';
import '../../services/myinfo_services.dart';
import 'lines_page.dart';

class SubscribePage extends StatefulWidget {
  @override
  _SubscribePageState createState() => _SubscribePageState();
}

class _SubscribePageState extends State<SubscribePage> {
  SubscribeInfo _subscribeInfo;
  List<String> selectedRoute = [];
  bool _before = false;
  bool _started = false;
  bool _after = false;
  final TextEditingController _beforecontroller = TextEditingController();
  final TextEditingController _startedcontroller = TextEditingController();
  final TextEditingController _aftercontroller = TextEditingController();
  String groupValue = '';
  String groupValue2 = '';
  bool isSavedPressed = false;
  bool isAnimating = false;
  String theme = '';

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

  Future<void> getData() async {
    await getSubscribe().then((data) {
      setState(() {
        _subscribeInfo = data;
        CheckPlan emailInfo;
        CheckPlan typeInfo;
        for (final f in _subscribeInfo.checkPlans) {
          if (f.msgType == 'checkType') {
            typeInfo = f;
          }
          if (f.msgType == 'checkEmail') {
            emailInfo = f;
          }
          if (f.msgType == 'planBegin') {
            _before = f.attribute1 == 'False' ? false : true;
            _beforecontroller.text = f.attribute2 ?? '';
          }
          if (f.msgType == 'planWarn') {
            _started = f.attribute1 == 'False' ? false : true;
            _startedcontroller.text = f.attribute2 ?? '';
          }
          if (f.msgType == 'planEnd') {
            _after = f.attribute1 == 'False' ? false : true;
            _aftercontroller.text = f.attribute2 ?? '';
          }
          if (f.msgType == 'route') {
            selectedRoute = f.attribute1 == null ? [] : f.attribute1.split(',');
          }
        }
        groupValue = typeInfo == null ? '' : typeInfo.attribute1;
        groupValue2 = emailInfo == null ? '' : emailInfo.attribute1;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_subscribeInfo == null) {
      return Scaffold(
        backgroundColor: const Color.fromRGBO(242, 246, 249, 1),
        appBar: AppBar(
          elevation: 0.2,
          title: const Text(
            '消息订阅',
          ),
        ),
      );
    }
    return Scaffold(
      backgroundColor: const Color.fromRGBO(242, 246, 249, 1),
      appBar: AppBar(
        elevation: 0.2,
        title: const Text(
          '消息订阅',
        ),
        actions: <Widget>[
          Container(
            width: 50,
            child: isSavedPressed
                ? GestureDetector(
                    child: const Text(
                      '保存',
                    ),
                    onTap: () {},
                  )
                : GestureDetector(
                    child: const Text(
                      '保存',
                    ),
                    onTap: () {
                      List<CheckPlan> _checkPlans = _subscribeInfo.checkPlans;

                      CheckPlan _planBegin =
                          _checkPlans.isNotEmpty ? _checkPlans.firstWhere((f) => f.msgType == 'planBegin') : null;
                      CheckPlan planBegin = CheckPlan.fromParams(
                          msgType: 'planBegin',
                          attribute1: _before ? 'True' : 'False',
                          attribute2: _beforecontroller.text,
                          id: _planBegin == null ? null : _planBegin.id);

                      CheckPlan _planWarn =
                          _checkPlans.isNotEmpty ? _checkPlans.firstWhere((f) => f.msgType == 'planWarn') : null;
                      CheckPlan planWarn = CheckPlan.fromParams(
                          msgType: 'planWarn',
                          attribute1: _started ? 'True' : 'False',
                          attribute2: _startedcontroller.text,
                          id: _planWarn == null ? null : _planWarn.id);

                      CheckPlan _planEnd = _checkPlans.isNotEmpty ? _checkPlans.firstWhere((f) => f.msgType == 'planEnd') : null;
                      CheckPlan planEnd = CheckPlan.fromParams(
                          msgType: 'planEnd',
                          attribute1: _after ? 'True' : 'False',
                          attribute2: _aftercontroller.text,
                          id: _planEnd == null ? null : _planEnd.id);

                      CheckPlan _checkType =
                          _checkPlans.isNotEmpty ? _checkPlans.firstWhere((f) => f.msgType == 'checkType') : null;
                      CheckPlan checkType = CheckPlan.fromParams(
                          msgType: 'checkType', attribute1: groupValue, id: _checkType == null ? null : _checkType.id);

                      CheckPlan _checkEmail =
                          _checkPlans.isNotEmpty ? _checkPlans.firstWhere((f) => f.msgType == 'checkEmail') : null;
                      CheckPlan checkEmail = CheckPlan.fromParams(
                          msgType: 'checkEmail', attribute1: groupValue2, id: _checkEmail == null ? null : _checkEmail.id);

                      CheckPlan _route = _checkPlans.isNotEmpty ? _checkPlans.firstWhere((f) => f.msgType == 'route') : null;
                      CheckPlan route = CheckPlan.fromParams(
                          msgType: 'route', attribute1: selectedRoute.join(','), id: _route == null ? null : _route.id);

                      List<CheckPlan> checkPlans = [];
                      checkPlans.add(planBegin);
                      checkPlans.add(planWarn);
                      checkPlans.add(planEnd);
                      checkPlans.add(checkType);
                      checkPlans.add(checkEmail);
                      checkPlans.add(route);
                      saveData(checkPlans);
                    },
                  ),
            alignment: Alignment.centerLeft,
          )
        ],
      ),
      body: ModalProgressHUD(
        child: ListView(
          children: <Widget>[
            //第一大块
            Container(
              color: Colors.white,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    margin: const EdgeInsets.only(left: 10.0, top: 10.0, bottom: 10.0),
                    height: 32.0,
                    child: const Text(
                      '巡检计划',
                      style: TextStyle(
                        fontSize: 18.0,
                        color: Colors.black,
                      ),
                    ),
                  ),
                  const Padding(
                    padding: EdgeInsets.only(left: 5.0, right: 5.0),
                    child: Divider(
                      height: 0.5,
                      color: Color(0xffd9d9d9),
                    ),
                  ),
                  Container(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(vertical: 8),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          Checkbox(
                              value: _before,
                              onChanged: (Value) {
                                setState(() {
                                  _before = Value;
                                });
                              }),
                          const Text('巡检计划开始前'),
                          Container(
                              margin: const EdgeInsets.symmetric(horizontal: 3),
                              color: Colors.grey[100],
                              width: 40.0,
                              alignment: Alignment.center,
                              child: TextField(
                                textAlign: TextAlign.center,
                                controller: _beforecontroller,
                                inputFormatters: <TextInputFormatter>[
                                  WhitelistingTextInputFormatter.digitsOnly,
                                ],
                                keyboardType: TextInputType.number,
                                decoration: const InputDecoration(
                                  border: InputBorder.none,
                                ),
                              )),
                          const Text('分钟，推送提醒'),
                        ],
                      ),
                    ),
                  ),
                  const Padding(
                    padding: EdgeInsets.only(left: 5.0, right: 5.0),
                    child: Divider(
                      height: 0.5,
                      color: Color(0xffd9d9d9),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 8),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Checkbox(
                            value: _started,
                            onChanged: (value) {
                              setState(() {
                                _started = value;
                              });
                            }),
                        const Text('巡检计划已开始'),
                        Container(
                            margin: const EdgeInsets.only(left: 3, right: 3),
                            color: Colors.grey[100],
                            width: 40.0,
                            child: TextField(
                              textAlign: TextAlign.center,
                              controller: _startedcontroller,
                              inputFormatters: <TextInputFormatter>[
                                WhitelistingTextInputFormatter.digitsOnly,
                              ],
                              keyboardType: TextInputType.number,
                              decoration: const InputDecoration(
                                border: InputBorder.none,
                              ),
                            )),
                        const Text('分钟未开始巡检，'),
                      ],
                    ),
                  ),
                  Container(
                    child: const Text('推送提醒'),
                    padding: const EdgeInsets.only(left: 50),
                  ),
                  const Padding(
                    padding: EdgeInsets.only(left: 5.0, right: 5.0),
                    child: Divider(
                      height: 0.5,
                      color: Color(0xffd9d9d9),
                    ),
                  ),
                  Container(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(vertical: 8),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          Checkbox(
                              value: _after,
                              onChanged: (Value) {
                                setState(() {
                                  _after = Value;
                                });
                              }),
                          const Text('巡检计划后'),
                          Container(
                              color: Colors.grey[100],
                              margin: const EdgeInsets.only(left: 3, right: 3),
                              width: 40.0,
                              child: TextField(
                                textAlign: TextAlign.center,
                                controller: _aftercontroller,
                                inputFormatters: <TextInputFormatter>[
                                  WhitelistingTextInputFormatter.digitsOnly,
                                ],
                                keyboardType: TextInputType.number,
                                decoration: const InputDecoration(
                                  border: InputBorder.none,
                                ),
                              )),
                          Container(
                            width: 180,
                            child: const Text('分钟有漏检点，推送提醒'),
                          ),
                        ],
                      ),
                    ),
                  ),
                  const Padding(
                    padding: EdgeInsets.only(left: 5.0, right: 5.0),
                    child: Divider(
                      height: 0.5,
                      color: Color(0xffd9d9d9),
                    ),
                  ),
                ],
              ),
            ),
            const Padding(
              padding: EdgeInsets.only(top: 10),
            ),
            //第二大块
            Container(
              color: Colors.white,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    margin: const EdgeInsets.only(left: 10.0, top: 10.0, bottom: 10.0),
                    height: 32.0,
                    child: const Text(
                      '巡检记录',
                      style: TextStyle(
                        fontSize: 18.0,
                        color: Colors.black,
                      ),
                    ),
                  ),
                  const Padding(
                    padding: EdgeInsets.only(left: 5.0, right: 5.0),
                    child: Divider(
                      height: 0.5,
                      color: Color(0xffd9d9d9),
                    ),
                  ),
                  Column(
                    children: _subscribeInfo.checks.map((f) {
                      return Column(
                        children: <Widget>[
                          Container(
                            child: RadioListTile(
                              value: f.code,
                              title: Text(f.message),
                              groupValue: groupValue,
                              onChanged: (val) {
                                setState(() {
                                  groupValue = val; // aaa
                                });
                              },
                            ),
                          ),
                          const Divider(
                            height: 1,
                          )
                        ],
                      );
                    }).toList(),
                  ),
                ],
              ),
            ),
            const Padding(
              padding: EdgeInsets.only(top: 10),
            ),
            //第三大块
            Container(
              color: Colors.white,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    margin: const EdgeInsets.only(left: 10.0, top: 10.0, bottom: 10.0),
                    height: 32.0,
                    child: const Text(
                      '邮件提醒',
                      style: TextStyle(
                        fontSize: 18.0,
                        color: Colors.black,
                      ),
                    ),
                  ),
                  const Padding(
                    padding: EdgeInsets.only(left: 5.0, right: 5.0),
                    child: Divider(
                      height: 0.5,
                      color: Color(0xffd9d9d9),
                    ),
                  ),
                  Column(
                    children: _subscribeInfo.emails.map((f) {
                      return Container(
                        child: Column(
                          children: <Widget>[
                            RadioListTile(
                              value: f.code,
                              title: Text(f.message),
                              groupValue: groupValue2,
                              onChanged: (val) {
                                // val 与 value 的类型对应
                                setState(() {
                                  groupValue2 = val; // aaa
                                });
                              },
                            ),
                            const Divider(
                              height: 1,
                            )
                          ],
                        ),
                      );
                    }).toList(),
                  ),
                ],
              ),
            ),
            const Padding(
              padding: EdgeInsets.only(top: 15),
            ),
            //关注的线路按钮
            TouchCallBack(
              child: Container(
                color: Colors.white,
                height: 50.0,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                      margin: const EdgeInsets.only(left: 10.0, top: 10.0, bottom: 10.0),
                      padding: const EdgeInsets.symmetric(horizontal: 10),
                      height: 32.0,
                      child: const Text(
                        '我关注的路线',
                        style: TextStyle(
                          fontSize: 17.0,
                          color: Colors.black,
                        ),
                      ),
                    ),
                    Container(
                        width: 50.0,
                        height: 32.0,
                        child: Icon(
                          Icons.arrow_forward_ios,
                          color: Theme.of(context).primaryColor,
                          size: 20,
                        ))
                  ],
                ),
              ),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => LinesPage(selectedRoute)),
                ).then((val) {
                  setState(() {
                    List<NameValue> _selectedRoutes = val;
                    selectedRoute = [];
                    if (_selectedRoutes != null && _selectedRoutes.isNotEmpty) {
                      _selectedRoutes.forEach((f) {
                        selectedRoute.add(f.value.toString());
                      });
                    }
                  });
                });
              },
            )
          ],
        ),
        inAsyncCall: isAnimating,
        opacity: 0.7,
        progressIndicator: const CircularProgressIndicator(),
      ),
    );
  }

  void saveData(List<CheckPlan> checkPlans) {
    setState(() {
      isSavedPressed = true;
      isAnimating = true;
    });
    saveSubscribe(checkPlans).then((data) {
      setState(() {
        isSavedPressed = false;
        isAnimating = false;
      });
      if (data) {
        showAlertMessageOnly('数据保存成功！');
      } else {
        showAlertMessageOnly('数据保存失败！');
      }
    });
  }

  Future<void> showAlertMessageOnly(String text) async {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) => AlertDialog(
                title: Column(
                  children: const <Widget>[
                    Text('信息'),
                    Divider(height: 2),
                  ],
                ),
                content: Text(text),
                actions: <Widget>[
                  FlatButton(
                    child: const Text('关闭', style: TextStyle(fontSize: 20, color: Colors.grey)),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ])).then((v) {
      return v;
    });
  }
}
