import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html/image_render.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:huixiang/retrofit/data/activity.dart';
import 'package:huixiang/retrofit/data/article.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:huixiang/view_widget/share_dialog.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sharesdk_plugin/sharesdk_defines.dart';
import 'package:sharesdk_plugin/sharesdk_interface.dart';
import 'package:sharesdk_plugin/sharesdk_map.dart';
import 'package:video_player/video_player.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_html/src/replaced_element.dart';
import 'package:flutter/cupertino.dart';
import 'package:chewie/src/chewie_progress_colors.dart' as chewie;
import 'package:chewie/chewie.dart';

class StoreDetailsPage extends StatefulWidget {
  final Map<String, dynamic> arguments;

  ///富文本 文章  活动
  StoreDetailsPage({this.arguments});

  @override
  State<StatefulWidget> createState() {
    return _StoreDetailsPage();
  }
}

class _StoreDetailsPage extends State<StoreDetailsPage> {
  ApiService apiService;

  @override
  void initState() {
    super.initState();

    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();

    SharedPreferences.getInstance().then((value) {
      apiService =
          ApiService(Dio(), context: context, token: value.getString("token"));
      queryHtml();
    });
  }

  Activity activity;
  Article article;

  queryHtml() async {
    BaseData baseData = await apiService.informationInfo(
        widget.arguments["activityId"] ?? widget.arguments["articleId"]);

    if (baseData != null && baseData.isSuccess) {
      if (widget.arguments.containsKey("activityId")) {
        activity = Activity.fromJson(baseData.data);
      } else if (widget.arguments.containsKey("articleId")) {
        article = Article.fromJson(baseData.data);
      }
      setState(() {});
    }
  }

  share() async {
    SSDKMap params = SSDKMap()
      ..setGeneral(
          activity != null
              ? activity.mainTitle
              : article != null
                  ? article.mainTitle
                  : "",
          activity != null
              ? activity.viceTitle
              : article != null
                  ? article.viceTitle
                  : "",
          [
            activity != null
                ? activity.coverImg
                : article != null
                    ? article.coverImg
                    : "",
          ],
          activity != null
              ? activity.coverImg
              : article != null
                  ? article.coverImg
                  : "",
          "",
          "http://hx.lotus-wallet.com/index.html?id=${widget.arguments["activityId"] ?? widget.arguments["articleId"]}",
          "",
          "",
          "",
          "",
          SSDKContentTypes.webpage);

    debugPrint(activity != null
        ? activity.coverImg
        : article != null
            ? article.coverImg
            : "");

    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        builder: (context) {
          return ShareDialog((platform) {
            if (platform == ShareSDKPlatforms.line) {
              params.map["type"] = SSDKContentTypes.text.value;
              params.map["text"] =
                  "${activity != null ? activity.viceTitle : article != null ? article.viceTitle : ""}  http://hx.lotus-wallet.com/index.html?id=${widget.arguments["activityId"] ?? widget.arguments["articleId"]}";
            }
            SharesdkPlugin.share(platform, params,
                (state, userData, contentEntity, error) {
              print("share!$state");
            });
          });
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        action: Container(
          margin: EdgeInsets.only(right: 10),
          child: GestureDetector(
            onTap: () {
              share();
            },
            child: Icon(
              Icons.share,
              size: 24,
              color: Colors.black,
            ),
          ),
        ),
        background: Color(0xFFF7F7F7),
        leadingColor: Colors.black,
        title: activity != null
            ? activity.mainTitle
            : article != null
                ? article.mainTitle
                : "",
        titleSize: 18.sp,
        titleColor: Colors.black,
      ),
      body: Container(
        child: SingleChildScrollView(
          physics: BouncingScrollPhysics(),
          child: Column(
            children: [
              Container(
                padding: EdgeInsets.all(12),
                alignment: Alignment.centerLeft,
                child: Text(
                  activity != null
                      ? activity.mainTitle
                      : article != null
                          ? article.mainTitle
                          : "",
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF353535),
                  ),
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 12.w),
                child: Row(
                  children: [
                    InkWell(
                      child: Text(
                        "${activity != null ? activity.storeName : (article != null && article.author != null) ? article.author.name : ""}",
                        style: TextStyle(
                          fontWeight: FontWeight.normal,
                          fontSize: 14.sp,
                          color: Colors.blue,
                        ),
                      ),
                      onTap: () {
                        if (activity != null) {
                          if (widget.arguments["source"] != null
                              && widget.arguments["source"] == activity.storeId) {
                            Navigator.of(context).pop();
                          } else {
                            Navigator.of(context).pushNamed(
                                '/router/union_detail_page',
                                arguments: {"id": activity.storeId, "source": widget.arguments["activityId"]});
                          }
                        }
                      },
                    ),
                    SizedBox(
                      width: 10.w,
                    ),
                    Text(
                      activity != null
                          ? activity.createTime
                          : article != null
                              ? article.createTime
                              : "",
                      style: TextStyle(
                        fontWeight: FontWeight.normal,
                        fontSize: 12.sp,
                        color: Colors.grey,
                      ),
                    )
                  ],
                ),
              ),
              Html(
                data: activity != null
                    ? activity.content
                    : article != null
                        ? article.content
                        : "",
                customImageRenders: {
                  base64DataUriMatcher(): base64ImageRender(),
                  assetUriMatcher(): assetImageRender(),
                  networkSourceMatcher(extension: "svg"):
                      svgNetworkImageRender(),
                  networkSourceMatcher(): networkImageRender(
                    loadingWidget: () {
                      return Container();
                    },
                    // mapUrl: (url) {
                    //     print("objectUrl: $url");
                    //     return "$url?imageMogr2/format/webp/blur/1x0/quality/75";
                    // },
                  ),
                },
                customRender: {
                  "video": (context, parsedChild, attributes, element) {
                    return videoWidget(
                        double.tryParse(attributes['width'] ?? ""),
                        double.tryParse(element.attributes['height'] ?? ""),
                        element.children.first.attributes["src"],
                        element.attributes["sandbox"]);
                  },
                  "iframe": (context, parsedChild, attributes, element) {
                    return videoWidget(
                        double.tryParse(attributes['width'] ?? ""),
                        double.tryParse(element.attributes['height'] ?? ""),
                        element.children.first.attributes["src"],
                        element.attributes["sandbox"]);
                  },
                  "audio": (context, parsedChild, attributes, element) {
                    final sources = <String>[
                      if (element.attributes['src'] != null)
                        element.attributes['src'],
                    ];
                    if (sources == null ||
                        sources.isEmpty ||
                        sources.first == null) {
                      return EmptyContentElement();
                    }
                    return audioWidget(
                        attributes['controls'] != null,
                        attributes['loop'] != null,
                        attributes['autoplay'] != null,
                        sources,
                        context.style.width ?? 300.w);
                  },
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  VideoPlayerController videoPlayerController;
  ChewieController chewieAudioController;
  Chewie chewies;

  Widget videoWidget(double width, double height, src, sandboxMode) {
    print("src :  $src");
    return Container(
      width: MediaQuery.of(context).size.width,
      height: (MediaQuery.of(context).size.width) / (width / height),
      child: chewies = Chewie(
        controller: chewieAudioController = ChewieController(
          videoPlayerController: videoPlayerController =
              VideoPlayerController.network(
            src,
          ),
          aspectRatio: width / height,
          //宽高比
          autoPlay: !true,
          //自动播放
          looping: false,
          //循环播放
          // 拖动条样式颜色
          materialProgressColors: chewie.ChewieProgressColors(
            playedColor: Colors.white,
            handleColor: Colors.white,
            backgroundColor: Colors.grey,
            bufferedColor: Colors.transparent,
          ),
          autoInitialize: true,
        ),
      ),
    );
  }

  Widget audioWidget(showControls, loop, autoplay, src, width) {
    return Container(
      width: width,
      child: chewies = Chewie(
        controller: chewieAudioController = ChewieController(
          videoPlayerController: VideoPlayerController.network(
            src.first ?? "",
          ),
          autoPlay: autoplay,
          looping: loop,
          showControls: showControls,
          autoInitialize: true,
        ),
      ),
    );
  }

  @override
  void dispose() {
    if (chewieAudioController != null) chewieAudioController.dispose();

    if (videoPlayerController != null) videoPlayerController.dispose();

    super.dispose();
  }
}