import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:zhiying_comm/pages/login_page/model/login_style_model.dart';
import 'package:zhiying_comm/util/empty_util.dart';
import 'package:zhiying_comm/util/mob_util/mob_util.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

import 'bloc/bloc.dart';
import 'bloc/login_invite_repository.dart';
import 'model/login_invite_user.dart';

///
/// 邀请页面
///
class LoginInvitePage extends StatelessWidget {
  final Map<String, dynamic> data;

  LoginInvitePage(this.data);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: HexColor.fromHex('#FFFFFF'),
      body: BlocProvider(
        create: (_) => LoginInviteBloc(repostitory: LoginInviteRepository())..add(LoginInviteInitEvent()),
        child: LoginInvitePageContainer(this.data),
      ),
    );
  }
}

///
/// 邀请
class LoginInvitePageContainer extends StatefulWidget {
  final Map<String, dynamic> data;

  LoginInvitePageContainer(this.data);

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

class _LoginInvitePageContainerState extends State<LoginInvitePageContainer> {
  TextEditingController _editingController;
  FocusNode _focusNode;
  bool _showInviteInfo = false;

  // 是否登录中
  bool _isLogging = false;

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

  /// 注册成功跳转
  void _successJump() {
    RouterUtil.hideKeyboard(context);
    RouterUtil.goBackHomePage(context);
    // Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (BuildContext context) => PageFactory.create('homePage', null)), (Route<dynamic> route) => false,);
  }

  /// 输入框输入变化
  void _onChange(String string) {
    setState(() {
      _showInviteInfo = false;
    });
    print('$string');
    if (!EmptyUtil.isEmpty(string) && string.length >= 3) {
      _queryInviteInfo(string);
    }
  }

  /// 查询邀请人
  void _queryInviteInfo(String inviteNum) {
    if (!EmptyUtil.isEmpty(inviteNum) && inviteNum.length < 3) {
      return;
    }
    BlocProvider.of<LoginInviteBloc>(context).add(LoginInviteQueryEvent(num: inviteNum));
  }

  /// 填写邀请啊吗
  void _submitOnClick(LoginInviteUser inviteUser) async {
    _focusNode.unfocus();

    if (!_isLogging) {
      /// 邀请码
      String inviteNum = inviteUser?.userId ?? '';

      /// 手机号
      // UserInfoModel model = await Provider.of<UserInfoNotifier>(context, listen: false)?.getUserInfoModel();

      String mobile = widget?.data['mobile'] ;//model?.mobile ?? '';
      if (!EmptyUtil.isEmpty(inviteNum) && !EmptyUtil.isEmpty(mobile)) {
        setState(() {
          _isLogging = true;
        });
        BlocProvider.of<LoginInviteBloc>(context).add(LoginInviteSubmitEvent(mobile: mobile, num: inviteNum));
      }
    }
  }

  @override
  void initState() {
    _editingController = TextEditingController();
    // SharedPreferencesUtil.setNetCacheResult(Constants.mobInvitedCode, tgid);

    MobUtil.getInvitedCode().then((value) {
      _editingController.text = value;
      _onChange(value);
    });

    _focusNode = FocusNode();
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    _editingController?.dispose();
    _focusNode?.unfocus();
    _focusNode?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<LoginInviteBloc, LoginInviteState>(
      listener: (context, state) {},
      buildWhen: (previous, current) {
        /// 提交失败
        if (current is LoginInviteSubmitErrorState) {
          _isLogging = false;
          return false;
        }

        /// 数据加载出错
        if (current is LoginInviteErrorState) {
          return false;
        }

        /// 查询邀请人失败
        if (current is LoginInviteQueryErrorState) {
          return false;
        }

        /// 邀请人查询成功
        if (current is LoginInviteQuerySuccessState) {
          _showInviteInfo = true;
          return true;
        }

        /// 邀请码成功 跳转
        if (current is LoginInviteSubmitSuccess) {
          // 缓存数据
          Provider.of<UserInfoNotifier>(context, listen: false).setUserInfo(current.model);
          _successJump();
          return false;
        }
        return true;
      },
      builder: (context, state) {
        print(state);
        if (state is LoginInviteLoadedState) {
          return _getMainWidget(state.model, null);
        }
        if (state is LoginInviteQuerySuccessState) {
          return _getMainWidget(state.pageMdel, state.model);
        }

        /// 骨架屏
        return Container();
      },
    );
  }

  /// 主视图
  Widget _getMainWidget(LoginStyleModel model, LoginInviteUser inviteUser) {
    return Column(
      children: <Widget>[
        /// appbar
        _getAppBar(model),

        /// 标题
        Padding(padding: const EdgeInsets.only(left: 27.5, right: 27.5, top: 40), child: _getTitleWidget(model)),

        /// 输入框
        Padding(padding: const EdgeInsets.only(left: 27.5, right: 27.5, top: 30), child: _getInviteInputWidget(model)),

        /// 邀请人信息
        Visibility(visible: inviteUser != null && _showInviteInfo, child: Padding(padding: const EdgeInsets.only(left: 27.5, right: 27.5, top: 8), child: _getInviteInfoWidget(inviteUser))),

        /// 按钮
        Padding(padding: const EdgeInsets.only(left: 27.5, right: 27.5, top: 30), child: _getSubmiBtnWidget(model, inviteUser)),
      ],
    );
  }

  /// appBar
  Widget _getAppBar(LoginStyleModel model) {
    return AppBar(
      brightness: Brightness.light,
      backgroundColor: HexColor.fromHex('#FFFFFF'),
      elevation: 0,
      title: Text(
        model?.invite?.appBarTitle ?? '登录',
        style: TextStyle(color: HexColor.fromHex(model?.invite?.appBarTitleColor ?? '#333333')),
      ),
      centerTitle: true,
      leading: IconButton(
        icon: Icon(
          Icons.arrow_back_ios,
          size: 22,
          color: HexColor.fromHex('#333333'),
        ),
        onPressed: () => _openPop(),
      ),
    );
  }

  /// title
  Widget _getTitleWidget(LoginStyleModel model) {
    return Align(
        alignment: Alignment.centerLeft,
        child: Text(
          model?.invite?.title ?? '输入邀请码',
          style: TextStyle(color: HexColor.fromHex(model?.invite?.titleColor ?? '#333333'), fontSize: 25),
        ));
  }

  /// 邀请码输入框
  Widget _getInviteInputWidget(LoginStyleModel model) {
    return _getCustomInputWidget(
        hint: model?.invite?.inputInviteText ?? '请输入邀请码',
        controller: _editingController,
        focusNode: _focusNode,
        onChanged: _onChange,
        hintColor: model?.invite?.inputHintColor ?? '#999999',
        bgColor: model?.invite?.inputBgColor ?? '#F7F7F7',
        textColor: model?.invite?.inputInviteTextColor ?? '#333333',
        iconUrl: model?.invite?.inputInviteIcon ?? '');
  }

  /// 邀请人信息
  Widget _getInviteInfoWidget(LoginInviteUser model) {
    return Container(
      // height: 77.5,
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(8), border: Border.all(color: HexColor.fromHex('#E8E8E8'), width: 0.5)),
      padding: const EdgeInsets.all(15),
      child: Row(
        children: <Widget>[
          /// 头像
          CircleAvatar(
            radius: 23.5,
            backgroundImage: CachedNetworkImageProvider(model?.avatar ?? ''),
          ),
          const SizedBox(width: 13),
          Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              /// 名字
              Text(
                '${model?.nickname}',
                style: TextStyle(color: HexColor.fromHex(model?.nickNameColor), fontSize: 13),
              ),

              /// 邀请
              RichText(
                text: TextSpan(text: '邀请您进入', style: TextStyle(fontSize: 11, color: HexColor.fromHex(model?.nickNameColor)), children: [
                  TextSpan(
                    text: '${model?.appName}',
                    style: TextStyle(fontSize: 11, color: HexColor.fromHex(model?.appNameColor)),
                  ),
                ]),
              )
            ],
          )
        ],
      ),
    );
  }

  /// 按钮
  Widget _getSubmiBtnWidget(LoginStyleModel model, LoginInviteUser inviteUser) {
    return Material(
      child: Container(
        height: 52,
        width: double.infinity,
        color: Colors.white,
        child: RaisedButton(
          child: Text(
            _isLogging ? '进入...' : model?.invite?.btnSubmitText ?? '进入智莺生活',
            style: TextStyle(fontSize: 15),
          ),
          textColor: HexColor.fromHex(model?.invite?.btnSubmitTextColor ?? '#FFFFFF'),
          color: HexColor.fromHex(model?.invite?.btnSubmitBgColor ?? '#FF3939'),
          disabledColor: HexColor.fromHex(model?.invite?.btnBanBgColor ?? '#F5F5F5'),
          disabledTextColor: HexColor.fromHex(model?.invite?.btnBanTextColor ?? '#999999'),
          elevation: 5,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(52 / 2)),
          onPressed: _showInviteInfo && inviteUser != null ? () => _submitOnClick(inviteUser) : null,
        ),
      ),
    );
  }

  /// 自定义输入框
  Widget _getCustomInputWidget(
      {String hint, String hintColor, String bgColor, String textColor, String iconUrl, TextEditingController controller, ValueChanged<String> onChanged, FocusNode focusNode}) {
    var border = OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide(color: HexColor.fromHex(bgColor), width: 0));

    return Container(
      height: 42,
      padding: const EdgeInsets.symmetric(horizontal: 15),
      decoration: BoxDecoration(
        color: HexColor.fromHex(bgColor),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          CachedNetworkImage(
            imageUrl: iconUrl ?? '',
            width: 10,
          ),
          Expanded(
            child: TextField(
              controller: controller,
              focusNode: focusNode,
              onChanged: onChanged,
              expands: false,
              style: TextStyle(color: HexColor.fromHex(textColor)),
              maxLines: 1,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.only(top: 30, left: 7.5),
                hintText: hint,
                hintStyle: TextStyle(fontSize: 13, color: HexColor.fromHex(hintColor)),
                hintMaxLines: 1,
                filled: true,
                fillColor: Colors.transparent,
                border: border,
                focusedBorder: border,
                enabledBorder: border,
                disabledBorder: border,
                errorBorder: border,
                focusedErrorBorder: border,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
