import 'dart:async';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutterappfuyou/code/YSBindInfo.dart';
import 'package:flutterappfuyou/code/base/YSNetWorking.dart';
import 'package:flutterappfuyou/code/version3/YSPerfectChapterInfo.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'YSMeans.dart';
import 'base/YSBase.dart';
import 'base/YSTools.dart';

class YSRegister extends StatefulWidget {
  @override
  _YSRegisterState createState() => _YSRegisterState();
}

class _YSRegisterState extends State<YSRegister> {
  TextEditingController _userName = TextEditingController();
  TextEditingController _password = TextEditingController();
  TextEditingController _code = TextEditingController();
  bool _isObscure = true;
  bool _isAgree = false;
  int _count = 60;
  Timer _timer;
  @override
  void dispose() {
    _userName.dispose();
    _password.dispose();
    _code.dispose();
    if(_timer.isActive)_timer.cancel();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Container(
          height: ysHeight(context),
          width: ysWidth(context),
          child: Stack(
            children: [
              SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      margin: EdgeInsets.only(top: MediaQuery.of(context).padding.top+50,left: 50),
                      child: GestureDetector(
                        child: Icon(Icons.arrow_back_ios,size: 25,color: Colors.pinkAccent,),
                        onTap: (){
                          Navigator.pop(context);
                        },
                      )
                    ),
                    Container(
                      padding: EdgeInsets.only(left: 60,top: 40,right: 60),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('注册',style: TextStyle(fontSize: 20,color: Color(0xFF282828)),),
                          Container(
                            margin: EdgeInsets.only(top: 20,bottom: 40),
                            child: Text('如果您还未有平台账号，请返回注册账号,请登录关联账号后，可以使用微信一键登录，快速进入应用。',
                              style: TextStyle(fontSize: 10,color: Color(0xFF707070)),),
                          ),
                          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,
                              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: _code,
                              prefix: Icon(Icons.security,size: 20,color: Colors.pinkAccent,),
                              keyboardType: TextInputType.number,
                              suffix: GestureDetector(
                                  onTap: (){
                                    if(_count==60){
                                      _getCode();
                                    }
                                  },
                                  child: Container(
                                    padding: EdgeInsets.only(top: 5,bottom: 5,left: 10,right: 10),
                                    child: Text(_count==60?'获取验证码':'$_count秒',style: TextStyle(fontSize: 10,color: Color(0xFFDE577D)),),
                                    decoration: BoxDecoration(
                                        border: Border.all(color: Color(0xFFDE577D),width: 0.5),
                                        borderRadius: BorderRadius.all(Radius.circular(50))
                                    ),
                                  )
                              ),
                            ),
                          ),
                          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,),
                              ),
                            ),
                          ),
                          GestureDetector(
                            child: Container(
                              margin: EdgeInsets.only(top: 60,bottom: 20),
                              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),),
                            ),
                            onTap: (){
                              FocusScope.of(context).unfocus();
                              _postRegisterData();
                            },
                          ),
                          Container(
                            height: 20,
                            width: MediaQuery.of(context).size.width-100,
                            alignment: Alignment.centerRight,
                            child: RichText(
                              text: TextSpan(
                                style: TextStyle(fontSize: 12,color: Color(0xFF292929),
                                    decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                                children: [
                                  TextSpan(
                                    text: '已有账号？'
                                  ),
                                  TextSpan(
                                    text: '立即登录',
                                    recognizer: TapGestureRecognizer()..onTap = () {
                                      Navigator.pop(context);
                                    },
                                    style: TextStyle(color: Colors.pinkAccent)
                                  ),
                                ]
                              ),
                            )
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              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',
                              );
                            },
                          )
                        ]
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  _getCode() async{
    if(_userName.text.isEmpty){
      ysFlutterToast(context,'手机号码不能为空');
      return;
    }
    Map dict = await ysRequestHttp(context,requestType.post, 'sign/sendSms', {'phone':_userName.text,'type':'register'});
    if(dict!=null){
      _timer =Timer.periodic(Duration(seconds: 1), (timer) {
        _count--;
        if(_count<=0){
          _count = 60;
          timer.cancel();
        }
        setState(() {});
      });
    }
  }

  _postRegisterData() async{
    FocusScope.of(context).unfocus();
    // Navigator.of(context).push(
    //     CupertinoPageRoute(
    //         builder: (context){
    //           return YSBindWeChat();
    //         }
    //     )
    // );
    // return;
    // Navigator.of(context).push(
    //     CupertinoPageRoute(
    //         builder: (context){//YSBindWeChat(userName: _userName.text,passWord: _password.text,)
    //           return YSPerfectChapterInfo(isFirst: true,);
    //         }
    //     )
    // );
    // return;
    if(_userName.text.isEmpty){
      ysFlutterToast(context,'手机号码不能为空');
      return;
    }
    if(isChinaPhoneLegal(_userName.text)==false){
      ysFlutterToast(context,'手机号码格式不正确');
      return;
    }
    if(_code.text.isEmpty){
      ysFlutterToast(context,'验证码不能为空');
      return;
    }
    if(_password.text.isEmpty){
      ysFlutterToast(context,'密码不能为空');
      return;
    }
    if(_password.text.length<6){
      ysFlutterToast(context,'密码长度不能小于6位');
      return;
    }
    if(_isAgree==false){
      ysFlutterToast(context,'请同意服务协议');
      return;
    }
    Map dict = await ysRequestHttp(context,requestType.post, 'sign/reg', {'username':_userName.text,'password':_password.text,'code':_code.text});
    if(dict!=null){
      Map data = dict['data'];
      Future<SharedPreferences> _prefer = SharedPreferences.getInstance();
      _prefer.then((value){
        value.setString('token', data['token'].toString());
      });
      Navigator.of(context).pushAndRemoveUntil(CupertinoPageRoute(builder: (context){
        return YSPerfectChapterInfo();
      }), (route) => false);
    }
  }
}


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

  @override
  _YSRegister2State createState() => _YSRegister2State();
}

class _YSRegister2State extends State<YSRegister2> {
  TextEditingController _phone = TextEditingController();
  TextEditingController _code = TextEditingController();
  TextEditingController _password = TextEditingController();
  bool _isAgree = false;
  int _count = 60;
  Timer _timer;
  @override
  void dispose() {
    if(_timer!=null){
      _timer.cancel();
    }
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ystitle: '注册',
      yschild: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              width: MediaQuery.of(context).size.width,
              margin: EdgeInsets.only(left: 40,top: 25,bottom: 10),
              child: Text('手机号',style: TextStyle(fontSize: 12,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
            ),
            Container(
                width: MediaQuery.of(context).size.width-50,
                margin: EdgeInsets.only(bottom: 10),
                padding: EdgeInsets.only(left: 10,right: 10),
                height: 40,
                decoration: BoxDecoration(
                    border: Border.all(color: Color(0xFFD7D7D7),width: 0.5),
                    borderRadius: BorderRadius.all(Radius.circular(20))
                ),
                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: _phone,
                  keyboardType: TextInputType.phone,
                  maxLength: 11,
                )
            ),
            Container(
              width: MediaQuery.of(context).size.width,
              margin: EdgeInsets.only(left: 40,top: 10,bottom: 10),
              child: Text('验证码',style: TextStyle(fontSize: 12,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
            ),
            Container(
                width: MediaQuery.of(context).size.width-50,
                margin: EdgeInsets.only(bottom: 10),
                padding: EdgeInsets.only(left: 10,right: 10),
                height: 40,
                decoration: BoxDecoration(
                    border: Border.all(color: Color(0xFFD7D7D7),width: 0.5),
                    borderRadius: BorderRadius.all(Radius.circular(20))
                ),
                child: Row(
                  children: [
                    Container(
                      width: (MediaQuery.of(context).size.width-50)*0.6,
                      height: 40,
                      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(),
                        keyboardType: TextInputType.number,
                        maxLength: 4,
                        controller: _code,
                      ),
                    ),
                    Container(height: 40,width: 1,color: Color(0xFFD7D7D7),),
                    CupertinoButton(
                      padding: EdgeInsets.all(0),
                      child: Container(
                        width: (MediaQuery.of(context).size.width-50)*0.4-22,
                        height: 40,
                        alignment: Alignment.center,
                        child: Text(_count==60?'获取验证码':'获取验证码\n$_count秒',style: TextStyle(fontSize: 14,color: Color(0xFF7F3344)),textAlign: TextAlign.center,),
                      ),
                      onPressed: _count==60?(){
                        if(_phone.text.isEmpty){
                          ysFlutterToast(context,'手机号码不能为空');
                          return;
                        }
                        _getCode();
                      }:null,
                    )
                  ],
                )
            ),
            Container(
              width: MediaQuery.of(context).size.width,
              margin: EdgeInsets.only(left: 40,top: 10,bottom: 10),
              child: Text('密码',style: TextStyle(fontSize: 12,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
            ),
            Container(
                width: MediaQuery.of(context).size.width-50,
                padding: EdgeInsets.only(left: 10,right: 10),
                height: 40,
                decoration: BoxDecoration(
                    border: Border.all(color: Color(0xFFD7D7D7),width: 0.5),
                    borderRadius: BorderRadius.all(Radius.circular(20))
                ),
                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(),
                  obscureText: true,
                  controller: _password,
                )
            ),
            Container(
              width: MediaQuery.of(context).size.width-50,
              margin: EdgeInsets.only(left: 20,bottom: 50),
              child: Row(
                children: [
                  CupertinoButton(
                    padding: EdgeInsets.all(0),
                    child: Row(
                      children: [
                        Icon(_isAgree==false?Icons.radio_button_unchecked:Icons.radio_button_checked,color: Color(0xFFDE577D),size: 15,),
                        Text(' 同意  ',style: TextStyle(fontSize: 12,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                      ],
                    ),
                    onPressed: (){
                      FocusScope.of(context).unfocus();
                      setState(() {
                        _isAgree = !_isAgree;
                      });
                    },
                  ),
                  CupertinoButton(
                    padding: EdgeInsets.all(0),
                    onPressed: () {

                    },
                    child: Text('服务协议',style: TextStyle(fontSize: 12,color: Color(0xFF8E1B3C),decoration: TextDecoration.underline,fontWeight: FontWeight.normal),),
                  )
                ],
              ),
            ),
            CupertinoButton(
              padding: EdgeInsets.all(0),
              child: Container(
                width: MediaQuery.of(context).size.width-150,
                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();
                _userRegister();
              },
            )
          ],
        ),
      ),
    );
  }


  _getCode() async{
    Map dict = await ysRequestHttp(context,requestType.post, 'sign/sendSms', {'phone':_phone.text,'type':'register'});
    if(dict!=null){
      _timer =Timer.periodic(Duration(seconds: 1), (timer) {
        _count--;
        if(_count<=0){
          _count = 60;
          timer.cancel();
        }
        setState(() {});
      });
    }
  }

  _userRegister() async{
    if(_phone.text.isEmpty){
      ysFlutterToast(context,'用户名不能为空');
      return;
    }
    if(_code.text.isEmpty){
      ysFlutterToast(context,'验证码不能为空');
      return;
    }
    if(_password.text.isEmpty){
      ysFlutterToast(context,'密码不能为空');
      return;
    }
    if(_password.text.length<6){
      ysFlutterToast(context,'密码长度不能小于6位');
      return;
    }
    if(_isAgree==false){
      ysFlutterToast(context,'请同意服务协议');
      return;
    }
    Map dict = await ysRequestHttp(context,requestType.post, 'sign/reg', {'username':_phone.text,'password':_password.text,'code':_code.text});
    if(dict!=null){
      Future<SharedPreferences> _prefer = SharedPreferences.getInstance();
      _prefer.then((value){
        value.setString('token', dict['data'].toString());
      });
      Navigator.of(context).push(
          CupertinoPageRoute(
              builder: (context){
                return YSMeans(isFirst: true,);
              }
          )
      );
    }
  }
}

