import 'dart:async';
import 'dart:io';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutterappfuyou/code/YSMeans.dart';
import 'package:flutterappfuyou/code/base/YSTools.dart';
import 'YSCodeLogin.dart';
import 'YSLoginRelation.dart';
import 'base/YSNetWorking.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../YSPage.dart';
import 'YSRegister.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

class YSLogin extends StatefulWidget {
  final bool isCheck;
  const YSLogin({Key key, this.isCheck = false}) : super(key: key);
  @override
  _YSLoginState createState() => _YSLoginState();
}

class _YSLoginState extends State<YSLogin> {
  TextEditingController _userName = TextEditingController();
  TextEditingController _password = TextEditingController();
  bool _isObscure = true;
  bool _isAgree = false;
  StreamSubscription _listen;
  @override
  void initState() {
    _isAgree = widget.isCheck;
    super.initState();
    _getPrivate();
  }

  _weChatLogIn(code,{Map appleRequest}) async{
    Map request = {};
    String url = '';
    if(appleRequest!=null){
      // request['client_user'] = appleRequest['{user_id'];
      // request['identity_token'] = appleRequest['{identity_token'];
      request = appleRequest;
      url = 'sign/appInApple';
    }else{
      request = {'code':code};
      url = 'sign/appInWechat';
    }
    Map dict = await ysRequestHttp(context, requestType.post, url, request);
    if(dict!=null){
      Map data = dict['data'];
      if(data['is_new_user']==true){
        Navigator.of(context).push(
            CupertinoPageRoute(builder: (context){
              return YSLoginRelation2(bindCode: data['bind_code'],);
            })
        );
      }else{
        SharedPreferences  _perfer = await SharedPreferences.getInstance();
        _perfer.setString('token', data['token'].toString());
        toPage(context);
      }

    }
  }
  @override
  void dispose() {
    _userName.dispose();
    _password.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.dark,
      child: CupertinoPageScaffold(
        backgroundColor: Colors.white,
        child: GestureDetector(
          onTap: (){
            FocusScope.of(context).unfocus();
          },
          child: SingleChildScrollView(
            child: Container(
              width: ysWidth(context),
              height: ysHeight(context),
              child: Stack(
                children: [
                  SingleChildScrollView(
                    child: Column(
                      children: [
                        Container(
                          height: 120,
                          width: 120,
                          child: Image.asset('lib/images/fuyouicon.png'),
                          margin: EdgeInsets.only(top: ysTOP(context)+30,bottom: 30),
                        ),
                        Container(
                          width: MediaQuery.of(context).size.width-100,
                          margin: EdgeInsets.only(bottom: 10),
                          height: 50,
                          decoration: BoxDecoration(
                              border: Border(bottom: BorderSide(color: Color(0xFFD7D7D7),width: 0.5))
                          ),
                          child: CupertinoTextField(
                            style: TextStyle(fontSize: 12,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                            placeholderStyle: TextStyle(fontSize: 12,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                            placeholder: '请输入手机号码',
                            decoration: BoxDecoration(),
                            controller: _userName,
                            onChanged: (value){
                              setState(() {});
                            },
                            maxLength: 11,
                            keyboardType: TextInputType.phone,
                            prefix: Icon(Icons.edit,size: 20,color: Colors.pinkAccent,),
                            suffix: _userName.text.isNotEmpty?GestureDetector(
                              onTap: (){
                                _userName.text = '';
                              },
                              child: Container(
                                width: 15,
                                height: 15,
                                decoration: BoxDecoration(
                                    color: Colors.pinkAccent,
                                    borderRadius: BorderRadius.all(Radius.circular(50))
                                ),
                                child: Icon(Icons.close,size: 10,color: Colors.white,),
                              ),
                            ):Container(),
                          ),
                        ),
                        Container(
                          width: MediaQuery.of(context).size.width-100,
                          height: 50,
                          decoration: BoxDecoration(
                              border: Border(bottom: BorderSide(color: Color(0xFFD7D7D7),width: 0.5))
                          ),
                          child: CupertinoTextField(
                            style: TextStyle(fontSize: 12,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                            placeholderStyle: TextStyle(fontSize: 12,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                            placeholder: '请输入密码',
                            decoration: BoxDecoration(),
                            controller: _password,
                            obscureText: _isObscure,
                            prefix: Icon(Icons.lock_outline,size: 20,color: Colors.pinkAccent,),
                            suffix: GestureDetector(
                              onTap: (){
                                _isObscure = !_isObscure;
                                setState(() {});
                              },
                              child: Image.asset('lib/images/${_isObscure?'eye-slash':'eye'}.png',height: 20,width: 20,),
                            ),
                          ),
                        ),
                        Container(
                            height: 20,
                            width: MediaQuery.of(context).size.width-100,
                            margin: EdgeInsets.only(top: 10,bottom: 30),
                            alignment: Alignment.centerRight,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                GestureDetector(
                                  onTap: (){

                                  },
                                  child: Text('忘记密码？',style: TextStyle(fontSize: 12,color: Colors.transparent,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                ),
                                GestureDetector(
                                  onTap: (){
                                    FocusScope.of(context).unfocus();
                                    Navigator.of(context).push(
                                        CupertinoPageRoute(
                                            fullscreenDialog: true,
                                            builder: (context){
                                              return YSCodeLogin();
                                            }
                                        )
                                    );
                                  },
                                  child: Text('验证码登录',style: TextStyle(fontSize: 12,color: Colors.pinkAccent,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                )
                              ],
                            )
                        ),
                        CupertinoButton(
                          padding: EdgeInsets.all(0),
                          child: Container(
                            width: MediaQuery.of(context).size.width-100,
                            height: 40,
                            decoration: BoxDecoration(
                                color: Color(0xFFEA6C8F),
                                borderRadius: BorderRadius.all(Radius.circular(20))
                            ),
                            alignment: Alignment.center,
                            child: Text('登录',style: TextStyle(fontSize: 16,color: Colors.white,decoration: TextDecoration.none),),
                          ),
                          onPressed: (){
                            FocusScope.of(context).unfocus();
                            loginToPage();
                          },
                        ),
                        Container(height: 20,),
                        CupertinoButton(
                          padding: EdgeInsets.all(0),
                          child: Container(
                            width: MediaQuery.of(context).size.width-100,
                            child: Text('快速注册',style: TextStyle(fontSize: 16,color: Colors.grey,decoration: TextDecoration.none),),
                            alignment: Alignment.center,
                          ),
                          onPressed: (){
                            if(_listen!=null)_listen.pause();
                            FocusScope.of(context).unfocus();
                            Navigator.of(context).push(
                                CupertinoPageRoute(
                                    builder: (context){
                                      return YSRegister();
                                    }
                                )
                            ).then((value) {
                              _listen.resume();
                            });
                          },
                        ),
                        Container(
                            height: 20,
                            margin: EdgeInsets.only(top: 50,bottom: 20),
                            alignment: Alignment.center,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                Container(color: Color(0xFFD7D7D7),height: 0.5,width: 70,),
                                CupertinoButton(
                                  padding: EdgeInsets.all(0),
                                  child: Text('第三方登录',style: TextStyle(fontSize: 12,color: Color(0xFF292929),
                                      decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                  onPressed: (){

                                  },
                                ),
                                Container(color: Color(0xFFD7D7D7),height: 0.5,width: 70,),
                              ],
                            )
                        ),
                        Platform.isIOS?Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            YSAppleView(valueSetter: (value){
                              _weChatLogIn('',appleRequest: value);
                            },),
                            GestureDetector(
                              onTap: (){
                                _weChatLogin();
                              },
                              behavior: HitTestBehavior.opaque,
                              child: Container(
                                height: 50,
                                width: 50,
                                child: Image.asset('lib/images/911663724605wechat.jpg',fit: BoxFit.cover,),
                              ),
                            )
                          ],
                        ):GestureDetector(
                          onTap: (){
                            if(_isAgree==false){
                              ysFlutterToast(context,'请同意服务协议');
                              return;
                            }
                            _weChatLogin();
                          },
                          behavior: HitTestBehavior.opaque,
                          child: Container(
                            height: 50,
                            width: 50,
                            child: Image.asset('lib/images/911663724605wechat.jpg',fit: BoxFit.cover,),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Positioned(
                    bottom: 50,
                    child: Container(
                      width: ysWidth(context),
                      alignment: Alignment.center,
                      child: RichText(
                        text: TextSpan(
                            style: TextStyle(fontSize: 12,color: Color(0xFF292929),
                                decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                            children: [
                              WidgetSpan(
                                  alignment: PlaceholderAlignment.middle,
                                  child: GestureDetector(
                                    onTap: (){
                                      _isAgree = !_isAgree;
                                      setState(() {});
                                    },
                                    child: Icon(_isAgree==true?Icons.check_circle:Icons.radio_button_unchecked,
                                      size: 20,color: _isAgree==true?Colors.pinkAccent:Colors.grey,),
                                  )
                              ),
                              TextSpan(
                                  text: ' 我已阅读并同意'
                              ),
                              TextSpan(
                                text: '《服务条款》',
                                style: TextStyle(color: Colors.pinkAccent),
                                recognizer: TapGestureRecognizer()..onTap = () {
                                  showNegotiate1AlertDio(
                                    context,
                                    title: '服务条款',
                                    content: 'https://fy.niwoshenghuo.com/tool/service',

                                  );
                                },
                              ),
                              TextSpan(
                                  text: '及'
                              ),
                              TextSpan(
                                text: '《隐私条款》',
                                style: TextStyle(color: Colors.pinkAccent),
                                recognizer: TapGestureRecognizer()..onTap = () {
                                  showNegotiate1AlertDio(
                                    context,
                                    title: '隐私条款',
                                    content: 'https://fy.niwoshenghuo.com/tool/privacy',
                                  );
                                },
                              )
                            ]
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  _weChatLogin() async{
    fluwx.sendWeChatAuth(
        scope: 'snsapi_userinfo',
        state: 'wechat_sdk_demo_test'
    ).then((data) {
      print('data===========$data');
    });
  }

  _getPrivate() async{
    SharedPreferences preferences = await SharedPreferences.getInstance();
    if(preferences.get('first')==true){
      Future.delayed(Duration(seconds: 0)).then((value) {
        getVersionData(context);
      });
      _listen = fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
        if (res is fluwx.WeChatAuthResponse) {
          if(res.isSuccessful){
            print("code================== ${res.code}");
            _weChatLogIn(res.code);
          }
        }
      });
    }else{
      showNegotiate2AlertDio(
        context,
        title: '隐私政策',
        content: 'https://fy.niwoshenghuo.com/tool/privacy',
        agree: () async{
          preferences.setBool('first', true);
          Future.delayed(Duration(seconds: 0)).then((value) {
            getVersionData(context);
          });
          _listen = fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
            if (res is fluwx.WeChatAuthResponse) {
              if(res.isSuccessful){
                print("code================== ${res.code}");
                _weChatLogIn(res.code);
              }
            }
          });
        },
        disAgree: (){
          SystemNavigator.pop();
        }
      );
    }
  }

  loginToPage() async{
    if(_isAgree==false){
      ysFlutterToast(context,'请同意服务协议');
      return;
    }
    if(_userName.text.isEmpty){
      ysFlutterToast(context,'手机号码不能为空');
      return;
    }
    if(isChinaPhoneLegal(_userName.text)==false){
      ysFlutterToast(context,'手机号码格式不正确');
      return;
    }
    if(_password.text.isEmpty){
      ysFlutterToast(context,'密码不能为空');
      return;
    }
    if(_password.text.length<6){
      ysFlutterToast(context,'密码长度不能小于6位');
      return;
    }
    Map dict = await ysRequestHttp(context,requestType.post, 'sign/in', {'username':_userName.text,'password':_password.text});
    if(dict!=null){
      Map data = dict['data'];
      SharedPreferences  prefs = await SharedPreferences.getInstance();
      prefs.setString('token', data['token'].toString());
      toPage(context);
    }
  }
}

