
import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:keyboard_avoider/keyboard_avoider.dart';
import 'package:twongCustomer/utils/index.dart';

import '../utils/http.dart';
import '../utils/cache.dart';
import '../routes/utils.dart';
import '../utils/loading.dart';
import '../utils/size_fit.dart';
import '../widgets/input_box.dart';
import '../utils/notification.dart';

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

class _LoginPageState extends State<LoginPage> {
  bool _loading = false;
  String username = "";
  String password = "";
  FocusNode userNode = new FocusNode();
  FocusNode passNode = new FocusNode();
  HttpClient http = new HttpClient();
  final ScrollController _scrollController = ScrollController();


  @override
  void initState() {
    super.initState();
    Http.init();
    Notifications.init(context);

    username = Cache.get("username");
    password = Cache.get("password");
    username = username == null ? "" : username;
    password = password == null ? "" : password;

    // if (Cache.get("autoLogin") != null) {
    //   Loading.show(context);
    //   Http.autoLogin().then((value) {
    //     // RouterUtils.toMain(context);
    //   }).catchError((err) {
    //     Loading.hide(context);
    //     Fluttertoast.showToast(msg: err.toString());
    //   });
    // }
  }

  @override
  Widget build(BuildContext context) {
    HYSizeFit.initialize(context);
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.only(top: 20.px),
              child: Row(
                children: [
                  Spacer(),
                  IconButton(icon: Icon(Icons.settings), onPressed: toSetting)
                ],
              ),
            ),
            Container(height: 80.px),
            Container(
              margin: EdgeInsets.only(left: 12.px, right: 12.px),
              child: InputBoxContainer(
                value: username,
                focusNode: userNode,
                hintText: "请输入您的账号",
                action: TextInputAction.next,
                onChange: (value) => username = value,
                submit: (value) {
                  FocusScope.of(context).requestFocus(passNode);
                },
                icon: Icons.account_circle,
              ),
            ),
            Container(
              margin: EdgeInsets.only(left: 12.px, right: 12.px),
              child: InputBoxContainer(
                password: true,
                value: password,
                focusNode: passNode,
                hintText: "请输入您的密码",
                action: TextInputAction.done,
                onChange: (value) => password = value,
                submit: (value) => _login(),
                icon: Icons.lock_sharp,
              ),
            ),
            _buildLoginBtn()
          ],
        ),
      ),
    );
  }

  Widget _buildLoginBtn() {
    if (_loading) return Center(
      child: CircularProgressIndicator(),
    );
    return Container(
        child: FlatButton(
          height: 40,
          minWidth: 300,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(20))
          ),
          textColor: Colors.white,
          color: Colors.blue,
          onPressed: _login,
          child: Text("登陆"),
        ));
  }

  toSetting () {
    // Routers.router().navigateTo(context, "setting");
    RouterUtils.toSetting(context);
  }

  _login () async {
    if(_loading) return;
    if(username.trim() == "" || password.trim() == "") {
      Fluttertoast.showToast(msg: "用户名密码不能为空!");
      return;
    }

    setState(() {
      _loading = true;
    });

    Loading.show(context);

    // HttpClient client = new HttpClient();
    // var httpRequest = await client.getUrl(Uri.parse("https://twongkefu.shotshock.shop/kefuinfo"));
    // HttpClientResponse response = await httpRequest.close();
    // response.transform(utf8.decoder).join().then((value){
    //   print(value);
    //   Loading.hide(context);
    //   setState(() {
    //     _loading = false;
    //   });
    // });

    // var dio = new Dio();
    // dio.post("https://google.com", data: FormData.fromMap({
    //   "username": username, "password": password
    // })).then((data) {
    //   print(data.data);
    //   setState(() {
    //     _loading = false;
    //   });
    //   Loading.hide(context);
    // });

    Http.login({ "username": username, "password": password}).then((data){
      Loading.hide(context);
      Cache.set("username", username);
      Cache.set("password", password);
      Cache.set("autoLogin", "true");

      RouterUtils.toMain(context);
    }).catchError((err) {
      print(err);
      Loading.hide(context);
      setState(() {
        _loading = false;
      });
      Fluttertoast.showToast(msg: err.toString());
    });
  }
}