import 'dart:convert';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:share_extend/share_extend.dart';
import 'package:sharesdk_plugin/sharesdk_plugin.dart';
import 'package:zhiying_base_widget/utils/image_download_util/image_download_util.dart';
import 'package:zhiying_base_widget/widgets/share/models/share_data_model.dart';
import 'package:zhiying_base_widget/widgets/share/models/share_icon_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class ShareAlert extends StatelessWidget {
  final String skipIdentifier;
  final Widget child;
  final ShareDataModel model;

  const ShareAlert(this.model, this.skipIdentifier, {Key key, this.child})
      : super(key: key); // 中间视图

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), //背景
          child: Container(
            child: Column(
              children: <Widget>[
                Expanded(
                  child: Center(child: child ?? Container()),
                ),
                _ShareAlertContent(this.model, this.skipIdentifier),
              ],
            ),
          ), // 模糊化
        ),
      ),
      onTap: () {
        Navigator.of(context).pop();
      },
    );
  }
}

class _ShareAlertContent extends StatefulWidget {
  final ShareDataModel model;
  final String skipIdentifier;

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

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

class _ShareAlertContentState extends State<_ShareAlertContent> {
  List<ShareIconModel> _icons = [];

  @override
  void initState() {
    NetUtil.request('/api/v1/mod/${widget.skipIdentifier}',
        method: NetMethod.GET, onCache: (data) {
      _parseData(data);
    }, onSuccess: (data) {
      _parseData(data);
    }, onError: (err) {});

    super.initState();
  }

  void _parseData(Map<String, dynamic> data) {
    List modList = data['mod_list'];
    Map d = modList.first;
    if (d != null) {
      String dString = d['data'];
      List list = jsonDecode(dString);
      _icons = list.map((item) {
        return ShareIconModel.fromJson(Map<String, dynamic>.from(item));
      }).toList();
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {},
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(12),
            topRight: Radius.circular(12),
          ),
        ),
        child: SafeArea(
          top: false,
          child: Column(
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(top: 8, bottom: 8),
                width: 62,
                height: 4,
                decoration: BoxDecoration(
                    color: Color(0xffd8d8d8),
                    borderRadius: BorderRadius.circular(2)),
              ),
              Text(
                '分享至',
                style: TextStyle(
                    fontSize: 15,
                    color: Color(0xff333333),
                    fontWeight: FontWeight.bold),
              ),
              Container(
                margin:
                    EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 10),
                child: _createIcons(),
              ),
              GestureDetector(
                child: Container(
                  margin: EdgeInsets.only(left: 12, right: 12, bottom: 10),
                  padding: EdgeInsets.all(12),
                  decoration: BoxDecoration(
                      color: Color(0xfff3f3f3),
                      borderRadius: BorderRadius.circular(8)),
                  child: Center(
                    child: Text(
                      '取消',
                      style: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                          color: Color(0xff999999)),
                    ),
                  ),
                ),
                onTap: () {
                  Navigator.of(context).pop();
                },
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _createIcons() {
    return Wrap(
      spacing: 10,
      runSpacing: 10,
      children: _icons.map((item) {
        return _createIcon(item);
      }).toList(),
    );
  }

  Widget _createIcon(ShareIconModel item) {
    return GestureDetector(
      child: Container(
        width: 60,
        child: Column(
          children: <Widget>[
            Container(
              width: 40,
              height: 40,
              child: CachedNetworkImage(
                imageUrl: item.icon,
                fit: BoxFit.contain,
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 2, bottom: 2),
              child: Text(
                item.name,
                style: TextStyle(
                    fontSize: 12,
                    color: Color(0xff333333),
                    fontWeight: FontWeight.bold),
              ),
            ),
          ],
        ),
      ),
      onTap: () async {
        //检查是否有存储权限
        var status = await Permission.storage.status;
        if (!status.isGranted) {
          status = await Permission.storage.request();
          print(status);
          return;
        }

        if (item.type == 'wx') {
          _shareByMob(ShareSDKPlatforms.wechatSession);
        } else if (item.type == 'pyq') {
          _shareByMob(ShareSDKPlatforms.wechatTimeline);
        } else if (item.type == 'qq') {
          _shareByMob(ShareSDKPlatforms.qq);
        } else if (item.type == 'qq_space') {
          _shareByMob(ShareSDKPlatforms.qZone);
        } else if (item.type == 'weibo') {
          _shareByMob(ShareSDKPlatforms.sina);
        } else if (item.type == 'more_setting') {
          _shareBySystem();
        }
      },
    );
  }

  void _shareByMob(ShareSDKPlatform plateform) async {
    // dynamic image;
    if (widget.model.image != null && widget.model.image.length > 1) {
      _shareMultipleImages();
      return;
    }

    //单独公共分享
    SSDKMap params = SSDKMap()
      ..setGeneral(
        widget.model.title,
        widget.model.content,
        widget.model.image,
        null,
        null,
        widget.model.url,
        null,
        null,
        null,
        null,
        SSDKContentTypes.auto,
      );

    SharesdkPlugin.share(plateform, params, (SSDKResponseState state,
        Map userdata, Map contentEntity, SSDKError error) {
      Logger.debug('${state}, ${error.rawData}');
    });
  }

  // 系统分享，只能分享图片或者文字，不能组合分享
  void _shareBySystem() async {
    if (widget.model.image.length >= 1) {
      _shareMultipleImages();
      return;
    } else {
      ShareExtend.share(widget.model.content, 'text');
    }
  }

  // 多图分享，调用系统分享
  void _shareMultipleImages() async {
    List<String> paths = await ImageDownloadUtil.download(widget.model.image);
    ShareExtend.shareMultiple(paths, "image", subject: "");
  }
}
