import 'dart:math';

import 'package:flutter/material.dart';
import 'package:loading_indicator/loading_indicator.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

import 'turn_chain_style_model.dart';

class TurnChainLoading {
  static OverlayEntry _overlayEntry;

  static Future show(
    BuildContext context,
    TurnChainStyleModel model,
  ) async {
    dismiss();
    _overlayEntry = new OverlayEntry(builder: (context) {
      return GestureDetector(
        onTap: dismiss,
        child: Container(
          color: Colors.black.withOpacity(0.3),
          child: TurnChainDialogWidget(model),
        ),
      );
    });

    try {
      //插入到 Overlay中显示 OverlayEntry
      Overlay.of(context).insert(_overlayEntry);
    } catch (e, s) {
      Logger.error(e, s);
    }
  }

  static dismiss() {
    try {
      _overlayEntry?.remove();
      _overlayEntry = null;
    } catch (e, s) {
      Logger.error(e, s);
    }
  }
}

class TurnChainDialogWidget extends StatelessWidget {
  TurnChainStyleModel model;

  TurnChainDialogWidget(this.model);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        return Future.value(false);
      },
      child: Scaffold(
        backgroundColor: HexColor.fromHex('#54555555'),
        body: Center(
          child: Container(
              height: 250,
              width: 260,
              // margin: const EdgeInsets.symmetric(horizontal: 70),
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: HexColor.fromHex('#FEFFFE'),
                borderRadius: BorderRadius.circular(13),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  /// 跳转图标
                  _buildTransitionIconWidget(),

                  /// 正在跳转提示文字
                  Padding(padding: const EdgeInsets.only(top: 12), child: _buildJumpTipWidget()),

                  /// 返利和券
                  Padding(padding: const EdgeInsets.only(top: 13), child: _buildCouponAndRebateWidget()),

                  // /// 共省提示
                  Padding(padding: const EdgeInsets.only(top: 14), child: _buildSaveMoneyTipWidget()),

                  /// 注意提示文字
                  Padding(padding: const EdgeInsets.only(top: 8, left: 9.5, right: 9.5), child: _buildNoticeWidget()),
                ],
              )),
        ),
      ),
    );
  }

  /// 过渡图标
  Widget _buildTransitionIconWidget() {
    return Container(
      height: 50,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Container(
            margin: const EdgeInsets.only(right: 8),
            width: 50,
            height: 50,
            child: CachedNetworkImage(
              imageUrl: model?.appLogo ?? '',
            ),
          ),
          Container(
            height: 10,
            width: 34,
            child: LoadingIndicator(
              indicatorType: Indicator.ballPulse,
              color: HexColor.fromHex('#FE7978'),
              colors: [
                HexColor.fromHex('#FF2020'),
                HexColor.fromHex('#FE7978'),
                HexColor.fromHex('#FEBCBB'),
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 8),
            width: 50,
            height: 50,
            // color: Colors.red,
            child: CachedNetworkImage(
              imageUrl: _getProviderIcon(),
            ),
          ),
        ],
      ),
    );
  }

  String _getProviderIcon() {
    int length = model?.style?.providerIcons?.length ?? 0;
    String result = '';
    if (length > 0) {
      model.style.providerIcons.forEach((element) {
        if (element.type == model.provider) {
          result = element?.img ?? '';
        }
      });
    }
    return result;
  }

  /// 跳转文字提示
  Widget _buildJumpTipWidget() {
    return Text(
      '${model?.style?.text}${model.providerName}',
      style: TextStyle(color: HexColor.fromHex('#333333'), fontSize: 15, fontWeight: FontWeight.bold),
    );
  }

  /// 返利与优惠券
  Widget _buildCouponAndRebateWidget() {
    return Container(
      height: 30,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          _buildCustomButtonWidget(
              text: model?.style?.leftBtnText ?? '返利',
              textColor: model?.style?.leftBtnTextColor ?? '#FEFFFE',
              number: !EmptyUtil.isEmpty(model?.commission) ? model?.commission : '0.00',
              numberColor: model?.style?.leftBtnTextColor ?? '#FEFFFE',
              bgColor: model?.style?.leftBtnColor ?? '#FF2020',
              bgImg: model?.style?.leftBtnImg ?? ''),
          const SizedBox(width: 8),
          _buildCustomButtonWidget(
              text: model?.style?.rightBtnText ?? '券',
              textColor: model?.style?.rightBtnTextColor ?? '#FEFFFE',
              number: !EmptyUtil.isEmpty(model?.coupon) ? model?.coupon : '0.00',
              numberColor: model?.style?.rightBtnTextColor ?? '#FEFFFE',
              bgColor: model?.style?.rightBtnColor ?? '#FF2020',
              bgImg: model?.style?.rightBtnImg ?? ''),
        ],
      ),
    );
  }

  Widget _buildCustomButtonWidget({String text, String textColor, String number, String numberColor, String bgColor, String bgImg}) {
    return Container(
        height: 30,
        width: 95,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            color: !EmptyUtil.isEmpty(bgImg) ? null : HexColor.fromHex(bgColor),
            image: EmptyUtil.isEmpty(bgImg)
                ? null
                : DecorationImage(
                    image: CachedNetworkImageProvider(bgImg ?? ''),
                  )),
        child: RichText(
          text: TextSpan(children: [
            TextSpan(
              text: text ?? '',
              style: TextStyle(color: HexColor.fromHex(textColor), fontSize: 13),
            ),
            TextSpan(
              text: number ?? '',
              style: TextStyle(color: HexColor.fromHex(numberColor), fontFamily: 'Din', package: 'zhiying_comm', fontSize: 13),
            ),
          ]),
        ));
  }

  /// 总共省下多少钱的提示
  Widget _buildSaveMoneyTipWidget() {
    return RichText(
      text: TextSpan(children: [
        TextSpan(text: model?.style?.saveMomenyText ?? '共省 ¥', style: TextStyle(color: HexColor.fromHex(model?.style?.saveMomenyColor ?? '#FF2020'), fontSize: 13)),
        TextSpan(
            text: model?.totalSave ?? '0.00',
            style: TextStyle(color: HexColor.fromHex(model?.style?.saveMomenyColor ?? '#FF2020'), fontSize: 18, fontFamily: 'Din', package: 'zhiying_comm')),
        // TextSpan(text: '.99', style: TextStyle(color: HexColor.fromHex(model?.style?.saveMomenyColor ?? '#FF2020'), fontSize: 13, fontFamily: 'Din', package: 'zhiying_comm')),
      ]),
    );
  }

  /// 注意提示文字提示
  Widget _buildNoticeWidget() {
    return Text(
      model?.style?.tipText ?? '注意：使用红包下单，会导致收益变少，或没有收益！',
      textAlign: TextAlign.center,
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
      style: TextStyle(color: HexColor.fromHex(model?.style?.tipColor ?? '#999999'), fontSize: 11),
    );
  }
}
