import 'package:flutter/material.dart';
import 'package:flutter_tzh/base/YSTabBar.dart';
import 'package:flutter_tzh/home/view/YSInputView.dart';
import 'package:flutter_tzh/tool/YSNetWork.dart';
import 'package:flutter_tzh/tool/YSTools.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

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

class YSLoginState extends State<YSLogin> {
  String _userName = '';
  String _password = '';
  bool _isCheck = true;
  late SharedPreferences _prefs;
  int _refresh = 0;
  @override
  void initState() {
    networkDelay((){
      _getUserPass();
    });
    super.initState();
  }
  _getUserPass() async{
    _prefs = await SharedPreferences.getInstance();
    _userName = _prefs.getString('userName')??'';
    _password = _prefs.getString('password')??'';
    _refresh = 1;
    setState(() {});
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF23262B),
      body: SingleChildScrollView(
        child: Container(
          width: ysWidth(context),
          height: ysHeight(context),
          padding: EdgeInsets.only(top: ysTOP(context)+hsp(10)),
          child: _refresh==0?Container():Column(
            children: [
              Container(
                height: hsp(150),
                width: ysWidth(context)-hsp(40),
                alignment: Alignment.center,
                decoration: const BoxDecoration(image: DecorationImage(image: AssetImage('images/login_bg.png'))),
                child: Text('用户登陆',style: TextStyle(fontSize: zsp(24),color: Colors.white),),
              ),
              Padding(
                padding: EdgeInsets.only(left: hsp(20),right: hsp(20),top: hsp(10)),
                child: YSInputView3(title: '账号', valueSetter:(value){
                  _userName = value;
                },value: _userName,),
              ),
              Padding(
                padding: EdgeInsets.only(bottom: hsp(20),left: hsp(20),right: hsp(20),top: hsp(12)),
                child: YSInputView3(title: '密码', valueSetter:(value){
                  _password = value;
                },isSec: true,value: _password,),
              ),
              Padding(
                padding: EdgeInsets.only(left: hsp(20),right: hsp(20)),
                child: GestureDetector(
                  onTap: (){
                    _isCheck = !_isCheck;
                    setState(() {});
                  },
                  behavior: HitTestBehavior.opaque,
                  child: Row(
                    children: [
                      Image.asset('images/${_isCheck?'Check_login2':'Check_login'}.png',height: hsp(40),width: hsp(40),),
                      Text('记住密码',style: TextStyle(fontSize: zsp(12),color: const Color(0xFFACB5C5)),)
                    ],
                  ),
                ),
              ),
              GestureDetector(
                onTap: () async{
                  FocusScope.of(context).unfocus();
                  if(_userName.isEmpty){
                    ysFlutterToast('请输入账号');
                    return;
                  }
                  if(_password.isEmpty){
                    ysFlutterToast('请输入密码');
                    return;
                  }
                  Map request = {};
                  request['account'] = _userName;
                  request['password'] = _password;
                  // LogUtil.d(request);
                  // return;
                  YSNetWork.ysRequestHttp(context, type: RequestType.post, api: '/auth/sampLogin', parameter: request, successSetter: (dict) async{
                    Map data = dict['data'];
                    _prefs.setString('token', data['token'].toString());
                    if(_isCheck){
                      _prefs.setString('userName', _userName);
                      _prefs.setString('password', _password);
                    }else{
                      _prefs.remove('userName');
                      _prefs.remove('password');
                    }
                    if(mounted){
                      Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context){
                        return const YSTabBar();
                      }), (route) => false);
                    }
                  },isLoading: true);
                },
                child: Container(
                  height: hsp(50),
                  width: ysWidth(context)-hsp(100),
                  margin: EdgeInsets.only(top: hsp(100)),
                  decoration: const BoxDecoration(
                    color: Color(0xFF09A171),
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                    gradient: LinearGradient(colors: [Color(0xFF7ADF8D),Color(0xFF8FF0A0)])
                  ),
                  alignment: Alignment.center,
                  child: const Text('登录',style: TextStyle(fontSize: 18,color: Colors.white,fontWeight: FontWeight.bold),),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

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

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

class YSLogin2State extends State<YSLogin2> {
  String _codeImage = '';
  String _userName = '';
  String _password = '';
  String _code = '';
  int _updateIndex = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF23262B),
      body: SingleChildScrollView(
        child: Container(
          width: ysWidth(context),
          height: ysHeight(context),
          padding: EdgeInsets.only(top: ysTOP(context)+hsp(10)),
          child: Column(
            children: [
              Container(
                height: hsp(150),
                width: ysWidth(context)-hsp(40),
                alignment: Alignment.center,
                decoration: const BoxDecoration(image: DecorationImage(image: AssetImage('images/login_bg.png'))),
                child: Text('用户登陆',style: TextStyle(fontSize: zsp(24),color: Colors.white),),
              ),
              Padding(
                padding: EdgeInsets.only(left: hsp(50),right: hsp(50),top: hsp(50)),
                child: YSInputView3(title: '账号', valueSetter:(value){
                  _userName = value;
                }),
              ),
              Padding(
                padding: EdgeInsets.only(bottom: hsp(20),left: hsp(50),right: hsp(50),top: hsp(20)),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    SizedBox(
                      width: ysWidth(context)-hsp(200),
                      child: YSInputView3(title: '验证码', valueSetter:(value){
                        _code = value;
                      }),
                    ),
                    GestureDetector(
                      onTap: () async{
                        if(_userName.isEmpty){
                          ysFlutterToast('请输入账号');
                          return;
                        }
                        _updateIndex++;
                        _codeImage = '$base/picture/code?account=$_userName&index=$_updateIndex';
                        setState(() {});
                      },
                      behavior: HitTestBehavior.opaque,
                      child: Container(
                        width: hsp(90),
                        height: hsp(65),
                        margin: const EdgeInsets.only(left: 10),
                        decoration: BoxDecoration(
                          color: const Color(0xFF1A1C1F),
                          border: Border.all(color: const Color(0xFF3E434E),width: hsp(1)),
                          borderRadius: const BorderRadius.all(Radius.circular(3))
                        ),
                        alignment: Alignment.center,
                        child: _codeImage.isNotEmpty?Image.network(
                          _codeImage,
                          fit: BoxFit.fill,
                          width: double.infinity,
                          height: double.infinity,
                          errorBuilder: (context,value,stackTrace){
                            return Text('获取失败',style: TextStyle(fontSize: zsp(14),color: Colors.red),);
                          },
                        ):Text('获取验证码',style: TextStyle(fontSize: zsp(14),color: Colors.white),),
                      ),
                    )
                  ],
                ),
              ),
              Padding(
                padding: EdgeInsets.only(bottom: hsp(20),left: hsp(50),right: hsp(50)),
                child: YSInputView3(title: '密码', valueSetter:(value){
                  _password = value;
                },isSec: true,),
              ),
              GestureDetector(
                onTap: () async{
                  FocusScope.of(context).unfocus();
                  if(_userName.isEmpty){
                    ysFlutterToast('请输入账号');
                    return;
                  }
                  if(_code.isEmpty){
                    ysFlutterToast('请输入验证码');
                    return;
                  }
                  if(_password.isEmpty){
                    ysFlutterToast('请输入密码');
                    return;
                  }
                  Map request = {};
                  request['account'] = _userName;
                  request['code'] = _code;
                  request['password'] = _password;
                  // LogUtil.d(request);
                  // return;
                  YSNetWork.ysRequestHttp(context, type: RequestType.post, api: '/auth/login', parameter: request, successSetter: (dict) async{
                    Map data = dict['data'];
                    SharedPreferences  prefs = await SharedPreferences.getInstance();
                    prefs.setString('token', data['token'].toString());
                    if(mounted){
                      Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context){
                        return const YSTabBar();
                      }), (route) => false);
                    }
                  },isLoading: true);
                },
                child: Container(
                  height: hsp(50),
                  width: ysWidth(context)-hsp(100),
                  margin: EdgeInsets.only(top: hsp(100)),
                  decoration: const BoxDecoration(
                      color: Color(0xFF09A171),
                      borderRadius: BorderRadius.all(Radius.circular(5)),
                      gradient: LinearGradient(colors: [Color(0xFF7ADF8D),Color(0xFF8FF0A0)])
                  ),
                  alignment: Alignment.center,
                  child: const Text('登录',style: TextStyle(fontSize: 18,color: Colors.white,fontWeight: FontWeight.bold),),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
