import 'dart:io';

import 'package:flutter/material.dart';
import 'package:zhiying_base_widget/widgets/goods_details/coupon/bloc/bloc.dart';
import 'package:zhiying_base_widget/widgets/goods_details/coupon/bloc/counpon_repository.dart';
import 'package:zhiying_base_widget/widgets/goods_details/coupon/counpon_sk.dart';
import 'package:zhiying_base_widget/widgets/goods_details/coupon/model/counpon_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';
import 'package:zhiying_comm/util/turn_chain/turn_chain_util.dart';

///
///  优惠券widget
///
class CounponWidget extends StatelessWidget {
  final Map<String, dynamic> model;

  const CounponWidget(this.model);

  @override
  Widget build(BuildContext context) {
    // return Container();
    return BlocProvider<CounponBloc>(
      create: (_) => CounponBloc(repository: CounponRepository()), //..add(CounponInitEvent(model: model)),
      child: CounponWidgetContainer(
        model,
        key: UniqueKey(),
      ),
    );
  }
}

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

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

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

class _CounponWidgetContainerState extends State<CounponWidgetContainer> {
  UserInfoModel _user;

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

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

  /// 点击领取
  void _onJump(CounponModel model) async{
    TurnChainUtil.openReceiveCoupon(context, _user, model?.good_id, model.provider, model?.convertArgs?.toJson());
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<CounponBloc, CounponState>(
      listener: (context, state) {},
      buildWhen: (prev, current) {
        if (current is CounponErrorState) {
          return false;
        }
        return true;
      },
      builder: (context, state) {
        if (state is CounponLoadedState) {
          return _getMainWidget(state.model);
        }
        return CounponSkeleton();
      },
    );
  }

  /// 主视图
  Widget _getMainWidget(CounponModel model) {
    return Visibility(
      visible: !EmptyUtil.isEmpty(model?.coupon_price),
      child: GestureDetector(
        onTap: () => _onJump(model),
        behavior: HitTestBehavior.opaque,
        child: Container(
          width: double.infinity,
          decoration: BoxDecoration(
            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))
            )
          ),
          margin: EdgeInsets.only(top: ParseUtil.stringParseDouble(model?.topMargin), left: ParseUtil.stringParseDouble(model?.leftRightMargin), right: ParseUtil.stringParseDouble(model?.leftRightMargin)),
          padding: const EdgeInsets.only(left: 12.5, right: 12.5, top: 6, bottom: 6),
          child: Container(
            // color: Colors.red,
            width: double.infinity,
            padding: const EdgeInsets.only(left: 18.5, top: 12, bottom: 14),
            decoration: BoxDecoration(
                image: DecorationImage(
                    image: CachedNetworkImageProvider(
                      model?.bgImage ?? '',
                    ),
                    fit: BoxFit.fill)),
            alignment: Alignment.centerLeft,
            child: Row(
              children: <Widget>[
                /// 价格
                _getPriceWidget(model),
                const SizedBox(width: 7.5),

                /// 有效期
                _getTimeWidget(model)
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 价格
  Widget _getPriceWidget(CounponModel model) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        /// 价格类型
        Text('¥ ', style: TextStyle(fontSize: 15, color: HexColor.fromHex(model?.couponPriceColor ?? '#FFFFFF'))),

        /// 价格
        Text(model?.coupon_price ?? '100',
            style: TextStyle(fontSize: 30, color: HexColor.fromHex(model?.couponPriceColor ?? '#FFFFFF'), fontFamily: 'Din', package: 'zhiying_comm')),
      ],
    );
  }

  /// 名称与有效期
  Widget _getTimeWidget(CounponModel model) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        /// 标题
        Text(model?.couponText ?? '优惠券', style: TextStyle(fontSize: 17, color: HexColor.fromHex(model?.couponTextColor ?? '#FFFFFF'))),

        /// 到期时间
        Visibility(
            visible: !EmptyUtil.isEmpty(model?.coupon_endtime),
            child: Text(model?.coupon_endtime ?? '有效期至2020-10-01', style: TextStyle(fontSize: 10, color: HexColor.fromHex(model?.couponTimeColor ?? '#FFFFFF'))))
      ],
    );
  }
}