import 'dart:async';

import 'package:base_app/common/common.dart';
import 'package:base_app/data/net/dio_util.dart';
import 'package:base_app/data/protocol/user_model.dart';
import 'package:base_app/data/repository/user_repository.dart';
import 'package:base_app/res/index.dart';
import 'package:base_app/res/styles.dart';
import 'package:base_app/ui/widgets/common/button/round_button_widget.dart';
import 'package:base_app/ui/widgets/common/dialog/loading_dialog_widget.dart';
import 'package:base_app/ui/widgets/login_page/login_item_widget.dart';
import 'package:base_app/utils/route_util.dart';
import 'package:base_app/utils/utils.dart';
import 'package:dio/dio.dart';
import 'package:fluintl/fluintl.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';

// 登录页Widget
class UserLoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new LoginPageState();
  }
}

// 登录页State
class LoginPageState extends State<UserLoginPage> {
  // 用户仓库（调用后台）
  UserRepository userRepository = new UserRepository();
  @override
  initState() {
    super.initState();
    // 显示loding窗口
    Future.delayed(Duration.zero, () {
      // 1. 显示loading窗
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return new LoadingDialog(
              text: "连接服务器中...",
            );
          });
      // 2. 连接后台服务器
      userRepository.baseConfig().then((result) {
        Navigator.pop(context); // 关闭弹窗
      }).catchError((onError) {
        Navigator.pop(context); // 关闭弹窗并提示错误信息
        showToast("连接服务器失败,请稍后退出重进~");
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      resizeToAvoidBottomInset: false,
      body: new Stack(
        children: <Widget>[
          new Image.asset(
            Utils.getImgPath("ic_login_bg"),
            width: double.infinity,
            height: double.infinity,
            fit: BoxFit.cover,
          ), // 背景图片
          new LoginBody()
        ],
      ),
    );
  }
}

// 登录BodyWidgegt
class LoginBody extends StatelessWidget {
  UserRepository userRepository = new UserRepository(); // 用户信息仓库

  TextEditingController _controllerPort = new TextEditingController(); // 地址
  TextEditingController _controllerName = new TextEditingController(); // 账户
  TextEditingController _controllerPwd = new TextEditingController(); // 密码

  FocusNode passwordFocusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    _controllerPort.text = SpUtil.getString(Constant.key_url);
    // UserModel userModel =
    //     SpUtil.getObj(BaseConstant.keyUserModel, (v) => UserModel.fromJson(v));
    // _controllerName.text = userModel?.username ?? "";
    MediaQueryData mq = MediaQuery.of(context);

    /// 登录
    void _userLogin() {
      String username = _controllerName.text.trim();
      String password = _controllerPwd.text.trim();
      if (username.isEmpty) {
        Utils.showSnackBar(context, "请输入用户名～");
        return;
      }
      if (password.isEmpty) {
        Utils.showSnackBar(context, "请输入密码～");
        return;
      }
      // 显示loading窗
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return new LoadingDialog(
              text: "登录中…",
            );
          });

      // 调后台验证登录
      LoginReq req = new LoginReq(username, password);
      userRepository.login(req).then((UserModel model) {
        LogUtil.e("LoginResp: ${model.toString()}");
        Navigator.pop(context);
        showToast("登录成功～");
        Timer timer = new Timer(new Duration(milliseconds: 500), () {
          RouteUtil.goMain(context);
        });
        // });
      }).catchError((error) {
        Navigator.pop(context);
        if (error is String) {
          // Utils.showSnackBar(context, error.toString());
          showToast(error.toString());
        } else {
          showToast("未知异常，请退出后重试");
          LogUtil.e("LoginResp error: ${error.toString()}");
        }
      });
    }

    void openUrlSetting(context) {
      // 打开服务器配置弹窗
      showCupertinoDialog(
          context: context,
          builder: (context) {
            return Container(
                child: CupertinoAlertDialog(
                    title: Text('请输入后台服务器地址'),
                    content: new Container(
                        padding: EdgeInsets.only(top: 10.0),
                        child: new CupertinoTextField(
                          controller: _controllerPort,
                          minLines: 1,
                          maxLines: 2,
                          placeholder: "如:http://127.0.0.01:8080/",
                        )),
                    actions: <Widget>[
                  CupertinoDialogAction(
                    onPressed: () {
                      // 放弃返回主页
                      Navigator.pop(context);
                    },
                    child: Text('取消'),
                  ),
                  CupertinoDialogAction(
                    onPressed: () {
                      String url = _controllerPort.text;
                      // 如果没有末尾斜杠加上斜杠
                      if (url[url.length - 1] != '/') {
                        url = url + '/';
                      }
                      SpUtil.putString(Constant.key_url, url);
                      Options options = DioUtil.getDefOptions();
                      options.baseUrl = url;
                      HttpConfig config = new HttpConfig(options: options);
                      DioUtil().setConfig(config);
                      Navigator.pop(context);
                      showToast("保存成功");
                      connectServer(); // 重新连接服务器
                    },
                    child: Text('保存'),
                  )
                ]));
          });
    }

    return new Column(
      children: <Widget>[
        new Container(
          height: mq.size.height / 3,
          alignment: Alignment.center,
          child: Text(
            AppConfig.appName,
            style: TextStyle(color: Colors.white, fontSize: 22),
          ),
        ), // 标题
        new Expanded(
            child: new Container(
          margin: EdgeInsets.only(left: 20, top: 15, right: 20),
          child: new Column(
            children: <Widget>[
              // 用户名输入框
              LoginItem(
                textInputAction: TextInputAction.next,
                onEditingComplete: () =>
                    FocusScope.of(context).requestFocus(passwordFocusNode),
                // autoFocus: true,
                keyboardType: TextInputType.emailAddress,
                controller: _controllerName,
                prefixIcon: Icons.person,
                hintText: IntlUtil.getString(context, Ids.user_name),
              ),
              Gaps.vGap15,
              // 密码输入框
              LoginItem(
                textInputAction: TextInputAction.done,
                focusNode: passwordFocusNode,
                controller: _controllerPwd,
                prefixIcon: Icons.lock,
                hasSuffixIcon: true,
                hintText: IntlUtil.getString(context, Ids.user_pwd),
              ),
              // 服务器配置
              new Container(
                padding: EdgeInsets.only(top: Dimens.gap_dp15),
                alignment: Alignment.centerRight,
                child: new InkWell(
                  child: new Text(
                    IntlUtil.getString(context, Ids.server_url_set),
                    style: new TextStyle(
                        color: Colours.gray_99, fontSize: Dimens.font_sp14),
                  ),
                  onTap: () {
                    openUrlSetting(context);
                  },
                ),
              ),
              new RoundButton(
                text: "登录",
                margin: EdgeInsets.only(top: 20),
                onPressed: () {
                  _userLogin();
                },
              ),
              Gaps.vGap15,
            ],
          ),
        )),
      ],
    );
  }

  // 连接服务器
  connectServer() {
    userRepository.baseConfig().then((result) {
      showToast("连接服务器成功");
    }).catchError((onError) {
      showToast("连接服务器失败,请确认服务器地址是否填写正确");
    });
  }
}
