import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:zhiying_base_widget/dialog/global_dialog/policy_dialog/policy_dialog.dart';
import 'package:zhiying_base_widget/models/app_config_model.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:zhiying_base_widget/utils/contants.dart';
import 'package:zhiying_base_widget/widgets/home/home_quick_entry/cached_network_image_util.dart';
import 'package:zhiying_comm/util/shared_prefe_util.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:zhiying_base_widget/utils/over_scroll_behavior.dart' as Scroll;

class GuidePage extends StatefulWidget {
  final GuideData model;
  final List<Uint8List> imageDatas;
  final List<Uint8List> bgImageDatas;

  const GuidePage(this.model, this.imageDatas, this.bgImageDatas, {Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _GuidePageState();
}

class _GuidePageState extends State<GuidePage> {
  @override
  void initState() {
    Future.delayed(Duration(milliseconds: 100), () {
      showPlolicy();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    List<int> list = List.generate(widget.imageDatas?.length, (index) => index);
    return WillPopScope(
      onWillPop: () async => false, // 拦截Android返回键
      child: Material(
        color: Colors.white,
        child: Theme(
          data: ThemeData(splashFactory: NoSplashFactory()),
          child: ScrollConfiguration(
            behavior: Scroll.OverScrollBehavior(),
            child: Swiper(
              physics: ClampingScrollPhysics(),
              itemBuilder: (BuildContext context, int index) {
                // return CachedNetworkImage(imageUrl: widget.model.images[index],fit: BoxFit.cover,);
                Uint8List bgImage;
                if (widget.bgImageDatas.length > index) {
                  bgImage = widget?.bgImageDatas[index];
                }

                return Stack(
                  alignment: Alignment.center,
                  children: <Widget>[
                    Container(
                        width: double.infinity,
                        height: double.infinity,
                        decoration: BoxDecoration(
                            image: DecorationImage(
                                image: bgImage != null
                                    ? Image.memory(
                                        bgImage,
                                      ).image
                                    : CachedNetworkImageProvider(""),
                                fit: BoxFit.fill)),
                        child: Center(
                            child: widget.imageDatas[index] != null
                                ? Image.memory(
                                    widget.imageDatas[index],
                                    fit: BoxFit.fitWidth,
                                  )
                                : Container(
                                    color: Colors.white,
                                  ))),
                    index == widget?.bgImageDatas?.length - 1
                        ? Positioned(
                            left: 0,
                            right: 0,
                            bottom: 110,
                            child: Center(
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Container(
                                    alignment: Alignment.center,
                                    height: 46,
                                    width: 180,
                                    decoration: BoxDecoration(
                                        color: HexColor.fromHex(widget?.model?.btnBgColor ?? ""),
                                        borderRadius: BorderRadius.circular(45),
                                        boxShadow: [BoxShadow(color: HexColor.fromHex(widget?.model?.btnBgColor), offset: Offset(1, 2), blurRadius: 6)]),
                                    child: Text(
                                      widget?.model?.btnText ?? "",
                                      style: TextStyle(color: HexColor.fromHex(widget?.model?.btnTextColor ?? ""), fontSize: 16, height: 1.1),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          )
                        : Container()
                  ],
                );
              },
              loop: false,
              itemCount: widget.imageDatas?.length ?? 0,
              pagination: widget?.model?.indicatorType != "1"
                  ? null
                  : widget?.model?.indicatorCssType == "2"
                      ? SwiperCustomPagination(builder: (BuildContext context, SwiperPluginConfig config) {
                          return Align(
                            alignment: Alignment(0.0, 1),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: list.map((index) {
                                return SafeArea(
                                  child: Container(
                                    margin: EdgeInsets.only(bottom: 40, left: 5, right: 5),
                                    height: 4,
                                    width: 20,
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(10),
                                        color: index == config.activeIndex
                                            ? HexColor.fromHex(widget?.model?.indicatorChooseColor)
                                            : HexColor.fromHex(widget?.model?.indicatorUnchooseColor)),
                                  ),
                                );
                              }).toList(),
                            ),
                          );
                        })
                      : SwiperCustomPagination(builder: (BuildContext context, SwiperPluginConfig config) {
                          return Align(
                            alignment: Alignment(0.0, 1),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: list.map((index) {
                                return SafeArea(
                                  child: Container(
                                    margin: EdgeInsets.only(bottom: 40, left: 5, right: 5),
                                    height: 10,
                                    width: 10,
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(10),
                                        color: index == config.activeIndex
                                            ? HexColor.fromHex(widget?.model?.indicatorChooseColor)
                                            : HexColor.fromHex(widget?.model?.indicatorUnchooseColor)),
                                  ),
                                );
                              }).toList(),
                            ),
                          );
                        }),
              onIndexChanged: (index) {},
              onTap: (index) {
                if (index == widget.model.guideCss.length - 1) {
                  Navigator.pop(context, true);
                }
              },
            ),
          ),
        ),
      ),
    );
  }

  void showPlolicy() async {
    ///协议弹窗
    String isShowPolicy = await SharedPreferencesUtil.getStringValue(Constants.isShowPolicy);
    if (isShowPolicy == null || isShowPolicy != '1') {
      NativeUtil.notifyInitSuccess();
      bool isAccept = await PolicyDialog.show(context);
      if (!isAccept) {
        exit(0);
      } else {
        await SharedPreferencesUtil.setStringValue(Constants.isShowPolicy, "1");
      }
    }
  }
}

class NoSplashFactory extends InteractiveInkFeatureFactory {
  InteractiveInkFeature create(
      {MaterialInkController controller,
      RenderBox referenceBox,
      Offset position,
      Color color,
      TextDirection textDirection,
      bool containedInkWell = false,
      rectCallback,
      BorderRadius borderRadius,
      ShapeBorder customBorder,
      double radius,
      onRemoved}) {
    return _NoInteractiveInkFeature(controller: controller, referenceBox: referenceBox);
  }
}

class _NoInteractiveInkFeature extends InteractiveInkFeature {
  _NoInteractiveInkFeature({
    MaterialInkController controller,
    RenderBox referenceBox,
  }) : super(controller: controller, referenceBox: referenceBox);

  void paintFeature(Canvas canvas, Matrix4 transform) {}
}
