import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:zhiying_base_widget/pages/wechat_teacher_page/bloc/wechat_teacher_bloc.dart';
import 'package:zhiying_base_widget/pages/wechat_teacher_page/bloc/wechat_teacher_repository.dart';
import 'package:zhiying_base_widget/pages/wechat_teacher_page/model/wechat_teacher_data_model.dart';
import 'package:zhiying_base_widget/pages/wechat_teacher_page/model/wechat_teacher_style_model.dart';
import 'package:zhiying_base_widget/pages/wechat_teacher_page/widgets/wechat_teacher_item.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

import 'bloc/wechat_teacher_event.dart';
import 'bloc/wechat_teacher_state.dart';
import 'package:url_launcher/url_launcher.dart';

///
/// 微信导师
///
class WechatTeacherPage extends StatelessWidget {
  final Map<String, dynamic> data;

  WechatTeacherPage(this.data);

  @override
  Widget build(BuildContext context) {
    return BlocProvider<WechatTeacherBloc>(
      create: (_) => WechatTeacherBloc(WechatTeacherRepository(data))..add(WechatTeacherInitEvent()),
      child: _WechatTeacherPageContainer(),
    );
  }
}

class _WechatTeacherPageContainer extends StatefulWidget {
  @override
  _WechatTeacherPageContainerState createState() => _WechatTeacherPageContainerState();
}

class _WechatTeacherPageContainerState extends State<_WechatTeacherPageContainer> {
  TextEditingController _editingController;

  /// 是否绑定中
  bool _isBinding = false;

  /// 绑定邀请人
  void _bindTeacher() {
    if (!_isBinding) {
      String wxAccount = _editingController?.text?.toString();
      if (EmptyUtil.isEmpty(wxAccount)) {
        Fluttertoast.showToast(msg: '请输入邀请码或者手机号码');
        return;
      }
      setState(() {
        _isBinding = true;
      });
      BlocProvider.of<WechatTeacherBloc>(context).add(WechatTeacherBindEvent(teacherWxChat: wxAccount));
    }
  }

  /// 拷贝
  void _copyText(String text) async {
    if (!EmptyUtil.isEmpty(text)) {
      await Clipboard.setData(ClipboardData(text: text));
      Fluttertoast.showToast(msg: '复制成功~');
      String url = "weixin://";
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        throw 'Could not launch $url';
      }
    } else {
      Fluttertoast.showToast(msg: '内容不能为空～');
    }
  }

  /// 长按保存图片
  void _longClickSaveImage(String url) async {
    Logger.log('长按保存图片');
    if (!EmptyUtil.isEmpty(url)) {
      var msg = await Download().fileToGallery(url);
      Fluttertoast.showToast(msg: msg);
    }
  }

  @override
  void initState() {
    _editingController = TextEditingController();
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<WechatTeacherBloc, WechatTeacherState>(
      listener: (context, state) {},
      buildWhen: (prov, current) {
        if (current is WechatTeacherInitErrorState) {
          return false;
        }
        if (current is WechatTeacherBindErrorState) {
          _isBinding = false;
          return false;
        }
        if (current is WechatTeacherBindSuccessState) {
          _isBinding = false;
          Fluttertoast.showToast(msg: '绑定成功');
          return false;
        }
        return true;
      },
      builder: (context, state) {
        if (state is WechatTeacherLoadedState) {
          return _createMainWidget(state?.styleModel, state?.dataModel);
        }
        return _createMainWidget(null, null);
      },
    );
  }

  Widget _createMainWidget(WechatTeacherStyleModel styleModel, WechatTeacherDataModel dataModel) {
    return Scaffold(
      appBar: _createNav(styleModel),
      backgroundColor: HexColor.fromHex(styleModel?.bgColor ?? '#FFF5F5F5'),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              _createHeader(styleModel, dataModel),
              Padding(
                  padding: const EdgeInsets.only(top: 15),
                  child: CachedNetworkImage(
                    imageUrl: styleModel?.chatDialogImg ?? '',
                    width: double.infinity,
                  )),
              _createWechat(styleModel),
            ],
          ),
        ),
      ),
    );
  }

  // 导航栏
  Widget _createNav(WechatTeacherStyleModel styleModel) {
    return CupertinoNavigationBar(
      border: Border(
        bottom: BorderSide(
          width: 0.0, // One physical pixel.
          style: BorderStyle.none,
        ),
      ),
      backgroundColor: HexColor.fromHex(styleModel?.appBarBgColor ?? '#FFFFFF'),
      leading: Navigator.canPop(context)
          ? GestureDetector(
              child: Container(
                padding: EdgeInsets.zero,
                child: Icon(
                  Icons.arrow_back_ios,
                  size: 20,
                ),
              ),
              onTap: () {
                if (Navigator.canPop(context)) {
                  Navigator.pop(context);
                }
              },
            )
          : Container(),
      middle: Text(
        styleModel?.appBarName ?? '微信导师',
        style: TextStyle(
          fontSize: 15,
          color: HexColor.fromHex(styleModel?.appBarNameColor ?? '#333333'),
        ),
      ),
    );
  }

  /// 没绑定的UI
  Widget _createNoBindWidget(WechatTeacherStyleModel styleModel) {
    return Column(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 8, bottom: 2),
          child: CupertinoTextField(
            onSubmitted: (val) => _bindTeacher(),
            controller: _editingController,
            placeholder: styleModel?.nobindTeacherDialog?.inputHintText ?? '请填写邀请人邀请码/手机号码',
            placeholderStyle: TextStyle(fontSize: 14),
            decoration: BoxDecoration(),
          ),
        ),
        Container(
          height: 0.5,
          color: Color(0xffd5d5d5),
        ),
        GestureDetector(
          onTap: () => _bindTeacher(),
          child: Center(
            child: Container(
              margin: EdgeInsets.only(top: 10),
              width: 130,
              height: 30,
              decoration: BoxDecoration(
                color: HexColor.fromHex(styleModel?.commStyle?.btnBgColor ?? '#FF5A5A'),
                borderRadius: BorderRadius.circular(15),
              ),
              child: Center(
                child: Text(
                  _isBinding ? '绑定中...' : styleModel?.nobindTeacherDialog?.btnText ?? '绑定邀请人',
                  style: TextStyle(
                      color: HexColor.fromHex(styleModel?.commStyle?.btnTextColor ?? '#FFFFFFF'), fontSize: 14),
                ),
              ),
            ),
          ),
        )
      ],
    );
  }

  /// 绑定的UI
  Widget _createBindWidget(WechatTeacherStyleModel styleModel, WechatTeacherDataModel dataModel) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      margin: const EdgeInsets.only(top: 10),
      child: Row(
        children: <Widget>[
          Container(
            width: 50,
            height: 50,
            // color: Colors.red,
            child: CircleAvatar(
                child: CachedNetworkImage(
              imageUrl: dataModel?.teacherAvatar ?? '',
            )),
          ),
          const SizedBox(width: 13),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              Text(dataModel?.teacherUsername ?? '',
                  style: TextStyle(
                      fontSize: 15, color: HexColor.fromHex(styleModel?.teacherDialogTitleColor ?? '#3C3C3C'))),
              Text('微信号:  ${dataModel?.teacherWechatAccount ?? ''}',
                  style: TextStyle(
                      fontSize: 15, color: HexColor.fromHex(styleModel?.commStyle?.wechatAccountColor ?? '#FF5050'))),
              GestureDetector(
                onTap: () => _copyText(dataModel?.teacherWechatAccount),
                child: UnconstrainedBox(
                  child: Container(
                    decoration: BoxDecoration(
                      // color: Color(0xffffdada),
                      color: HexColor.fromHex(styleModel?.bindTeacherDialog?.btnBgColor ?? '#FFDADA'),
                      borderRadius: BorderRadius.circular(20),
                    ),
                    padding: EdgeInsets.only(left: 9, right: 9, top: 4, bottom: 4),
                    child: Text(
                      styleModel?.bindTeacherDialog?.btnText ?? '复制去微信添加',
                      style: TextStyle(
                          fontSize: 13,
                          color: HexColor.fromHex(styleModel?.bindTeacherDialog?.btnTextColor ?? '#FF0000')),
                    ),
                  ),
                ),
              ),
            ],
          ),
          Expanded(
            child: Align(
              alignment: Alignment.centerRight,
              child: GestureDetector(
                onLongPress: () => _longClickSaveImage(
                    dataModel?.teacherWxQrCode ?? styleModel?.myTeacher?.defalutTeacher?.qrcode ?? ''),
                child: Column(
                  children: <Widget>[
                    Container(
                      width: 56,
                      height: 56,
                      // color: Colors.red,
                      child: CachedNetworkImage(
                        imageUrl: dataModel?.teacherWxQrCode ?? styleModel?.myTeacher?.defalutTeacher?.qrcode ?? '',
                      ),
                    ),
                    const SizedBox(height: 9),
                    Text(
                      styleModel?.officalWxchat?.qrcodeText ?? '长按保存二维码',
                      style: TextStyle(
                          fontSize: 13,
                          color: HexColor.fromHex(styleModel?.officalWxchat?.qrcodeTextColor ?? '#999999')),
                    ),
                  ],
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _createHeader(WechatTeacherStyleModel styleModel, WechatTeacherDataModel dataModel) {
    return Container(
      width: double.infinity,
      height: 283,
      child: Stack(
        children: <Widget>[
          // 背景图
          Container(
            width: double.infinity,
            height: 185,
            // color: Colors.redAccent,
            child: CachedNetworkImage(
              imageUrl: styleModel?.bgImg ?? '',
              fit: BoxFit.contain,
            ),
          ),

          // 中间弹窗
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              width: double.infinity,
              height: 138,
              margin: EdgeInsets.only(left: 10, right: 10),
              padding: EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: HexColor.fromHex(styleModel?.teacherDialogBgColor ?? '#FFFFFF'),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    styleModel?.teacherDialogTitle ?? '我的导师',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 15,
                      color: HexColor.fromHex(styleModel?.teacherDialogTitleColor ?? '#3C3C3C'),
                    ),
                  ),
                  Expanded(
                    child: Visibility(
                      visible: dataModel?.isBindTeacher == '1',
                      replacement: _createNoBindWidget(styleModel),
                      child: _createBindWidget(styleModel, dataModel),
                    ),
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _createWechat(WechatTeacherStyleModel styleModel) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(left: 10, right: 10, top: 0, bottom: 22),
      padding: EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: HexColor.fromHex(styleModel?.officalWxchat?.bgColor ?? '#FFFFFF'),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            styleModel?.officalWxchat?.title ?? '官方微信',
            style: TextStyle(
              color: HexColor.fromHex(styleModel?.officalWxchat?.titleColor ?? '#3C3C3C'),
              fontSize: 15,
              fontWeight: FontWeight.bold,
            ),
          ),
          _createOfficalWxchatListWidget(styleModel),
        ],
      ),
    );
  }

  Widget _createOfficalWxchatListWidget(WechatTeacherStyleModel styleModel) {
    List<Widget> widgets = [];
    int length = styleModel?.officalWxchat?.list?.length ?? 0;
    if (length > 0) {
      styleModel.officalWxchat.list.forEach((element) {
        widgets.add(WechatTeachetItem(element, styleModel));
        widgets.add(Container(
            margin: EdgeInsets.only(top: 4, bottom: 4), width: double.infinity, height: 0.5, color: Color(0xffebebeb)));
      });
      widgets.removeLast();
    } else {
      widgets.add(Container());
    }

    return Column(
      children: widgets,
    );
  }
}
