import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:zhiying_comm/zhiying_comm.dart';

import '../activity_dialog/activity_dialog_model.dart';
import 'advertising_model.dart';

///
/// 广告弹窗接口
///
class AdvertisingDialog extends StatelessWidget {
  final AdvertisingDialogModel model;

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

  static Future show(BuildContext context) async {
    try {
      Map result = await NetUtil.post('/api/v1/app/push_dialog', method: NetMethod.GET);
      if (!EmptyUtil.isEmpty(result)) {
        var dialogList = result['data'];
        for (var item in dialogList) {
          if (!EmptyUtil.isEmpty(item)) {
            AdvertisingDialogModel model = AdvertisingDialogModel.fromJson(item);
            if (!EmptyUtil.isEmpty(model)) {
              await Future.delayed(Duration(milliseconds: model?.interval*1000));
              await showCupertinoDialog(context: context, builder: (_) => AdvertisingDialog(model));
            }
          }
        }
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
  }

  /// 跳转
  void _jumpTo(BuildContext context) {
    Navigator.maybePop(context);
    RouterUtil.route(SkipModel.fromJson(json.decode(model?.skip)), json.decode(model?.skip), context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Container(
        width: double.infinity,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            /// 图片
            GestureDetector(
              onTap: () => _jumpTo(context),
              behavior: HitTestBehavior.opaque,
              child: Container(
                // margin: const EdgeInsets.symmetric(horizontal: 40),
                width: MediaQuery.of(context).size.width * 0.7,
                child: CachedNetworkImage(
                  fadeInDuration: Duration(milliseconds: 0),
                  imageUrl: model?.image ?? '',
                  fit: BoxFit.fitWidth,
                ),
              ),
            ),

            /// 关闭按钮
            GestureDetector(
              child: Container(
                  width: 30,
                  height: 30,
                  margin: EdgeInsets.only(top: 10),
                  child: Icon(
                    Icons.cancel,
                    color: Colors.white,
                    size: 32,
                  )),
              onTap: () {
                Navigator.pop(context);
              },
            )
          ],
        ),
      ),
    );
  }
}
