import 'dart:convert' as convert;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/goods_share_content_bloc.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/goods_share_editor/goods_share_editor.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/goods_share_image/goods_share_image_model.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/models/goods_share_temp_add_model.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/widgets/good_share_msg.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/widgets/goods_share_edit.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/widgets/goods_share_item.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/widgets/goods_share_link_widget.dart';
import 'package:zhiying_base_widget/widgets/public/custom_button/custom_bottom.dart';
import 'package:zhiying_base_widget/widgets/public/custom_button/custom_button_model.dart';
import 'package:zhiying_base_widget/widgets/share/models/share_data_model.dart';
import 'package:zhiying_base_widget/widgets/share/share_alert.dart';
import 'package:zhiying_comm/util/base_bloc.dart';

class GoodsShareLink extends StatefulWidget {
  final Map<String, dynamic> model;
  final Map<String, dynamic> params;

  final String shareType;

  const GoodsShareLink(this.model, this.params, this.shareType, {Key key})
      : super(key: key);

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

class _GoodsShareLinkState extends State<GoodsShareLink> {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<GoodsShareContentBloc>(
      bloc: GoodsShareContentBloc(),
      child:
          _GoodsShareLinkContent(widget.model, widget.params, widget.shareType),
    );
  }
}

class _GoodsShareLinkContent extends StatefulWidget {
  final Map<String, dynamic> model;
  final Map<String, dynamic> params;
  final String shareType;

  // final GoodsShareTempDataModel datas;

  const _GoodsShareLinkContent(this.model, this.params, this.shareType,
      {Key key})
      : super(key: key);

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

class _GoodsShareLinkContentState extends State<_GoodsShareLinkContent>
    with AutomaticKeepAliveClientMixin {
  GoodsShareImageModel _style;
  Map<int, String> _images = Map();
  List<Widget> widgets = List();
  String _content = '';

  GoodsShareContentBloc _bloc;

  // 分享数据
  final ShareDataModel _shareModel = ShareDataModel();

  @override
  // 切换Tab导航栏保持页面状态
  bool get wantKeepAlive => true;

  @override
  void initState() {
    String data = widget.model['data'];
    var d = convert.jsonDecode(data);
    _style = GoodsShareImageModel.fromJson(Map<String, dynamic>.from(d));
    // _content = widget.datas.shareContent;
    _bloc = BlocProvider.of<GoodsShareContentBloc>(context);
    _bloc.loadData(widget.shareType, widget.params);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<GoodsShareTempDataModel>(
        stream: _bloc.outData,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          GoodsShareTempDataModel data = snapshot.data;
          widgets.clear();
          if (data != null) {
            if (_content == null || _content == '') {
              _content = data.shareContent;
            }
            widgets.add(GoodsShareItem(
              imgHeader: _style?.cssList?.headerImage ?? '',
              imgCheck: _style?.cssList?.unChooseImage ?? '',
              imgCheckSelected: _style?.cssList?.chooseImage ?? '',
              enabled: false,
              child: GoodsShareLinkWidget(
                title: data?.title ?? '',
                desc: data?.content ?? '',
                imgGoods: data?.imgUrl ?? '',
                icon: data?.appLogo ?? '',
                name: data?.appName ?? '',
              ),
            ));
            widgets.add(GoodsShareItem(
              imgHeader: _style?.cssList?.headerImage ?? '',
              imgCheck: _style?.cssList?.unChooseImage ?? '',
              imgCheckSelected: _style?.cssList?.chooseImage ?? '',
              enabled: false,
              child: GoodsShareEdit(
                _content,
                data,
                imgCheck: _style?.cssList?.unChooseImage ?? '',
                imgCheckSelected: _style?.cssList?.chooseImage ?? '',
                onCopyClick: () {
                  Clipboard.setData(ClipboardData(text: _content));
                  Fluttertoast.showToast(msg: '文案已复制');
                },
                onEditorClick: () {
                  Fluttertoast.showToast(msg: '正在开发中');
                  return;
                  Navigator.push(
                      context,
                      CupertinoPageRoute(
                          builder: (context) => GoodsShareEditor(_style)));
                },
                onTempChange: (temp) {
                  setState(() {
                    _content = data.shareContent + temp;
                  });
                },
              ),
              onSelected: (isSelected) {
                // _isContentSelected = isSelected;
                // _shareModel.content = isSelected ? _content : '';
              },
            ));
            for (String message in _style.customContent) {
              widgets.add(
                GoodsShareItem(
                  imgHeader: _style?.cssList?.headerImage ?? '',
                  imgCheck: _style?.cssList?.unChooseImage ?? '',
                  imgCheckSelected: _style?.cssList?.chooseImage ?? '',
                  enabled: false,
                  child: GoodsShareMessage(message),
                ),
              );
            }
          }

          return Column(
            children: <Widget>[
              Expanded(
                child: Container(
                  margin: EdgeInsets.only(bottom: 4),
                  padding: EdgeInsets.only(top: 10),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(8),
                          bottomRight: Radius.circular(8))),
                  child: SingleChildScrollView(
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: widgets),
                  ),
                ),
              ),
              _createBottom(),
            ],
          );
        });
  }

  Widget _createBottom() {
    Map<String, dynamic> shareImages = _style?.cssList?.shareLink;
    if (shareImages == null) {
      return Container();
    }
    CustomButtonModel btnCopy = CustomButtonModel.fromJson(
        Map<String, dynamic>.from(shareImages['copy_btn']));
    CustomButtonModel btnShare = CustomButtonModel.fromJson(
        Map<String, dynamic>.from(shareImages['share_btn']));
    return SafeArea(
      child: Container(
        margin: EdgeInsets.only(left: 12.5, right: 12.5, top: 4, bottom: 4),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            btnCopy == null
                ? Container()
                : Container(
                    width: 110,
                    height: 36,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(18),
                    ),
                    child: CustomButton(btnCopy)),
            btnShare == null
                ? Container()
                : GestureDetector(
                    child: Container(
                        margin: EdgeInsets.only(left: 5),
                        width: 110,
                        height: 36,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(18),
                        ),
                        child: CustomButton(btnShare)),
                    onTap: () {
                      _showShare();
                    },
                  ),
          ],
        ),
      ),
    );
  }

  void _showShare() async {
    List<String> images = List();
    for (int index = 0; index < _style.customImage.length; index++) {
      if (_images.containsKey(index)) {
        images.add(_images[index]);
      }
    }
    if (images.length >= 0) {
      _shareModel.image = images;
    }
    showCupertinoModalPopup(
      context: context,
      builder: (context) => ShareAlert(
        _shareModel,
        'pub.flutter.share_icon',
        // child: GoodsShareAlertContent(),
      ),
    );
  }
}
