import 'package:chat/data/UserData.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/utils/screen.dart';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oktoast/oktoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wifi_info_plugin/wifi_info_plugin.dart';
import '../utils/OtherLogin.dart';
import 'LoginPage.dart';
import 'Registerpage.dart';
import 'package:fluwx_no_pay/fluwx_no_pay.dart' as fluwx;
import 'package:chat/data/constants.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:dio/dio.dart';
import 'dart:convert';
import 'package:chat/utils/TokenMgr.dart';

const RATE_NUM = 0.82;

class IndexPage extends StatefulWidget {
  IndexPage({Key key}) : super(key: key);

  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  bool isShow = false;
  var subscription = Connectivity();
  bool isOffline = false;
  var subStript;

  GlobalKey<ScaffoldState> registKey = new GlobalKey();

  @override
  void initState() {
    super.initState();
    fluwx.responseFromAuth.listen((data) {
      if (data.errCode == 0) {
        getLoginData(data.code);
      } else {}
    });

    // subscription.onConnectivityChanged.listen((ConnectivityResult result) {
    //   if (result == ConnectivityResult.none) {
    //     if (mounted) {
    //       setState(() {
    //         isOffline = true;
    //       });
    //     }
    //   } else {
    //     if (mounted) {
    //       setState(() {
    //         if (isOffline == true) {
    //           isOffline = false;
    //           autoLogin();
    //         }
    //       });
    //     }
    //   }
    // });

    autoLogin();
  }

  void autoLogin({showLoading: false}) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String autoLoginKey = prefs.getString(Constants.AutoLoginKey);
    if (autoLoginKey != null) {
      if (UserData().basicInfo.userId == null) {
        Future.delayed(Duration(seconds: 10), () {
          if (mounted) {
            setState(() {
              isOffline = true;
            });
          }
        });
        var data = {
          "key": autoLoginKey,
          "language": UserData().language,
        };

        data['sign'] = TokenMgr().getSign(data);

        print('~~~~~~~~~~~indexPage autologin ~~~~~~~~~~');
        Response res = await HttpUtil()
            .post('user/auto/login', data: data, isShowLoading: showLoading);
        var resData = res.data;
        if (resData['code'] == 0) {
          print('### 跳转 成功--');
          HttpUtil().changePage(context, resData);
        } else {
          isShow = true;
          setState(() {});
          showToast(resData['msg']);
        }
      } else {
        HttpUtil().changePage(context, {
          'data': {
            'userid': UserData().basicInfo.userId,
            'sex': UserData().basicInfo.sex,
            'mobile': UserData().mobile.toString(),
            'bindId': UserData().agentId
          }
        });
      }
    } else {
      print('### 跳转 失败  autoLoginKey null--');
      isShow = true;
      setState(() {});
    }
  }

  getLoginData(String code) async {
    Response f = await HttpUtil().getDataWX(
        'https://api.weixin.qq.com/sns/oauth2/access_token?appid=${Constants.AppId}&secret=${Constants.Secret}&code=$code&grant_type=authorization_code');
    var tokenData = json.decode(f.data);
    print(tokenData);
    if (tokenData['unionid'] == null || tokenData['unionid'] == '') {
      return;
    }
    var data = {
      "onlyid": tokenData['unionid'],
      "type": 0,
      "language": UserData().language,
    };

    data['sign'] = TokenMgr().getSign(data);
    data['openid'] = tokenData['openid'];
    data['lng'] = UserData().longitude;
    data['lat'] = UserData().latitude;

    try {
      WifiInfoWrapper wifiObject = await WifiInfoPlugin.wifiDetails;
      if (wifiObject != null) {
        data['routerName'] = wifiObject.ssid.replaceAll('"', '');
        data['mac'] = wifiObject.bssId;
      }
    } catch (e) {
      print(e);
    }

    Response res = await HttpUtil()
        .post('user/auth/login', data: data, isShowLoading: true);

    var resData = res.data;
    print(resData);
    if (resData['code'] != 0) {
      showToast(resData['msg']);
      return;
    }
    if (resData['data'] != null) {
      HttpUtil().changePage(Constants.getCurrentContext(), resData);
    }
  }

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

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 360, height: 744)..init(context);
    return new Scaffold(
        key: registKey,
        backgroundColor: Colors.white,
        body: SafeArea(
          child: Center(
            child: Container(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              child: _buildBody(),
            ),
          ),
        ));
  }

  Widget buildNetState() {
    return isOffline
        ? Container(
            margin: EdgeInsets.only(top: ScreenUtil().setHeight(450)),
            width: Screen.width,
            child: Column(
              children: <Widget>[
                Container(
                  child: Text(
                    I18n.of(context).net_error,
                    textScaleFactor: 1.0,
                    style: TextStyle(color: Color(0xFF8F8E8E), fontSize: 21.5),
                  ),
                ),
                InkWell(
                  onTap: () {
                    print('~~~~~~~~~~~indexPage click autologin ~~~~~~~~~~');

                    autoLogin(showLoading: true);
                  },
                  child: Container(
                    margin: EdgeInsets.only(top: 28),
                    padding:
                        EdgeInsets.symmetric(horizontal: 26, vertical: 9.5),
                    decoration: BoxDecoration(
                        border: Border.all(color: const Color(0xFF3875E9)),
                        borderRadius: BorderRadius.circular(8)),
                    child: Text(
                      I18n.of(context).re_connect,
                      textScaleFactor: 1.0,
                      style:
                          TextStyle(color: Color(0xFF3875E9), fontSize: 20.22),
                    ),
                  ),
                )
              ],
            ))
        : Container();
  }

  Widget _buildBody() {
    List<Widget> show = [
      _buildLoginButton(),
      _buildRegisterButton(),
      _buildOtherLogin(),
    ];
    List<Widget> hidden = [
      buildNetState(),
    ];
    return Stack(
      alignment: Alignment.center,
      children: <Widget>[
        Positioned(
            top: 0, child: isOffline ? _buildErrorBg() : _buildNormalBg()),
        Column(
          children: isShow ? show : hidden,
        )
      ],
    );
  }

  //构建底部第三方登陆
  Widget _buildOtherLogin() {
    return new Expanded(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          new Container(
            alignment: Alignment.bottomCenter,
            child: OtherLogin().builder(context),
          )
        ],
      ),
    );
  }

  //构建登陆按钮
  Widget _buildLoginButton() {
    Text text = fixedText(I18n.of(context).login,
        fontSize: Constants.ShaderButtonFontSize, color: Colors.white);
    return InkWell(
      onTap: () {
        Navigator.of(context).push(
          new MaterialPageRoute(
            builder: (context) {
              return LoginPage();
            },
          ),
        );
      },
      child: Container(
        margin: EdgeInsets.only(top: ScreenUtil().setHeight(460)),
        alignment: Alignment.center,
        height: Constants.ShaderButtonHeight,
        width: ScreenUtil.instance.setWidth(282.9),
        decoration: BoxDecoration(
            color: Constants.ConfrimButtonColor,
            //border: Border.all(color: const Color(0x803875E9)),
            borderRadius:
                BorderRadius.all(Radius.circular(Constants.BigButtonRadius))),
        child: text,
      ),
    );
  }

  //构建注册按钮
  Widget _buildRegisterButton() {
    Text text = fixedText(I18n.of(context).number_registration,
        fontSize: Constants.ShaderButtonFontSize,
        color: Constants.ConfrimButtonColor);
    return InkWell(
      onTap: () {
        Navigator.of(context).push(
          new MaterialPageRoute(
            builder: (context) {
              return RegisterPage(
                type: PageType.register.index,
              );
            },
          ),
        );
      },
      child: Container(
        margin: EdgeInsets.only(top: 30),
        alignment: Alignment.center,
        height: Constants.ShaderButtonHeight,
        width: ScreenUtil.instance.setWidth(282.9),
        decoration: BoxDecoration(
            border: Border.all(color: Constants.ConfrimButtonColor),
            borderRadius:
                BorderRadius.all(Radius.circular(Constants.BigButtonRadius))),
        child: text,
      ),
    );
  }

  // Widget _buildLogo() {
  //   return Container(
  //       alignment: Alignment.center,
  //       margin: EdgeInsets.only(top: ScreenUtil.instance.setHeight(53)),
  //       child: Image.asset(
  //         'assets/images/login/SY_logo.png',
  //         width: ScreenUtil.instance.setWidth(120.5),
  //       ));
  // }

  Widget _buildNormalBg() {
    return Container(
      margin: EdgeInsets.only(top: ScreenUtil.instance.setHeight(35)),
      child: Image.asset(
        'assets/images/login/SY_bg.png',
        width: Screen.width,
        //width: ScreenUtil.instance.setHeight(266),
      ),
    );
  }

  Widget _buildErrorBg() {
    return Container(
      margin: EdgeInsets.only(
          top: ScreenUtil.instance.setHeight(180),
          bottom: ScreenUtil.instance.setHeight(49)),
      child: Image.asset(
        'assets/images/net_error.png',
        width: ScreenUtil.instance.setWidth(150),
      ),
    );
  }
}
