import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:more_picture_share/more_picture_share.dart';
import 'package:path_provider/path_provider.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/dialog/global_dialog/intellect_search_goods_dialog/intellect_create.dart';
import 'package:zhiying_base_widget/dialog/loading/loading.dart';
import 'package:zhiying_base_widget/utils/image_download_util/image_download_util.dart';
import 'package:zhiying_base_widget/widgets/share/models/share_alert_model.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_base_widget/widgets/share/share_alert_content.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'dart:io';

class ShareAlert extends StatefulWidget {
  final String skipIdentifier;
  final bool isContentShow;
  final ShareDataModel model;

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

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

class _ShareAlertState extends State<ShareAlert> {
  ShareAlertModel _iconModel;

  @override
  void initState() {
    Logger.log('设置分享页面不弹');
    /// 设置分享页面不弹
    IntellectCreate.setCheck(false);
    NetUtil.request('/api/v1/mod/${widget.skipIdentifier}', method: NetMethod.GET, onCache: (data) {
      // try{
      //   _parseData(data);
      // }catch(e){
      //   print(e);
      // }
    }, onSuccess: (data) {
      print(data);
      _parseData(data);
    }, onError: (err) {});

    super.initState();
  }

  @override
  void dispose() {
    Logger.log('设置智能弹窗可以弹');
    /// 之后可以弹
    IntellectCreate.setCheck(true);
    super.dispose();
  }

  void _parseData(Map<String, dynamic> data) {
    List modList = data['mod_list'];
    Map d = modList.first;
    if (d != null) {
      String dString = d['data'];
      _iconModel = ShareAlertModel.fromJson(Map<String, dynamic>.from(jsonDecode(dString)));

      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Loading.dismiss();
        Navigator.canPop(context);
        return true;
      },
      child: 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: widget.isContentShow ? ShareAlertContent(_iconModel) : Container()),
                  ),
                  _ShareAlertContent(widget.model, widget.skipIdentifier, _iconModel),
                ],
              ),
            ), // 模糊化
          ),
        ),
        onTap: () {
          Navigator.of(context).pop();
        },
      ),
    );
  }
}

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

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

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

class _ShareAlertContentState extends State<_ShareAlertContent> {
  @override
  void initState() {
    Future.delayed(Duration(milliseconds: 100), () async {
      var status = await Permission.storage.status;
      if (status != PermissionStatus.granted) {
        status = await Permission.storage.request();
      }
    });
    super.initState();
  }

  @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: widget.iconModel?.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;
        }
        int count = 0;
        if (widget.model.poster != null) {
          count++;
        }
        count += (widget.model?.image?.length ?? 0);
        // 多图分享
        if (count > 1) {
          _shareMultipleImages(item.type);
          return;
        }

        if (widget?.model?.poster != null) {
          Loading.show(context);
          File file = await EncodeUtil.compressImage(context, images: widget?.model?.poster, size: 600);
          widget?.model?.poster = await file.readAsBytes();
          Loading.dismiss();
        }

        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(item.type);
        }
      },
    );
  }

  // mob分享,只能单图分享,多图分享调用系统分享
  void _shareByMob(ShareSDKPlatform plateform) async {
    Loading.show(context);
    Timer(Duration(milliseconds: 2000), () {
      Loading.dismiss();
    });

    SSDKMap params;
    if (widget.model.poster != null) {
      String path = await _savePoster();
      if (path != null && path != '') {
        params = SSDKMap()
          ..setGeneral(
            widget.model?.title ?? '',
            widget.model?.content ?? '',
            Platform.isIOS ? path : null,
            null,
            Platform.isAndroid ? path : null,
            null,
            null,
            null,
            null,
            null,
            SSDKContentTypes.image,
          );
      }
    } else {
      var type = SSDKContentTypes.auto;

      if ((widget?.model?.image?.length ?? 0) != 0 && widget.model?.url != null) {
        type = SSDKContentTypes.webpage;
      } else if ((widget?.model?.image?.length ?? 0) != 0) {
        type = SSDKContentTypes.image;
      } else if (widget?.model?.title != null || widget.model?.content != null) {
        type = SSDKContentTypes.text;
      }
      if (plateform == ShareSDKPlatforms.qZone && widget?.model?.content != null) {
        widget?.model?.title = null;
        widget?.model?.image=[];
        widget?.model?.url=null;
        type = SSDKContentTypes.message;
      }

      var isExistImage = false;

      if (widget?.model?.image != null && widget?.model?.image?.length > 0) {
        isExistImage = true;
      }

      if (plateform == ShareSDKPlatforms.qq && widget?.model?.url != null) {
        SSDKMap params = SSDKMap()
          ..setQQ(
            widget?.model?.content ?? "",
            widget?.model?.title ?? "",
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            (isExistImage ? widget?.model?.image?.first : null),
            null,
            widget?.model?.content ?? "",
            null,
            null,
            SSDKContentTypes.image,
            ShareSDKPlatforms.qq,
          );
        SharesdkPlugin.share(ShareSDKPlatforms.qq, params, (SSDKResponseState state, Map userdata, Map contentEntity, SSDKError error) {});
        return;
      }

      params = SSDKMap()
        ..setGeneral(
          widget.model?.title ?? '',
          widget?.model?.content ?? '',
          Platform.isIOS ? widget.model.image : null,
          Platform.isAndroid ? (isExistImage ? widget?.model?.image?.first : null) : null,
          null,
          widget.model.url,
          null,
          null,
          null,
          null,
          type,
        );
    }
    SharesdkPlugin.share(plateform, params, (SSDKResponseState state, Map userdata, Map contentEntity, SSDKError error) {
      print(error);
      if (state == SSDKResponseState.Fail) {
        Fluttertoast.showToast(msg: '分享失败');
      } else if (state == SSDKResponseState.Success) {
        //Fluttertoast.showToast(msg: '分享成功');
      } else if (state == SSDKResponseState.Cancel) {
        Fluttertoast.showToast(msg: '取消分享');
      }
      Logger.debug('${state}, ${error.rawData}');
      Loading.dismiss();
    });
  }

  // 系统分享,只能分享图片或者文字,不能组合分享
  void _shareBySystem(String type) async {
    int count = 0;
    if (widget.model.poster != null) {
      count++;
    }
    count += (widget.model?.image?.length ?? 0);
    // 多图分享
    if (count > 1) {
      _shareMultipleImages(type);
      return;
    }

    if (widget.model.poster != null) {
      String path = await _savePoster();
      if (path != null && path != '') {
        ShareExtend.share(path, 'image');
      }
    } else {
      ShareExtend.share(widget.model.content, 'text');
    }
  }

  Future<String> _savePoster() async {
    String path;
    if (widget.model.poster != null) {
      // 检查并请求权限
      var status = await Permission.storage.status;
      if (status != PermissionStatus.granted) {
        status = await Permission.storage.request();
      }
      if (status != PermissionStatus.granted) {
        Fluttertoast.showToast(msg: '暂无权限,分享失败');
        return null;
      }

      try {
        // 保存到本地路径
        // final tempDir = await getTemporaryDirectory();
        final tempDir = await getApplicationSupportDirectory();
        final file = await File('${tempDir.path}/image.png').create();
        file.writeAsBytesSync(widget.model.poster);

        path = file.path;
        Logger.debug(file.path);
      } catch (err, s) {
        Logger.error(err.toString(), s.toString());
        Fluttertoast.showToast(msg: '分享失败');
        return null;
      }
    }
    return path;
  }

  // 多图分享,调用系统分享
  void _shareMultipleImages(String type) async {
    List<String> paths = List();
    String path = await _savePoster();
    if (path != null && path != '') {
      paths.add(path);
    }
    Loading.show(context);
    List<String> downPaths = await ImageDownloadUtil.download(widget.model.image);
    paths.addAll(downPaths);
    if (Platform.isAndroid && type == 'wx') {
      MorePictureShare.shareWeixinPics(paths);
    } else if (Platform.isAndroid && type == 'pyq') {
      MorePictureShare.shareWeixinPicsCirlc(paths);
    } else {
      ShareExtend.shareMultiple(paths, "image", subject: "");
    }
    Loading.dismiss();
  }
}