import 'dart:async';

import 'package:fake_push/fake_push.dart';
import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/common/user_db.dart';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:liftmanager/internal/account/model/user_entity.dart';
import 'package:liftmanager/internal/work/work_router.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/routers/routers.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/widgets/my_button.dart';
import 'package:liftmanager/widgets/text_field.dart';

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _LoginState();
  }
}

class _LoginState extends State<LoginPage> {
  TextEditingController _nameController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();

  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  bool _isClick = false;
  bool _isWechatInstalled = false; //是否安装微信

  Push _push = Push();
  StreamSubscription<fluwx.WeChatAuthResponse> _wxlogin;
  bool checkXY = false; //是否勾选协议
  @override
  void initState() {
    super.initState();
    print("initState() {");
    _initFluwx();
    _nameController.addListener(_verify);
    _passwordController.addListener(_verify);
    _nameController.text = FlutterStars.SpUtil.getString(Constant.phone);
    checkXY = FlutterStars.SpUtil.getBool("xieyi");
    _wxlogin = fluwx.responseFromAuth.listen((res) {
      switch (res.errCode) {
        case -4:
          {
            //拒绝
            toasts("已拒绝");
            break;
          }
        case -2:
          {
            //取消
            toasts("已取消");
            break;
          }
        case 0:
          {
            if (res.type != 2) {
              print(res.code);
              ApiService(context: context).wxLogin(res.code, onSuccess: (res) {
                User().setCurrentUser(res);
                print("==============");
                _push.getDeviceToken().then((res) {
                  print(res);
//                      _push.bindAccount(account: phone);
                  print("==============");
                  FlutterStars.SpUtil.putString(
                      Constant.phone, _nameController.text);
                  NavigatorUtils.push(context, Routers.home, clearStack: true);
                });
              }, onError: (code, msg) {
                if (code == 0) {
//                      showAlert(context, "提示", msg, ""
//                          "去注册", (){
//                        Navigator.pop(context);
//                        NavigatorUtils.push(
//                            context, '${AccountRouter.registerPage}?authCode=${res.code}');
//                      },txt2:"取消",onPre2:(){
//                        Navigator.pop(context);
//                      });
                  showAlert(
                      context,
                      "提示",
                      msg,
                      ""
                          "确定", () {
                    Navigator.pop(context);
                  });
                }
              });
            }
            break;
          }
      }
    });
  }

  _initFluwx() async {
    await fluwx.registerWxApi(
        appId: "wx0f10e6386fb9969e",
        doOnAndroid: true,
        doOnIOS: true,
        universalLink: "https://www.edtyun.com/");
    var result = await fluwx.isWeChatInstalled();
    _isWechatInstalled = result;
    setState(() {});
  }

  void _verify() {
    String name = _nameController.text;
    String password = _passwordController.text;
    bool isClick = true;
    if (name.isEmpty || name.length < 11) {
      isClick = false;
    }
    if (password.isEmpty || password.length < 6) {
      isClick = false;
    }

    /// 状态不一样在刷新，避免重复不必要的setState
    if (isClick != _isClick) {
      setState(() {
        _isClick = isClick;
      });
    }
  }

  void custom_login(){
    showLoading(context, "正在登录...");
    ApiService(context: context).login("12345678910", Utils.generateMd5("123456789"),
        onSuccess: (UserEntity res) {
//          FlutterStars.SpUtil.putObject(Constant.user, res);
      dismissLoading(context);
      User().setCurrentUser(res);
      print("==============");
      FlutterStars.SpUtil.putString(Constant.phone, _nameController.text);
      NavigatorUtils.push(context, Routers.home, clearStack: true);
    }, onError: (code, errMsg) {
      toasts(errMsg);
      dismissLoading(context);
    });
  }

  void _login() {
    var phone = _nameController.text.toString().trim();
    var password = _passwordController.text.toString().trim();
    if (_nameController.text.length != 11) {
      toasts("请输入正确手机号码");
      return;
    }
    if (!checkXY) {
      toasts("请阅读并同意电梯管家协议");
      return;
    }
    showLoading(context, "正在登录...");
    ApiService(context: context).login(phone, Utils.generateMd5(password),
        onSuccess: (UserEntity res) {
//          FlutterStars.SpUtil.putObject(Constant.user, res);
      dismissLoading(context);
      FlutterStars.SpUtil.putBool("xieyi",true);
      User().setCurrentUser(res);
      print("==============");
      _push.getDeviceToken().then((res) {
        print(res);
        _push.bindAccount(account: phone);
        print("==============");
        
        FlutterStars.SpUtil.putString(Constant.phone, _nameController.text);
        // FlutterStars.SpUtil.putBool('isInitLink', false);
        NavigatorUtils.push(context, Routers.home, clearStack: true);

      });
    }, onError: (code, errMsg) {
      toasts(errMsg);
      dismissLoading(context);
    });
  }

  void _wechatLogin() {
    fluwx.sendWeChatAuth(
      scope: "snsapi_userinfo",
    );
  }

  @override
  void dispose() {
    super.dispose();
    _wxlogin.cancel();
  }

  @override
  Widget build(BuildContext context) {
    
    return Scaffold(
        backgroundColor: ThemeUtils.getTabsBg(context),
        appBar: MyAppBar(
          centerTitle: "登录",
          isBack: false,
        ),
        body: defaultTargetPlatform == TargetPlatform.iOS
            ? FormKeyboardActions(
                child: _buildBody(),
              )
            : SingleChildScrollView(
                child: _buildBody(),
              ));
  }

  _buildBody() {
    double width = MediaQuery.of(context).size.width;
    return Padding(
      padding: EdgeInsets.only(left: 34.0, right: 34.0, top: 27.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Center(
              child: LoadAssetImage(
            "login/icon_logo",
//              key: Key('${widget.keyName}_delete'),
            width: 111.5,
            height: 111.5,
          )),
          Gaps.vGap28,
          MyTextField(
            key: const Key('phone'),
            focusNode: _nodeText1,
            controller: _nameController,
            maxLength: 11,
            keyboardType: TextInputType.phone,
            hintText: "请输入手机号",
          ),
          Gaps.vGap8,
          MyTextField(
            key: const Key('password'),
            keyName: 'password',
            focusNode: _nodeText2,
            config: Utils.getKeyboardActionsConfig(
                context, [_nodeText1, _nodeText2]),
            isInputPwd: true,
            controller: _passwordController,
            keyboardType: TextInputType.visiblePassword,
            maxLength: 16,
            hintText: "请输入密码",
          ),
          Gaps.vGap16,
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              Container(
            child: GestureDetector(
              onTap: (){
                custom_login();
              },
              child: Text(
                                            "游客登录",
                                            textAlign: TextAlign.right,
                                            style: TextStyle(
                                              // fontSize: 14,
                                              color: Colours.app_main,
                                            ),
                                          ),
            )
          ),
            ],
          ),
          Gaps.vGap12,
          MyButton(
            key: const Key('login'),
            onPressed: _isClick ? _login : null,
            colors:
                _isClick ? null : [Colours.text_gray_c, Colours.text_gray_c],
            text: "登录",
          ),
          Gaps.vGap8,
          Row(
            children: <Widget>[
              Checkbox(
                activeColor: Colours.app_main,
                tristate: false,
                value: checkXY,
                onChanged: (bol) {
                  checkXY = bol;
                  setState(() {});
                },
              ),
              Expanded(
                flex: 1,
                child: Wrap(
                  children: <Widget>[
                    Text("阅读并同意电梯管家"),
                    GestureDetector(
                      onTap: (){
                        NavigatorUtils.push(context, "${WorkRouter.webview}?title="+Uri.encodeComponent("电梯管家协议")+"&url="+Uri.encodeComponent("http://dl.edtyun.com/xieyi.html"));
                      },
                      child: Text("用户协议",
                          style: TextStyle(
                            color: Colours.app_main,
                          )),
                    ),
                    Text("及相关"),
                    GestureDetector(
                      onTap: (){
                        NavigatorUtils.push(context, "${WorkRouter.webview}?title="+Uri.encodeComponent("电梯管家协议")+"&url="+Uri.encodeComponent("http://dl.edtyun.com/xieyi.html"));
                      },
                      child: Text("隐私声明",
                          style: TextStyle(
                            color: Colours.app_main,
                          )),
                    ),
                  ],
                ),
              )
            ],
          ),
          Gaps.vGap21,
          Row(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Container(
                  height: 20.0,
                  alignment: Alignment.centerRight,
                  child: GestureDetector(
                    child: Text(
                      '注册账号',
                      style: TextStyles.textDarkBlue14,
                    ),
                    onTap: () => NavigatorUtils.push(
                        context, "${AccountRouter.registerPage}?authCode="),
                  ),
                ),
              ),
              SizedBox(
                child: Container(
                  margin: EdgeInsets.fromLTRB(17.5, 0, 17.5, 0),
                  color: Color(0xFFDDDDDD),
                  width: 1.5,
                  height: 19,
                ),
              ),
              Expanded(
                flex: 1,
                child: Container(
                  height: 20.0,
                  alignment: Alignment.centerLeft,
                  child: GestureDetector(
                    child: Text(
                      '忘记密码',
                      style: TextStyles.textDarkBlue14,
                    ),
                    onTap: () => NavigatorUtils.push(
                        context, AccountRouter.resetPasswordPage),
                  ),
                ),
              ),
            ],
          ),
          Gaps.vGap28,
          Offstage(
              offstage: !_isWechatInstalled,
              child: Row(
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: SizedBox(
                      height: 1,
                      child: Container(
                        color: Color(0xFFDDDDDD),
                      ),
                    ),
                  ),
                  Container(
                      margin: EdgeInsets.fromLTRB(12, 0, 12, 0),
                      alignment: Alignment.center,
                      child: GestureDetector(
                        child: Text(
                          '更多登录方式',
                          style: TextStyles.textGray12,
                        ),
                        onTap: () => NavigatorUtils.push(
                            context, AccountRouter.registerPage),
                      )),
                  Expanded(
                    flex: 1,
                    child: SizedBox(
                      height: 1,
                      child: Container(
                        color: Color(0xFFDDDDDD),
                      ),
                    ),
                  ),
                ],
              )),
          Gaps.vGap22,
          Offstage(
            offstage: !_isWechatInstalled,
            child: MyButton(
                key: const Key('wxlogin'),
                onPressed: _wechatLogin,
                text: "微信登录",
                borderColor: Theme.of(context).textSelectionHandleColor,
                borderWidth: 0.5,
                textColor: Theme.of(context).textSelectionHandleColor,
                colors: [Color(0xFFFFFFFF), Color(0xFFFFFFFF)]),
          )
        ],
      ),
    );
  }
}
