import 'dart:io';

import 'package:apple_sign_in/apple_sign_in.dart';
import 'package:chat/data/UserData.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/utils/screen.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_facebook_login/flutter_facebook_login.dart';
import 'package:fluwx_no_pay/fluwx_no_pay.dart' as fluwx;
import 'package:oktoast/oktoast.dart';
import 'package:wifi_info_plugin/wifi_info_plugin.dart';
import 'HttpUtil.dart';
import 'LoadingDialog.dart';
import 'TokenMgr.dart';
import 'apple_sign_in_btn.dart' as apple;

class OtherLogin {
  static final FacebookLogin facebookSignIn = new FacebookLogin();

  static bool isAvailableForAppleSignIn = false;

  ///是否支持苹果登录-ios苹果登录只支持ios13+手机

  Widget _buildSelection(context) {
    List<Widget> loginList = [];

    if(Platform.isAndroid ){
//      fluwx.isWeChatInstalled() 这里ios要判断是否已经安装
      loginList.add(InkWell(
        borderRadius: BorderRadius.all(Radius.circular(30.0)),
        child: new Image.asset(
          'assets/images/login/dly_icon2.png',
          height: 24,
        ),
        onTap: () {
          print('微信登陆');
          fluwx.sendAuth(
              scope: "snsapi_userinfo", state: "wechat_sdk_demo_test");
        },
      ));
    }
    loginList.add(InkWell(
      borderRadius: BorderRadius.all(Radius.circular(30.0)),
      child: new Image.asset(
        'assets/images/login/dly_icon3.png',
        height: 24,
      ),
      onTap: () async {
        print('facebook');
        facebookSignIn.loginBehavior = FacebookLoginBehavior.webViewOnly;
        final FacebookLoginResult result =
        await facebookSignIn.logIn(['email']);

        switch (result.status) {
          case FacebookLoginStatus.loggedIn:
            final FacebookAccessToken accessToken = result.accessToken;
            thirdLogin(context, accessToken.userId, 1);

            break;
          case FacebookLoginStatus.cancelledByUser:
            break;
          case FacebookLoginStatus.error:
            break;
        }
      },
    ));
    if (isAvailableForAppleSignIn) {
      loginList.add(apple.AppleSignInBtn(
        style: apple.ButtonStyle.black,
        type: apple.ButtonType.signIn,
        onPressed:  () async {
          print('apple sign in');
          showDialog(
              context: context,
              barrierDismissible: false,
              builder: (BuildContext context) {
                return LoadingDialog(
                  text: "",
                );
              });
          final AuthorizationResult result = await AppleSignIn.performRequests([
            AppleIdRequest(requestedScopes: [Scope.fullName])
          ]);
          Navigator.of(context).pop();
          switch (result.status) {
            case AuthorizationStatus.authorized:
              print('result.credential.user：${result.credential.user}');
              // Store user ID
              thirdLogin(context, result.credential.user, 2);
              break;
            case AuthorizationStatus.error:
              print("Sign in failed: ${result.error.localizedDescription}");
              break;
            case AuthorizationStatus.cancelled:
              print('User cancelled');
              break;
          }
        },
      ));
//      loginList.add(InkWell(
//        borderRadius: BorderRadius.all(Radius.circular(30.0)),
//        child: new Image.asset(
//          'assets/images/login/dly_icon4.png',
//          height: 24,
//        ),
//        onTap: () async {
//          print('apple sign in');
//          showDialog(
//              context: context,
//              barrierDismissible: false,
//              builder: (BuildContext context) {
//                return LoadingDialog(
//                  text: "",
//                );
//              });
//          final AuthorizationResult result = await AppleSignIn.performRequests([
//            AppleIdRequest(requestedScopes: [Scope.fullName])
//          ]);
//          Navigator.of(context).pop();
//          switch (result.status) {
//            case AuthorizationStatus.authorized:
//              print('result.credential.user：${result.credential.user}');
//              // Store user ID
//              thirdLogin(context, result.credential.user, 2);
//              break;
//            case AuthorizationStatus.error:
//              print("Sign in failed: ${result.error.localizedDescription}");
//              break;
//            case AuthorizationStatus.cancelled:
//              print('User cancelled');
//              break;
//          }
//        },
//      ));
    }

    return new Container(
      width: MediaQuery.of(context).size.width * 0.7,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: loginList,
      ),
    );
  }

  thirdLogin(BuildContext context, String onlyId, int type) async {
    var data = {
      "onlyid": onlyId,
      "type": type,
      "language": UserData().language,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['openid'] = onlyId;
    data['lng'] = UserData().longitude;
    data['lat'] = UserData().latitude;

    try {
      WifiInfoWrapper wifiObject = await WifiInfoPlugin.wifiDetails;
      if (wifiObject != null) {
        data['routerName'] = wifiObject.ssid;
        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('user/auth/login $resData');
    if (resData['code'] != 0) {
      showToast(resData['msg']);
      return;
    }
    if (resData['data'] != null) {
      HttpUtil().changePage(context, resData);
    }
  }

  Widget builder(context) {
    return Column(
      children: <Widget>[
        _buildBottomLabel(context),
        SizedBox(height: 10),
        _buildSelection(context),
        SizedBox(height: 20),
      ],
    );
  }

  Widget _buildBottomLabel(context) {
    return new Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        new SizedBox(
          width: MediaQuery.of(context).size.width * 0.3,
          child: Divider(
            height: 1.0,
            color: Colors.grey,
          ),
        ),
        fixedText(
          I18n.of(context).other_login,
          color: Colors.grey[500],
          fontSize: 11.34,
        ),
        new SizedBox(
          width: MediaQuery.of(context).size.width * 0.3,
          child: Divider(
            height: 1.0,
            color: Colors.grey,
          ),
        ),
      ],
    );
  }
}
