import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.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_base_widget/pages/goods_share_page/goods_share_page.dart';
import 'package:zhiying_base_widget/widgets/custom/multi_nav/cached_network_image_util.dart';
import 'package:zhiying_base_widget/widgets/goods_details/footer/bloc/goods_details_footer_bloc.dart';
import 'package:zhiying_base_widget/widgets/goods_details/footer/bloc/goods_details_footer_repository.dart';
import 'package:zhiying_base_widget/widgets/goods_details/footer/goods_details_footer_sk.dart';
import 'package:zhiying_base_widget/widgets/goods_details/footer/model/goods_details_footer_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:zhiying_comm/util/turn_chain/turn_chain_util.dart';

///
/// 商品详情底部Widget
///
class GoodsDetailsFooterWidget extends StatelessWidget {
  final Map<String, dynamic> model;
  final bool isFree;

  const GoodsDetailsFooterWidget(this.model, {this.isFree = false});

  @override
  Widget build(BuildContext context) {
    return Visibility(
      visible: !EmptyUtil.isEmpty(model),
      replacement: GoodsDetailsFooterSkeleton(),
      child: BlocProvider<GoodsDetailsFooterBloc>(
        create: (_) => GoodsDetailsFooterBloc(repository: GoodsDetailsFooterRepository()),
        //..add(GoodsDetailsFooterInitEvent(model: model)),
        child: _GoodsDetailsFooterContainer(
          model,
          key: UniqueKey(),
          isFree: isFree,
        ),
      ),
    );
  }
}

class _GoodsDetailsFooterContainer extends StatefulWidget {
  final Map<String, dynamic> model;
  final bool isFree;

  const _GoodsDetailsFooterContainer(this.model, {this.isFree, Key key}) : super(key: key);

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

class _GoodsDetailsFooterContainerState extends State<_GoodsDetailsFooterContainer> {
  UserInfoModel _user;

  @override
  void initState() {
    BlocProvider.of<GoodsDetailsFooterBloc>(context).add(GoodsDetailsFooterInitEvent(model: widget?.model));
    super.initState();
  }

  @override
  void didChangeDependencies() {
    _user = Provider.of<UserInfoNotifier>(context).userInfo;
    super.didChangeDependencies();
  }

  /// 打开首页
  void _openHome() {
    // Navigator.pushAndRemoveUntil(
    //   context,
    //   CupertinoPageRoute(builder: (BuildContext context) => PageFactory.create('homePage', null)),
    //       (Route<dynamic> route) => false,
    // );

    // Navigator.popUntil(
    //   context,
    //   CupertinoPageRoute(builder: (BuildContext context) => PageFactory.create('homePage', null)),
    //   (Route<dynamic> route) => false,
    // );

    RouterUtil.goBackHomePage(context, needUpdateAuth: false);
  }

  /// 收藏
  void _collectOnClick(GoodsDetailsFooterModel model) {
    ///获取用户信息，未登录需要先登录
    var _user = Provider.of<UserInfoNotifier>(context,listen: false).userInfo;
    if (_user?.token == null || _user?.token?.length == 0) {
      RouterUtil.goLogin(context);
      return;
    }
    bool isCollect = model.isFav == '0';
    if (isCollect) {
      // 收藏
      BlocProvider.of<GoodsDetailsFooterBloc>(context).add(GoodsDetailsFooterCollectEvent(model: model?.favArgs?.toJson()));
    } else {
      // 取消收藏
      BlocProvider.of<GoodsDetailsFooterBloc>(context).add(GoodsDetailsFooterDeleteCollectEvent(model: model?.favArgs?.toJson()));
    }
  }

  /// 分享
  void _shareOnClick(GoodsDetailsFooterModel model) async {
    Map<String, dynamic> result = await TurnChainUtil.getShareTurnChain(context, _user, model?.good_id, model.provider, model.convertArgs.toJson());
    if (!EmptyUtil.isEmpty(result)) {
      model.shareUrlArgs.buyUrl = result['open_app_url'];
      Navigator.of(context).push(CupertinoPageRoute(builder: (context) => GoodsSharePage(model.toJson())));
    }
  }

  /// 自购省
  void _saveMoneyOnClick(GoodsDetailsFooterModel model) async {
    await TurnChainUtil.openReceiveCoupon(context, _user, model?.good_id, model?.provider, model?.convertArgs?.toJson(), isFree: widget?.isFree);
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<GoodsDetailsFooterBloc, GoodsDetailsFooterState>(
      listener: (context, state) {},
      buildWhen: (prev, current) {
        if (current is GoodsDetailsFooterErrorState) {
          return false;
        }
        return true;
      },
      builder: (context, state) {
        print('GoodsDetailsFooterWidget state = $state');
        if (state is GoodsDetailsFooterLoadedState) {
          return _getMainWidget(state.model);
        }
        return GoodsDetailsFooterSkeleton();
      },
    );
  }

  Widget _getMainWidget(GoodsDetailsFooterModel model) {
    double height = MediaQuery.of(context).padding.bottom;
    return SafeArea(
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.only(bottom: (height > 10 ? 0 : 8), top: 8, left: 12.5, right: 12.5),
        decoration: BoxDecoration(
            // boxShadow: [
            //   BoxShadow(color: Colors.grey[300], offset: Offset(0.0, 0.0), blurRadius: 5.0, spreadRadius: 2.0),
            //   BoxShadow(color: Colors.grey[300], offset: Offset(0.0, 0.0)),
            // ],
            color: HexColor.fromHex(model?.bgColor),
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(ParseUtil.stringParseDouble(model?.topLeftRadius)),
              topRight: Radius.circular(ParseUtil.stringParseDouble(model?.topRightRadius)),
              bottomLeft: Radius.circular(ParseUtil.stringParseDouble(model?.bottomLeftRadius)),
              bottomRight: Radius.circular(ParseUtil.stringParseDouble(model?.bottomRightRadius)),
            )),
        child: Container(height: 44, child: _getMainWidet(model)),
      ),
    );
  }

  /// 主Widget
  Widget _getMainWidet(GoodsDetailsFooterModel model) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        /// 首页与收藏
        _getLeftWidget(model),

        /// 分享赚与自购省
        Expanded(child: _getRightWidget(model)),
      ],
    );
  }

  /// 首页 和 收藏
  Widget _getLeftWidget(GoodsDetailsFooterModel model) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        Visibility(
          visible: (model?.listStyle?.leftIcon1?.isShow ?? "0") == "1" ? true : false,
          child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () => _openHome(),
              child: Padding(
                padding: const EdgeInsets.only(right: 35, left: 8),
                child: _getCustomWidget(model?.listStyle?.leftIcon1?.text ?? '首页', model?.listStyle?.leftIcon1?.color ?? '999999', model?.listStyle?.leftIcon1?.beforeIcon ?? ''),
              )),
        ),
        Visibility(
          visible: (model?.listStyle?.leftIcon2?.isShow ?? "0") == "1" ? true : false,
          child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () => _collectOnClick(model),
              child: Padding(
                  padding: const EdgeInsets.only(right: 35),
                  child: _getCustomWidget(model?.listStyle?.leftIcon2?.text ?? '收藏', model?.listStyle?.leftIcon2?.color ?? '999999',
                      model?.isFav == '0' ? model?.listStyle?.leftIcon2?.beforeIcon ?? '' : model?.listStyle?.leftIcon2?.afterIcon ?? ''))),
        )
      ],
    );
  }

  /// 分享赚与自购省
  Widget _getRightWidget(GoodsDetailsFooterModel model) {
    if (model?.listStyle?.rightIcon1.isShow == "0" || model?.listStyle.rightIcon2.isShow == "0") {
      return Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            (model?.listStyle?.rightIcon1?.isShow ?? "0") == "1" ? Expanded(child: _getFxzButton(model)) : Container(),
            (model?.listStyle?.rightIcon2?.isShow ?? "0") == "1" ? Expanded(child: _getZgsButton(model)) : Container()
          ],
        ),
      );
    }
    return Container(
      width: 220,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Expanded(child: _getFxzButton(model)),
          Expanded(child: _getZgsButton(model)),
        ],
      ),
    );
  }

  /// 分享赚，
  Widget _getFxzButton(GoodsDetailsFooterModel model) {
    return GestureDetector(
      onTap: () => _shareOnClick(model),
      child: Container(
        alignment: Alignment.center,
        height: 44,
        width: double.infinity,
        // padding: const EdgeInsets.only(left: 30, right: 30, top: 5, bottom: 5),
        decoration: BoxDecoration(
            // gradient: LinearGradient(
            //     colors: [HexColor.fromHex(/*model?.share_earn_bg1_color ??*/ '#FFCA66'), HexColor.fromHex(/*model?.share_earn_bg2_color ??*/ '#FFD961')],
            //     begin: Alignment.centerLeft,
            //     end: Alignment.centerRight),
            image: DecorationImage(image: CachedNetworkImageProvider(model?.listStyle?.rightIcon1?.bgImage ?? ''), fit: BoxFit.fitWidth),
            borderRadius: BorderRadius.only(bottomLeft: Radius.circular(25), topLeft: Radius.circular(25))),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RichText(
              text: TextSpan(text: '¥ ', style: TextStyle(fontSize: 12, color: HexColor.fromHex(model?.listStyle?.rightIcon1?.color ?? 'FFFFFF')), children: [
                TextSpan(
                    text: model?.share_value ?? '0.0',
                    style: TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.bold,
                        color: HexColor.fromHex(model?.listStyle?.rightIcon1?.color ?? '#FFFFFF'),
                        fontFamily: 'Din',
                        package: 'zhiying_comm')),
              ]),
            ),
            Text(
              model?.listStyle?.rightIcon1?.text ?? '分享赚',
              style: TextStyle(color: HexColor.fromHex(model?.listStyle?.rightIcon1?.color ?? '#FFFFFF'), fontSize: 12),
            ),
          ],
        ),
      ),
    );
  }

  /// 自购省
  Widget _getZgsButton(GoodsDetailsFooterModel model) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () => _saveMoneyOnClick(model),
      child: Container(
        alignment: Alignment.center,
        // padding: const EdgeInsets.only(left: 30, right: 30, top: 5, bottom: 5),
        height: 44,
        decoration: BoxDecoration(
            // gradient: LinearGradient(
            //     colors: [HexColor.fromHex(/*model?.save_earn_bg1_color ??*/ '#FF6969'), HexColor.fromHex(/*model?.save_earn_bg2_color ??*/ '#FF4646')],
            //     begin: Alignment.centerLeft,
            //     end: Alignment.centerRight),
            image: DecorationImage(image: CachedNetworkImageProvider(model?.listStyle?.rightIcon2?.bgImage ?? ''), fit: BoxFit.fitWidth),
            borderRadius: BorderRadius.only(bottomRight: Radius.circular(25), topRight: Radius.circular(25))),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RichText(
              text: TextSpan(text: '¥ ', style: TextStyle(fontSize: 12, color: HexColor.fromHex(model?.listStyle?.rightIcon2?.color ?? 'FFFFFF')), children: [
                TextSpan(
                    text: model?.self_buy_value ?? '0.0',
                    style: TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.bold,
                      color: HexColor.fromHex(model?.listStyle?.rightIcon2?.color ?? '#FFFFFF'),
                      fontFamily: 'Din',
                      package: 'zhiying_comm',
                    )),
              ]),
            ),
            Text(model?.listStyle?.rightIcon2?.text ?? '自购省', style: TextStyle(color: HexColor.fromHex(model?.listStyle?.rightIcon2?.color ?? '#FFFFFF'), fontSize: 12))
          ],
        ),
      ),
    );
  }

  Widget _getCustomWidget(String text, String textColor, String icon) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        /// 图标
        CachedNetworkImage(
          imageUrl: icon,
          fit: BoxFit.fill,
          width: 20,
          height: 20,
        ),
        // Container( width: 25,  margin: const EdgeInsets.only(bottom: 3), child: CachedNetworkImage(imageUrl: icon, fit: BoxFit.fill, width: 25,),),
        const SizedBox(height: 5),

        /// 图片
        Text(text, style: TextStyle(color: HexColor.fromHex(textColor), fontSize: 11))
      ],
    );
  }
}
