import 'package:deus_app/common/local/StoreHelper.dart';
import 'package:deus_app/common/style/gsy_style.dart';
import 'package:deus_app/common/utils/CommonUtils.dart';
import 'package:deus_app/common/utils/DioUtil.dart';
import 'package:deus_app/common/utils/ToastUtils.dart';
import 'package:deus_app/generated/json/user_response_entity_helper.dart';
import 'package:deus_app/model/login_response_entity.dart';
import 'package:deus_app/model/user_response_entity.dart';
import 'package:deus_app/page/home/home_page.dart';
import 'package:deus_app/widget/gsy_flex_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../../common/utils/ConstantString.dart';
import '../../generated/json/login_response_entity_helper.dart';


/// 登录页
/// Created by Ocean
class LoginPage extends StatefulWidget {
  static const String sName = "login";
  static var routeName = '/LoginPage';

  const LoginPage({super.key});

  @override
  State createState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends State<LoginPage> {
  //TextEditingController可以使用 text 属性指定初始值
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  String _username = '13182861111', _password = '123456';

  @override
  Widget build(BuildContext context) {
    StoreHelper.init();
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.cover,
            image: AssetImage("images/login_bg.png"),
          ),
        ),

        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            SizedBox(
              height: MediaQuery.of(context).size.height / 6,
            ),
            Container(
              margin: EdgeInsets.only(left: 30),
              child: const Text('鑫森科技',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: GSYConstant.lagerTextSize,
                    fontWeight: FontWeight.bold,
                  )),
            ),
            Container(
              padding:  EdgeInsets.only(left: 40,right: 40,top: 60),
              margin: EdgeInsets.only(top: 40),

              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage("images/login_bg_write.png"),
                  fit: BoxFit.fill,
                ),
              ),
              child:Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text('输入手机号',style: TextStyle(
                    color: Color(0xFF999999),
                    fontSize: GSYConstant.smallTextSize
                  )),
                  SizedBox(
                    height: 10,
                  ),
                  _getUsernameInput(),
                  SizedBox(
                    height: 20,
                  ),
                  Text('输入密码',style: TextStyle(
                      color: Color(0xFF999999),
                      fontSize: GSYConstant.smallTextSize
                  )),
                  SizedBox(
                    height: 10,
                  ),
                  _getPasswordInput(),
                  SizedBox(
                    height:50,
                  ),
                  _getLoginButton(),
                  SizedBox(
                    height: 45,
                  ),
                ],
              ),
            ),

          ],
        ),
      ),
    );
  }

  Widget _getUsernameInput() {
    return _getInputTextField(
      TextInputType.number,
      controller: _usernameController,
      decoration: InputDecoration(
          border: OutlineInputBorder(
            ///设置边框四个角的弧度
            borderRadius: BorderRadius.all(Radius.circular(5)),
            ///用来配置边框的样式
            borderSide: BorderSide(
              ///设置边框的颜色
              color: Colors.red,
              ///设置边框的粗细
              width: 1.0,
            ),
          ),
        prefixIcon: Icon(
          Icons.mobile_friendly_rounded,
          size: 18.0,
        ),
        contentPadding: EdgeInsets.only(left: 15,right: 15,top: 0,bottom: 0),
        //使用 GestureDetector 实现手势识别
        suffixIcon: GestureDetector(
          child: Offstage(
            child: Icon(Icons.clear,size: 18.0),
            offstage: _username == '',
          ),
          //点击清除文本框内容
          onTap: () {
            this.setState(() {
              _username = '';
              _usernameController.clear();
            });
          },
        ),
      ),
      //使用 onChanged 完成双向绑定
      onChanged: (value) {
        this.setState(() {
          _username = value;
        });
      },
    );
  }

  Widget _getPasswordInput() {
    return _getInputTextField(
      TextInputType.text,
      obscureText: true,
      controller: _passwordController,
      decoration: InputDecoration(
        prefixIcon: Icon(
          Icons.lock_open,
          size: 18.0,
        ),
        suffixIcon: GestureDetector(
          child: Offstage(
            child: Icon(Icons.clear,size: 18.0),
            offstage: _password == '',

          ),
          onTap: () {
            this.setState(() {
              _password = '';
              _passwordController.clear();
            });
          },
        ),
        contentPadding: EdgeInsets.only(left: 15,right: 15,top: 0,bottom: 0),
        border: OutlineInputBorder(
          ///设置边框四个角的弧度
          borderRadius: BorderRadius.all(Radius.circular(5)),
          ///用来配置边框的样式
          borderSide: BorderSide(
            ///设置边框的颜色
            color: Colors.red,
            ///设置边框的粗细
            width: 1.0,
          ),
        ),
      ),
      onChanged: (value) {
        this.setState(() {
          _password = value;
        });
      },
    );
  }

//省略了上述列举的代码
  Widget _getInputTextField(
    TextInputType keyboardType, {
    FocusNode? focusNode,
    controller: TextEditingController,
    onChanged: Function,
    InputDecoration? decoration,
    bool obscureText = false,
    height = 52.0,
  }) {
    return Container(
      height: height,
      child: Column(
        children: [
          TextField(
            keyboardType: keyboardType,
            focusNode: focusNode,
            obscureText: obscureText,
            controller: controller,
            decoration: decoration,
            onChanged: onChanged,
            style: const TextStyle(fontSize: GSYConstant.TextSize15),
          ),
          // Divider(
          //   height: 1.0,
          //   color: Colors.grey[400],
          // ),
        ],
      ),
    );
  }

  Widget _getLoginButton() {
    return SizedBox(
      height: 50,
      width: double.infinity,
      child: GSYFlexButton(
        text: ConstantString.loginText,
        color: Color(0xFF215CFF),
        textColor: GSYColors.textWhite,
        fontSize: 16,
        onPress: login,
      ),
    );
  }

  login() async {
    if (!CommonUtils.validationInput(_username)) {
      showToast(ConstantString.loginNull);
    } else {
      // LoadingDialogHelper.showLoading(context);
      // EasyLoading.show(status: 'loading...');
      var result = await DioUtil().request('auth/login',
          method: DioMethod.post,
          data: {'username': _username, 'password': _password});
      LoginResponseEntity loginResponseEntity =
          loginResponseEntityFromJson(LoginResponseEntity(), result);
      if (0 == loginResponseEntity.code) {
        StoreHelper.putStorage(
            ConstantString.token, loginResponseEntity.data.token);
        debugPrint(loginResponseEntity.data.token);
        getInfo();
      } else {
        EasyLoading.dismiss();
        showToast(loginResponseEntity.msg);
      }
    }
  }

  getInfo() async {
    var result =
        await DioUtil().request('user/current-user', method: DioMethod.post);
    UserResponseEntity entity =
        userResponseEntityFromJson(UserResponseEntity(), result);
    if (entity.code == 0) {
      StoreHelper.putStorage(ConstantString.name, entity.data.name);
      StoreHelper.putStorage(ConstantString.orgName, entity.data.orgName);
      StoreHelper.putStorage(ConstantString.phone, entity.data.phone);
      Navigator.pushAndRemoveUntil(
          context,
          MaterialPageRoute(builder: (context) => HomePage(userResponseEntity: entity.data.menu4AppList)),
          (route) => false);
    } else {
      showToast(entity.msg);
    }
  }
}
