import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:zhiying_comm/pages/login_page/account/login_account_page.dart';
import 'package:zhiying_comm/util/empty_util.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

import 'bloc/bloc.dart';
import 'bloc/login_repository.dart';
import 'login_page_sk.dart';
import 'model/login_model.dart';

///
/// 登陆页面
///
class LoginPage extends StatelessWidget {

  const LoginPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: HexColor.fromHex('#FFFFFF'),
      body: BlocProvider<LoginBloc>(
        create: (_) => LoginBloc(repository: LoginRepository())..add(LoginInitEvent()),
        child: LoginPageContainer(),
      ),
    );
  }
}

class LoginPageContainer extends StatefulWidget {
  @override
  _LoginPageContainerState createState() => _LoginPageContainerState();
}

class _LoginPageContainerState extends State<LoginPageContainer> {

  /// 微信登陆
  void _loginClick(String type) {
    print('登陆$type');
    if(type == 'mobile'){
      Navigator.push(context, CupertinoPageRoute(
          builder: (_) => LoginAccountPage(null)
      ));
    }
  }

  /// 返回上一页
  void _openPop(){
    if(Navigator.canPop(context)){
      Navigator.pop(context);
    }
  }

  /// 第三方登陆
  void _otherLoginClick(BottomIcons model) {
    print('第三方登陆${model.type}');
  }

  /// 跳到用户协议
  void _jumpUserAgreement(String url) {
    if(!EmptyUtil.isEmpty(url)) {
      print('协议');
    }
  }

  /// 展开关闭其它登陆
  void _showOrColoseOtherLogin() {
    setState(() {
      _showOther = !_showOther;
    });
  }

  final _sizedHeight50 = const SizedBox(height: 50);
  final _sizedHeight9 = const SizedBox(height: 9);
  final _sizedHeight18 = const SizedBox(height: 18);
  final _sizedHeight21 = const SizedBox(height: 21);
  bool _showOther = true;

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<LoginBloc, LoginState>(
      listener: (context, state) {
        // Fluttertoast.showToast(msg: '网络异常');
      },
      buildWhen: (prev, current) {
        if (current is LoginErrorState) {
          return false;
        }
        return true;
      },
      builder: (context, state) {
        if (state is LoginCacheState) {
          return _getMainWidget(state.model);
        }
        if (state is LoginLoadedState) {
          return _getMainWidget(state.model);
        }
        return LoginPageSkeleton(); // 骨架屏幕
      },
    );
  }

  /// 主视图
  Widget _getMainWidget(LoginModel model) {
    return Column(
      children: <Widget>[

        /// 头部
        _headWidget(model),
        _sizedHeight50,

        /// 按钮
        _buttonsWidget(model),
        _sizedHeight9,

        /// 协议
        _protocolWidget(model),

        /// 其它登陆方式
        _otherLoginWidget(model),
      ],
    );
  }

  /// 头部Widget
  Widget _headWidget(LoginModel model) {
    return Container(
      height: 228 + MediaQuery.of(context).padding.top,
      width: double.infinity,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: CachedNetworkImageProvider(model?.main?.backgroundImg ?? ''),
          fit: BoxFit.fill,
        ),
      ),
      child: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          AppBar(
            backgroundColor: Colors.transparent,
            elevation: 0,
            leading: IconButton(
              icon: Icon(
                Icons.arrow_back_ios,
                size: 22,
                color: HexColor.fromHex('#333333'),
              ),
              onPressed: ()=> _openPop(),
            ),
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[

              /// logo
              Container(
                margin: EdgeInsets.only(bottom: 12, top: MediaQuery.of(context).padding.top),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(14),
                  boxShadow: [
                    BoxShadow(color: Colors.grey[300], offset: Offset(0.0, 0.0), blurRadius: 10.0, spreadRadius: 1.0),
                    BoxShadow(color: Colors.grey[300], offset: Offset(0.0, 0.0)),
                  ],
                ),
                height: 80,
                width: 80,
                child: CachedNetworkImage(imageUrl: model?.logoImg ?? ''),
              ),

              /// logo 名字
              CachedNetworkImage( imageUrl: model?.main?.appNameImg ?? '', width: 90,),

            ],
          ),
        ],
      ),
    );
  }

  /// 按钮
  Widget _buttonsWidget(LoginModel model) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 27.5),
      child: Column(
        children: model.main.importanceLogin.map((item) {
          return Padding(
            padding: const EdgeInsets.only(bottom: 8),
            child: _customButton(
                height: 40,
                text: item?.btnText,
                iconUrl: item?.btnMobileIcon ?? '',
                textColor: item?.btnTextColor,
                bgColor: item?.btnBgColor,
                borderColor: item?.btnBorderColor,
                onTap: () => _loginClick(item?.type)),
          );
        }).toList(),
      ),
    );
  }

  /// 协议
  Widget _protocolWidget(LoginModel model) {
    return RichText(
      text: TextSpan(text: '', children: model.main.agreements.map((item){
        return TextSpan(text: item?.text, style: TextStyle(color: HexColor.fromHex(item?.textColor), fontSize: 10),recognizer: TapGestureRecognizer()..onTap = (){
          _jumpUserAgreement(item?.url);
        });
      }).toList()),
    );
  }

  /// 其它登陆方式
  Widget _otherLoginWidget(LoginModel model) {
    return Expanded(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          _getOtherLoginTitle(model),
          _sizedHeight18,
          Visibility(visible: _showOther, child: _getOtherLoginIcons(model)),
          Visibility(visible: _showOther, child: _sizedHeight21),
        ],
      ),
    );
  }

  /// 其它登陆方式的title
  Widget _getOtherLoginTitle(LoginModel model) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () => _showOrColoseOtherLogin(),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text('${model?.main?.otherIconsTitle}', style: TextStyle(fontSize: 13, color: HexColor.fromHex(model?.main?.otherIconsTitleColor))),
          SizedBox(width: 5.5),
          RotatedBox(
            quarterTurns: _showOther ? 0 : 2,
            child: CachedNetworkImage(imageUrl: model?.main?.otherExpansionIcon ?? '', width: 12),
          ),
        ],
      ),
    );
  }

  /// 其它登陆方式的按钮
  Widget _getOtherLoginIcons(LoginModel model) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: model.main.bottomIcons.map((item) {
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () => _otherLoginClick(item),
          child: Container(
            width: 30,
            margin: const EdgeInsets.symmetric(horizontal: 20),
            child: CachedNetworkImage(imageUrl: item?.img ?? ''),
          ),
        );
      }).toList(),
    );
  }

  /// 自定义按钮
  Widget _customButton({double height, String text, String iconUrl, String textColor, String bgColor, String borderColor, GestureTapCallback onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: double.infinity,
        height: height ?? 0,
        decoration: BoxDecoration(
          border: Border.all(color: HexColor.fromHex(borderColor), width: 0.5),
          borderRadius: BorderRadius.circular(height ?? 0 / 2),
          color: HexColor.fromHex(bgColor),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            // icon
            CachedNetworkImage(imageUrl: iconUrl, width: 12),
            SizedBox(width: 8),
            // text
            Text(text, style: TextStyle(color: HexColor.fromHex(textColor), fontSize: 15))
          ],
        ),
      ),
    );
  }
}
