import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:zhiying_base_widget/pages/team_page/model/team_data_model.dart';
import 'package:zhiying_base_widget/pages/team_page/model/team_style_model.dart';
import 'package:zhiying_base_widget/widgets/team/recommend/bloc/team_recommend_bloc.dart';
import 'package:zhiying_base_widget/widgets/team/recommend/bloc/team_recommend_repository.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

///
/// 我的团队 - 我的推荐人
///
class TeamRecommendWidget extends StatelessWidget {
  TeamStyleModel styleModel;
  TeamDataModel dataModel;

  TeamRecommendWidget(this.styleModel, this.dataModel);

  @override
  Widget build(BuildContext context) {
    return BlocProvider<TeamRecommendBloc>(
      create: (_) => TeamRecommendBloc(TeamRecommendRepository())..add(TeamRecommendInitEvent(dataModel: dataModel)),
      child: _TeamRecommendWidgetContainer(styleModel, dataModel),
    );
  }
}

class _TeamRecommendWidgetContainer extends StatefulWidget {
  TeamStyleModel styleModel;

  TeamDataModel dataModel;

  _TeamRecommendWidgetContainer(this.styleModel, dataModel, {Key key}) : super(key: key);

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

class __TeamRecommendWidgetState extends State<_TeamRecommendWidgetContainer> {
  TextEditingController _textEditingController;
  FocusNode _focusNode;
  TeamStyleModel styleModel;
  TeamDataModel dataModel;

  /// 按钮点击添加事件
  void _onClickListener() {
    String text = _textEditingController?.text?.toString()?.trim();
    if (!EmptyUtil.isEmpty(text)) {
      BlocProvider.of<TeamRecommendBloc>(context).add(TeamRecommendRelateEvent(text));
    } else {
      Fluttertoast.showToast(msg: '邀请码不能为空～');
    }
  }

  /// 拷贝
  void _copyText(String text) {
    if(!EmptyUtil.isEmpty(text)) {
      Clipboard.setData(ClipboardData(text: text));
      Fluttertoast.showToast(msg: '复制成功~');
    }else{
      Fluttertoast.showToast(msg: '内容不能为空～');
    }
  }

  @override
  void initState() {
    _textEditingController = TextEditingController();
    _focusNode = FocusNode();
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(left: 12.5, right: 12.5, top: 10.5),
      child: BlocConsumer<TeamRecommendBloc, TeamRecommendState>(
        listener: (context, state) {},
        buildWhen: (prove, current) {
          if (current is TeamRecommendErrorState) {
            return false;
          }
          return true;
        },
        builder: (context, state) {
          if (state is TeamRecommendLoadedState) {
            return _getMainWidget(state?.model);
          }
          return _getMainWidget(null);
        },
      ),
    );
  }

  /// 主体Widget
  Widget _getMainWidget(TeamDataModel dataModel) {
    return Container(
      padding: const EdgeInsets.only(left: 10, bottom: 12, right: 10),
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(10), color: Colors.white),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          /// 左上角的Icon
          _getLeftTopWidget(),

          const SizedBox(height: 6),

          /// 数据视图
          Visibility(
            visible: !EmptyUtil.isEmpty(dataModel) && !EmptyUtil.isEmpty(dataModel?.referrer_invite_code) && !EmptyUtil.isEmpty(dataModel?.referrer_username),
            replacement: _getInputCombWidget(),
            child: Padding(padding: const EdgeInsets.only(left: 10), child: _getDataWidget(dataModel)),
          ),
        ],
      ),
    );
  }

  /// 我的推荐人IconWidget(左上角的ICON)
  Widget _getLeftTopWidget() {
    return Transform.translate(
        offset: Offset(0, -4.5),
        child: Container(
          padding: const EdgeInsets.only(left: 10.5, right: 8, top: 4, bottom: 4.5),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              gradient: LinearGradient(begin: Alignment.centerLeft, end: Alignment.centerRight, colors: [
                HexColor.fromHex(widget?.styleModel?.headerReferrerTitleBgColor ?? '#FF5E5E'),
                HexColor.fromHex(widget?.styleModel?.headerReferrerTitleBgColorT ?? '#FF5252'),
              ])),
          child: Text(
            widget?.styleModel?.headerReferrerTitle ?? '我的推荐人',
            style: TextStyle(
              color: HexColor.fromHex(widget?.styleModel?.headerReferrerTitleColor ?? '#FFFFFF'),
              fontSize: 11,
            ),
          ),
        ));
  }

  /// 没邀请人的Widget
  Widget _getInputCombWidget() {
    return Container(
      margin: const EdgeInsets.only(left: 2.5, right: 2.5),
      width: double.infinity,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        // crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          /// 输入框
          Container(
            height: 30,
            width: double.infinity,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(30),
              color: HexColor.fromHex(widget?.styleModel?.headerNoReferrerInputBgColor ?? '#F7F7F7'),
            ),
            padding: const EdgeInsets.only(top: 3.5, bottom: 3.5, right: 3, left: 13),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: _getInputWidget(),
                ),

                /// 添加的按钮
                _getAddButtomWidget(),
              ],
            ),
          ),

          const SizedBox(height: 10.5),

          /// 文字提示
          Text(
            widget?.styleModel?.headerNoReferrerTipText ?? '还没有填写邀请人ID，填写后双方都可以获得奖励',
            style: TextStyle(color: HexColor.fromHex(widget?.styleModel.headerNoReferrerTipTextColor ?? '#909090'), fontSize: 11),
          ),
        ],
      ),
    );
  }

  /// 输入框的
  Widget _getInputWidget() {
    return TextField(
      controller: _textEditingController,
      focusNode: _focusNode,
      onSubmitted: (value) => _onClickListener(),
      style: TextStyle(color: HexColor.fromHex(widget?.styleModel?.headerNoReferrerInputColor ?? '#000000'), fontSize: 12, textBaseline: TextBaseline.alphabetic),
      decoration: InputDecoration(
        border: InputBorder.none,
        enabledBorder: InputBorder.none,
        disabledBorder: InputBorder.none,
        errorBorder: InputBorder.none,
        focusedErrorBorder: InputBorder.none,
        focusedBorder: InputBorder.none,
        hintText: widget?.styleModel?.headerNoReferrerIntputText ?? '输入邀请人ID',
        isDense: true,
        filled: true,
        fillColor: Colors.transparent,
        contentPadding: EdgeInsets.zero,
        hintStyle: TextStyle(color: HexColor.fromHex(widget?.styleModel?.headerNoReferrerIntputTextColor ?? '#909090'), fontSize: 12, textBaseline: TextBaseline.alphabetic),
      ),
    );
  }

  /// 添加的按钮
  Widget _getAddButtomWidget() {
    return Material(
      child: InkWell(
        onTap: _onClickListener,
        child: Container(
          padding: const EdgeInsets.only(left: 21, right: 21, top: 2.5, bottom: 2.5),
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(30), color: HexColor.fromHex(widget?.styleModel?.headerNoReferrerBtnBgColor ?? '#F94B47')),
          child: Text(
            widget?.styleModel?.headerNoReferrerBtnText ?? '添加',
            style: TextStyle(
              fontSize: 13,
              color: HexColor.fromHex(widget?.styleModel?.headerNoReferrerBtnTextColor ?? '#FFFFFF'),
            ),
          ),
        ),
      ),
    );
  }

  /// 数据视图
  Widget _getDataWidget(TeamDataModel dataModel) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        /// 头像widget
        _getAvatarWidget(dataModel),

        const SizedBox(width: 12),

        /// 数据
        _getDataRightWidget(dataModel),
      ],
    );
  }

  /// 头像widget
  Widget _getAvatarWidget(TeamDataModel dataModel) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(55/2),
      child: Container(
        width: 55,
        // height: 55,
        // color: Colors.red,
        child: CachedNetworkImage(
          imageUrl: dataModel?.referrerAvatar ?? '',
        ),
      ),
    );
  }

  /// 数据右边视图，头像右边的widget
  Widget _getDataRightWidget(TeamDataModel dataModel) {
    return SizedBox(
      height: 55,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          /// 昵称
          _getNickNameWidget(dataModel),

          /// 手机号
          _getPhoneNumberWidget(dataModel),

          /// 微信号
          _getWXWidget(dataModel)
        ],
      ),
    );
  }

  /// 昵称
  Widget _getNickNameWidget(TeamDataModel dataModel) {
    // return  RichText(
    //   text: TextSpan(text: '毛毛虫', style: TextStyle(fontSize: 14, color: HexColor.fromHex('#000000'), fontWeight: FontWeight.bold),
    //     children: [
    //       TextSpan(text: '邀请码：', style: TextStyle(fontSize: 11, color: HexColor.fromHex('#909090'), fontWeight: FontWeight.w400)),
    //       TextSpan(text: '123456', style: TextStyle(fontSize: 11, color: HexColor.fromHex('#909090'), fontWeight: FontWeight.w400)),
    //     ]
    //   ),
    // );

    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        /// 昵称
        Text(dataModel?.referrer_username ?? '',
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: 14,
              color: HexColor.fromHex(widget?.styleModel?.headerReferrerUsernameColor ?? '#000000'),
              fontWeight: FontWeight.bold,
            )),
        const SizedBox(width: 6),
        Text(widget?.styleModel?.headerReferrerInvitecodeText ?? '邀请码：',
            style: TextStyle(fontSize: 11, color: HexColor.fromHex(widget?.styleModel?.headerReferrerInvitecodeColor ?? '#909090'))),
        Text(dataModel?.referrer_invite_code ?? '',
            style: TextStyle(
                fontSize: 11, color: HexColor.fromHex(widget?.styleModel?.headerReferrerInvitecodeColor ?? '#909090'), fontFamily: 'Din', package: 'zhiying_base_widget')),
      ],
    );
  }

  /// 手机号
  Widget _getPhoneNumberWidget(TeamDataModel dataModel) {
    return Row(
      children: <Widget>[
        Text(widget?.styleModel?.headerReferrerPhoneText ?? '手机号：',
            style: TextStyle(fontSize: 11, color: HexColor.fromHex(widget?.styleModel?.headerReferrerPhoneColor ?? '#AFAFAF'))),
        Text(dataModel?.referrer_phone ?? '',
            style: TextStyle(fontSize: 11, color: HexColor.fromHex(widget?.styleModel?.headerReferrerPhoneColor ?? '#AFAFAF'), fontFamily: 'Din', package: 'zhiying_base_widget')),
        const SizedBox(width: 6),

        /// 拷贝按钮
        _getCustomCopyWidget(dataModel?.referrer_phone),
      ],
    );
  }

  /// 微信号
  Widget _getWXWidget(TeamDataModel dataModel) {
    return Row(
      children: <Widget>[
        Text(widget?.styleModel?.headerReferrerWxText ?? '微信号：', style: TextStyle(fontSize: 11, color: HexColor.fromHex(widget?.styleModel?.headerReferrerWxColor ?? '#AFAFAF'))),
        Text(dataModel?.referrer_wechat ?? '',
            style: TextStyle(fontSize: 11, color: HexColor.fromHex(widget?.styleModel?.headerReferrerWxColor ?? '#AFAFAF'), fontFamily: 'Din', package: 'zhiying_base_widget')),
        const SizedBox(width: 6),

        /// 拷贝按钮
        _getCustomCopyWidget(dataModel?.referrer_wechat),
      ],
    );
  }

  /// 自定义复制按钮的Widget
  Widget _getCustomCopyWidget(String text) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () => _copyText(text),
      child: Container(
        padding: const EdgeInsets.only(left: 4, bottom: 2, top: 2, right: 6),
        decoration: BoxDecoration(
          color: HexColor.fromHex(widget?.styleModel?.headerReferrerCopyBtnBgColor ?? '#FFF2F2'),
          borderRadius: BorderRadius.circular(30),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            // Container(width: 11, child: CachedNetworkImage(),),
            CachedNetworkImage(
              imageUrl: widget?.styleModel?.headerReferrerCopyBtnIcon ?? '',
              width: 11,
            ),
            const SizedBox(width: 4.5),
            Text(widget?.styleModel?.headerReferrerCopyBtnText ?? '复制',
                style: TextStyle(fontSize: 8, color: HexColor.fromHex(widget?.styleModel?.headerReferrerCopyBtnTextColor ?? '#F94B47')))
          ],
        ),
      ),
    );
  }
}
