import 'dart:convert' as convert;
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:save_image/save_image.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/goods_share_editor/goods_share_editor.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/goods_share_image/goods_share_image_model.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/models/goods_share_temp_add_model.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/widgets/good_share_msg.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/widgets/goods_share_edit.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/widgets/goods_share_image.dart';
import 'package:zhiying_base_widget/pages/goods_share_page/widgets/goods_share_item.dart';
import 'package:zhiying_base_widget/utils/image_download_util/image_download_util.dart';
import 'package:zhiying_base_widget/widgets/public/custom_button/custom_bottom.dart';
import 'package:zhiying_base_widget/widgets/public/custom_button/custom_button_model.dart';
import 'package:zhiying_base_widget/widgets/share/models/share_data_model.dart';
import 'package:zhiying_base_widget/widgets/share/share_alert.dart';

class GoodsShareImage extends StatefulWidget {
  final Map<String, dynamic> model;
  final GoodsShareTempDataModel datas;

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

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

class _GoodsShareImageState extends State<GoodsShareImage> {
  GoodsShareImageModel _style;
  Map<int, String> _images = Map();
  List<Widget> widgets = List();
  String _content = '';

  // 分享数据
  final ShareDataModel _shareModel = ShareDataModel();

  @override
  void initState() {
    String data = widget.model['data'];
    var d = convert.jsonDecode(data);
    _style = GoodsShareImageModel.fromJson(Map<String, dynamic>.from(d));
    _content = widget.datas.shareContent;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    widgets.clear();
    widgets.add(GoodsShareItem(
      imgHeader: _style.cssList.headerImage,
      imgCheck: _style.cssList.unChooseImage,
      imgCheckSelected: _style.cssList.chooseImage,
      child: GoodsShareEdit(
        _content,
        imgCheck: _style.cssList.unChooseImage,
        imgCheckSelected: _style.cssList.chooseImage,
        onCopyClick: () {
          Clipboard.setData(ClipboardData(text: _content));
          Fluttertoast.showToast(msg: '文案已复制');
        },
        onEditorClick: () {
          Fluttertoast.showToast(msg: '正在开发中');
          return;
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => GoodsShareEditor()));
        },
      ),
      onSelected: (isSelected) {
        _shareModel.content = isSelected ? _content : '';
      },
    ));
    for (String message in _style.customContent) {
      widgets.add(
        GoodsShareItem(
          imgHeader: _style.cssList.headerImage,
          imgCheck: _style.cssList.unChooseImage,
          imgCheckSelected: _style.cssList.chooseImage,
          enabled: false,
          child: GoodsShareMessage(message),
        ),
      );
    }
    for (int index = 0; index < _style.customImage.length; index++) {
      String image = _style.customImage[index];
      // 分享图片
      widgets.add(
        GoodsShareItem(
          imgHeader: _style.cssList.headerImage,
          imgCheck: _style.cssList.unChooseImage,
          imgCheckSelected: _style.cssList.chooseImage,
          enabled: true,
          child: GoodsShareImageWidget(image),
          onSelected: (isSelected) {
            if (_images.containsKey(index)) {
              _images.remove(index);
            } else {
              _images[index] = image;
            }
          },
        ),
      );
    }

    return Column(
      children: <Widget>[
        Expanded(
          child: Container(
            margin: EdgeInsets.only(bottom: 4),
            padding: EdgeInsets.only(top: 10),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(8),
                    bottomRight: Radius.circular(8))),
            child: SingleChildScrollView(
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: widgets),
            ),
          ),
        ),
        _createBottom(),
      ],
    );
  }

  Widget _createBottom() {
    Map<String, dynamic> shareImages = _style.cssList.shareImage;
    if (shareImages == null) {
      return Container();
    }
    CustomButtonModel btnCopy = CustomButtonModel.fromJson(
        Map<String, dynamic>.from(shareImages['copy_btn']));
    CustomButtonModel btnSave = CustomButtonModel.fromJson(
        Map<String, dynamic>.from(shareImages['save_btn']));
    CustomButtonModel btnShare = CustomButtonModel.fromJson(
        Map<String, dynamic>.from(shareImages['share_btn']));
    return SafeArea(
      child: Container(
        margin: EdgeInsets.only(left: 12.5, right: 12.5, top: 4, bottom: 4),
        child: Row(
          children: <Widget>[
            btnCopy == null
                ? Container()
                : GestureDetector(
                    child: Container(
                        width: 95,
                        height: 36,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(18),
                        ),
                        child: CustomButton(btnCopy)),
                    onTap: () {
                      Clipboard.setData(ClipboardData(text: _content));
                      Fluttertoast.showToast(msg: '文案已复制');
                    },
                  ),
            btnSave == null
                ? Container()
                : GestureDetector(
                    child: Container(
                      margin: EdgeInsets.only(left: 5),
                      width: 95,
                      height: 36,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(18),
                      ),
                      child: CustomButton(btnSave),
                    ),
                    onTap: () {
                      _saveImages();
                    },
                  ),
            btnShare == null
                ? Container()
                : Expanded(
                    child: GestureDetector(
                      child: Container(
                          margin: EdgeInsets.only(left: 5),
                          // width: 95,
                          height: 36,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(18),
                          ),
                          child: CustomButton(btnShare)),
                      onTap: () {
                        _showShareAlert();
                      },
                    ),
                  ),
          ],
        ),
      ),
    );
  }

  void _saveImages() async {
    List<String> images = List();
    for (int index = 0; index < _style.customImage.length; index++) {
      if (_images.containsKey(index)) {
        images.add(_images[index]);
      }
    }
    if (images.length > 0) {
      _shareModel.image = images;
    } else {
      _shareModel.image = null;
    }

    if ((_shareModel.image == null || _shareModel.image.length == 0)) {
      Fluttertoast.showToast(msg: '请选择要保存的图片');
      return;
    }

    List<String> paths = await ImageDownloadUtil.download(images);
    paths.forEach((path) async {
      Uint8List data = File(path).readAsBytesSync();
      bool isSaveSuccess = await SaveImage.save(imageBytes: data);
      if (!isSaveSuccess) {
        Fluttertoast.showToast(msg: '保存失败');
        return;
      }
    });
    Fluttertoast.showToast(msg: '保存成功');
  }

  // 弹出分享框
  void _showShareAlert() async {
    List<String> images = List();
    for (int index = 0; index < _style.customImage.length; index++) {
      if (_images.containsKey(index)) {
        images.add(_images[index]);
      }
    }
    if (images.length > 0) {
      _shareModel.image = images;
    } else {
      _shareModel.image = null;
    }

    if ((_shareModel.title == null || _shareModel.title == '') &&
        (_shareModel.image == null || _shareModel.image.length == 0) &&
        (_shareModel.content == null || _shareModel.content == '') &&
        (_shareModel.url == null || _shareModel.url == '')) {
      Fluttertoast.showToast(msg: '请选择要分享的内容');
      return;
    }

    showCupertinoModalPopup(
      context: context,
      builder: (context) => ShareAlert(
        _shareModel,
        'pub.flutter.share_icon',
        // child: GoodsShareAlertContent(),
      ),
    );
  }
}
