import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:package_info/package_info.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'ChangePassword.dart';
import '../styles/colors.dart';
import 'dart:async';
import 'dart:ui';
import '../styles/totast.dart';
import 'loginFirst.dart';
import 'package:redux/redux.dart';
import 'package:flutter_redux/flutter_redux.dart';
import '../redux/AppState.dart';
import '../model/UserInfo.dart';
import '../net/HttpManager.dart';
import '../net/Result.dart';
import '../redux/UserRedux.dart';
import '../widget/Dialog.dart';
import '../widget/LinearButton.dart';
import '../utils/Utils.dart';

class Setting extends StatefulWidget {
  @override
  SettingState createState() => SettingState();
}

class SettingState extends State<Setting> {
  String version = '';
  bool receiveMsg = false;

  @override
  void initState() {
    super.initState();
    PackageInfo.fromPlatform().then((packageInfo) {
      setState(() {
        version = packageInfo.version;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 375, height: 667)..init(context);
    return StoreConnector<AppState, UserInfo>(
        converter: (Store store) => store.state.userInfo,
        builder: (context, userInfo) {
          return WillPopScope(
              key: Key('SettingsPage'),
              child: Scaffold(
                backgroundColor: Color(0xFF2E3049),
                appBar: AppBar(
                  // backgroundColor: PRIMARY_COLOR,
                  title: Text('系统设置'),
                  centerTitle: true,
                  elevation: 0,
                ),
                body: RefreshIndicator(
                  color: PRIMARY_COLOR,
                  backgroundColor: Colors.white,
                  displacement: 10,
                  onRefresh: () async {
                    await Future.delayed(const Duration(seconds: 1));
                    getUserInfo();
                  },
                  child: SizedBox.expand(
                    child: SingleChildScrollView(
                      physics: AlwaysScrollableScrollPhysics(),
                      child: Column(
                        children: <Widget>[
                          _sectionDivier(),
                          _section([
                            _cell('修改密码', ' ', onTap: () {
                               Navigator.push(context, CupertinoPageRoute(builder: (context) => ChangePassword()));
                            })
                          ]),
                          _sectionDivier(),
                          _section([
                            _cell(
                                '是否接收消息',
                                Switch(
                                    value: userInfo.noticeFlag,
                                    onChanged: (val) {
                                      updateUserInfo(userInfo, val ? 'Y' : 'N', 'noticeFlag');
                                    }),
                                showBorder: false),
                            _cell(
                                '是否查看房间提醒',
                                Switch(
                                    value: userInfo.remindFlag,
                                    onChanged: (val) {
                                      updateUserInfo(userInfo, val ? 'Y' : 'N', 'remindFlag');
                                    }),
                                showBorder: false)
                          ]),
                          _sectionDivier(),
                          _section([
                            _cell('检查更新', ' ', onTap: () {
                              getVersion(context);
                            }),
                            _cell('版本号', version, showBorder: false),
                          ]),
                          Container(
                            padding: EdgeInsets.fromLTRB(15, 60, 15, 30),
                            child: LinearButton(
                              btntext: '退出登录',
                              onTapHomeMenu: () async {
                                Toast.show(context, '退出成功', 1500, 'success');
                                Navigator.push(context, MaterialPageRoute(builder: (context) => LoginFirst()));
                                final prefs = await SharedPreferences.getInstance();
                                prefs.remove('token');
                                JPush jpush = JPush();
                                jpush.deleteAlias();
                                // Future.delayed(const Duration(seconds: 1), () {
                                //   StoreProvider.of<AppState>(context).dispatch(UpdateUserAction(null));
                                // });
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                // floatingActionButton: Container(
                //   height: 100,
                //   padding: EdgeInsets.symmetric(vertical: 30),
                //   child: Column(
                //     children: <Widget>[Text('Copyright©2019',style:TextStyle(color: Colors.white30,fontSize: 12)), Text('盛世明越(海南)科技有限公',style:TextStyle(color: Colors.white30,fontSize: 12))],
                //   ),
                // ),
                // floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
              ),
              onWillPop: () {
                Toast.hide();
                Navigator.pop(context);
                return Future.value(false);
              });
        });
  }

  Future<void> updateUserInfo(userInfo, value, key) async {
    if (Toast.preToast == null) {
      Toast.show(context, '加载中', -1, 'loading');
    }
    final Result res = await HttpManager.post('userInfo/update', data: {'id': userInfo.id, key: value});
    Toast.hide();
    if (res.success) {
      Toast.show(context, '修改成功', 1500, 'success');
      getUserInfo();
    } else {
      Toast.show(context, res.error, 1500, 'info');
    }
  }

  Future<void> getUserInfo() async {
    Result res = await HttpManager.get('userInfo/getUserInfo');
    if (res.success) {
      StoreProvider.of<AppState>(context).dispatch(UpdateUserAction(UserInfo.fromJson(res.data)));
    } else {}
  }

  Future<void> _chooseSex(BuildContext context) async {
    String sex = await showCupertinoModalPopup(
        context: context,
        builder: (BuildContext context) {
          return CupertinoActionSheet(
            title: Text('选择性别'),
            actions: <Widget>[
              CupertinoActionSheetAction(
                child: Text('男'),
                onPressed: () {
                  Navigator.pop(context, '男');
                },
              ),
              CupertinoActionSheetAction(
                child: Text('女'),
                onPressed: () {
                  Navigator.pop(context, '女');
                },
              ),
              CupertinoDialogAction(
                child: const Text('取消'),
                isDestructiveAction: true,
                onPressed: () {
                  Navigator.pop(context);
                },
              )
            ],
          );
        });
    if (sex != null) {
      updateUserInfo(StoreProvider.of<AppState>(context).state.userInfo, sex, 'sex');
    }
  }

  Future<void> _chooseBirthday(BuildContext context) async {
    UserInfo userInfo = StoreProvider.of<AppState>(context).state.userInfo;
    DateTime date = userInfo.birthday > 0 ? DateTime.fromMillisecondsSinceEpoch(userInfo.birthday) : DateTime.now();
    DateTime res = await showCupertinoModalPopup<DateTime>(
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: 216,
          color: CupertinoColors.white,
          child: Column(
            children: <Widget>[
              SizedBox(
                height: 44,
                child: Stack(
                  children: <Widget>[
                    Positioned(
                      left: 0,
                      top: 0,
                      bottom: 0,
                      child: CupertinoButton(
                        child: Text(
                          '取消',
                          style: TextStyle(color: PRIMARY_COLOR),
                        ),
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                      ),
                    ),
                    Positioned(
                      right: 0,
                      top: 0,
                      bottom: 0,
                      child: CupertinoButton(
                        child: Text(
                          '确定',
                          style: TextStyle(color: PRIMARY_COLOR),
                        ),
                        onPressed: () {
                          Navigator.of(context).pop(date);
                        },
                      ),
                    )
                  ],
                ),
              ),
              Expanded(
                flex: 1,
                child: DefaultTextStyle(
                  style: const TextStyle(
                    color: CupertinoColors.black,
                    fontSize: 22.0,
                  ),
                  child: GestureDetector(
                    // Blocks taps from propagating to the modal sheet and popping.
                    onTap: () {},
                    child: SafeArea(
                      top: false,
                      child: CupertinoDatePicker(
                        mode: CupertinoDatePickerMode.date,
                        initialDateTime: date,
                        onDateTimeChanged: (DateTime newDateTime) {
                          date = newDateTime;
                        },
                      ),
                    ),
                  ),
                ),
              )
            ],
          ),
        );
      },
    );
    if (res != null) {
      updateUserInfo(userInfo, res.millisecondsSinceEpoch, 'birthday');
    }
  }

  Widget _sectionDivier() {
    return Container(
      height: 10,
      color: Color(0xFF24263A),
    );
  }

  Widget _section(List<Widget> children) {
    return Container(
      color: Color(0xFF2E3049),
      child: Column(
        children: children,
      ),
    );
  }

  Widget _cell(String title, dynamic child, {String placeholder, void Function() onTap, bool showBorder = true}) {
    Widget secondChild;
    if (child == null || (child is String && child.isEmpty)) {
      secondChild = Text(
        placeholder ?? '',
        style: TextStyle(color: PLACEHOLDER_COLOR, fontSize: 13),
      );
    } else if (child is String) {
      secondChild = Text(
        child ?? '',
        style: TextStyle(color: Colors.white, fontSize: 15),
      );
    } else {
      secondChild = child;
    }
    return Container(
      height: 60,
      padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
      child: GestureDetector(
        onTap: onTap,
        child: Container(
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(
                color: Color(0xFF24263A),
                width: showBorder ? 1 : 0,
              ),
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Expanded(
                child: Text(
                  title ?? '',
                  style: TextStyle(color: Colors.white, fontSize: 14),
                ),
              ),
              secondChild,
              Padding(
                padding: EdgeInsets.only(left: 2),
                child: Image.asset(
                  'images/icon_inter.png',
                  width: 24,
                  height: 24,
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
