import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_alibc/alibc_model.dart';
import 'package:flutter_alibc/flutter_alibc.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/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';

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

  const GoodsDetailsFooterWidget(this.model);

  @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: GooddsDetailsFooterContainer(model),
      ),
    );
  }
}

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

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

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

class _GooddsDetailsFooterContainerState
    extends State<GooddsDetailsFooterContainer> {
  UserInfoModel _user;

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

  /// 收藏
  void _collectOnClick() {}

  /// 分享
  void _shareOnClick(GoodsDetailsFooterModel model) {
    print(_user?.toString());
    if (_user?.token == null || _user.token == '') {
      print('need login...');
      RouterUtil.goLogin(context);
      return;
    }
    Navigator.of(context).push(
        MaterialPageRoute(builder: (context) => GoodsSharePage(widget.model)));
  }

  /// 自购省
  void _savemoneyOnClick(GoodsDetailsFooterModel model) async {
    print(_user?.toString());
    if (_user?.token == null || _user.token == '') {
      print('need login...');
      RouterUtil.goLogin(context);
      return;
    }

    String d = widget.model['data'];
    Map<String, dynamic> data = jsonDecode(d);

    Map shareArgs = data['share_url_args'] ?? {};
    String shopType = shareArgs['type'];

    if (data.containsKey('buy_url')) {
      String url = data['buy_url'];
      if (url == null || url == '') {
        Fluttertoast.showToast(msg: '购买链接不存在');
        return;
      }
      if (shopType == 'taobao') {
        TradeResult result = await FlutterAlibc.openByUrl(url: url);
        Logger.debug('${result.errorCode}   ${result.errorMessage} ');
      } else {
        RouterUtil.openWebview(url, context);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    _user = Provider.of<UserInfoNotifier>(context).userInfo;
    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: 21, 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: Colors.white,
        ),
        child: Container(height: 44, child: _getMainWidet(model)),
      ),
    );
  }

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

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

  /// 首页 和 收藏
  Widget _getLeftWidget(GoodsDetailsFooterModel model) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () => _openHome(),
            child: Padding(
              padding: const EdgeInsets.only(right: 35),
              child: _getCustomWidget(model?.home ?? '首页',
                  model?.home_color ?? '999999', model?.home_icon ?? ''),
            )),
        GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () => _collectOnClick(),
            child: Padding(
                padding: const EdgeInsets.only(right: 0),
                child: _getCustomWidget(
                    model?.collect ?? '收藏',
                    model?.collect_color ?? '999999',
                    model?.collect_icon ?? '')))
      ],
    );
  }

  /// 分享赚与自购省
  Widget _getRightWidget(GoodsDetailsFooterModel model) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        _getFxzButton(model),
        _getZgsButton(model),
      ],
    );
  }

  /// 分享赚，
  Widget _getFxzButton(GoodsDetailsFooterModel model) {
    return GestureDetector(
      onTap: () => _shareOnClick(model),
      child: Container(
        alignment: Alignment.center,
        height: 44,
        width: 110,
        // 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),
            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?.share_earn_val_color ?? 'FFFFFF')),
                  children: [
                    TextSpan(
                        text: model?.share_value ?? '0.0',
                        style: TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.bold,
                            color: HexColor.fromHex(
                                model?.share_earn_color ?? '#FFFFFF'),
                            fontFamily: 'Din',
                            package: 'zhiying_base_widget')),
                  ]),
            ),
            Text(
              model?.share_earn ?? '分享赚',
              style: TextStyle(
                  color: HexColor.fromHex(model?.share_earn_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,
        width: 110,
        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),
            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?.save_earn_val_color ?? 'FFFFFF')),
                  children: [
                    TextSpan(
                        text: model?.slef_buy_value ?? '0.0',
                        style: TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.bold,
                          color: HexColor.fromHex(
                              model?.save_earn_val_color ?? '#FFFFFF'),
                          fontFamily: 'Din',
                          package: 'zhiying_base_widget',
                        )),
                  ]),
            ),
            Text(model?.save_earn ?? '自购省',
                style: TextStyle(
                    color:
                        HexColor.fromHex(model?.save_earn_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))
      ],
    );
  }
}
