import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sport/bean/forum.dart';
import 'package:sport/bean/post.dart';
import 'package:sport/bean/user_friend.dart';
import 'package:sport/pages/social/chat_page.dart';
import 'package:sport/pages/social/post_page.dart';
import 'package:sport/provider/user_model.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/services/api/inject_api.dart';
import 'package:sport/services/api/resp.dart';
import 'package:sport/utils/toast.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/dialog/alert_dialog.dart';
import 'package:sport/widgets/image.dart';
import 'package:sport/widgets/loading.dart';
import 'package:sport/widgets/space.dart';

// 简单判断吧 post 就是转发 帖子类型     link 就是 链接类型 ...
class PostSharePage extends StatefulWidget {
  final Post post;
  // link 需要hash 和 url 要分开操作的是...
  final String url;
  final String hash;
  // Img
  final String image;
  const PostSharePage({this.post, this.url, this.hash, this.image});

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

class _PageState extends State<PostSharePage> with InjectApi {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        leading: buildBackButton(context),
        title: Text(
          "选择分享到的吧",
          style: titleStyle,
        ),
        centerTitle: false,
        titleSpacing: 0,
      ),
      body: FutureBuilder<RespList<Forum>>(
        future: api.getForumIndex(),
        builder: (_, snapshot) {
          if (snapshot.connectionState != ConnectionState.done)
            return RequestLoadingWidget();
          var list = snapshot.data?.results ?? [];
          return ListView.separated(
            itemBuilder: (BuildContext context, int index) => ListTile(
              leading: CircleAvatar(
                  backgroundImage:
                      CachedNetworkImageProvider(list[index].cover),
                  radius: 22.0),
              title: Text(
                "${list[index].name}",
                style: Theme.of(context)
                    .textTheme
                    .subtitle1
                    .copyWith(fontSize: 16),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
              onTap: () async {
                bool result = await NavigatorUtil.goPage(
                    context,
                    (context) => PostPage(
                          list[index].forumId,
                          post: widget.post,
                          forum: list[index],
                          url: widget.url,
                          hash: widget.hash,
                          image: widget.image,
                        ));
                if (result == true) {
                  Navigator.of(context).pop(true);
                }
              },
              trailing: arrowRight(),
            ),
            itemCount: list.length,
            separatorBuilder: (BuildContext context, int index) => Divider(),
          );
        },
      ),
    );
  }
}

class PostShareFriendsPage extends StatefulWidget {
  final Post post; // 应该是二选一...
  final String hash; // 二选一 ...
  final String image;
  const PostShareFriendsPage({this.post, this.hash, this.image});

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

class _PostShareFriendsPageState extends State<PostShareFriendsPage>
    with InjectApi {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        leading: buildBackButton(context),
        title: Text(
          "选择分享到的朋友",
          style: titleStyle,
        ),
        centerTitle: false,
        titleSpacing: 0,
      ),
      body: FutureBuilder<RespListTest<UserFriend>>(
        future: api.userFriendsTest(),
        builder: (_, snapshot) {
          if (snapshot.connectionState != ConnectionState.done)
            return RequestLoadingWidget();
          var list = snapshot.data?.results?.list ?? [];
          return ListView.separated(
            itemBuilder: (BuildContext context, int index) => ListTile(
              leading: CircleAvatar(
                  backgroundImage:
                      CachedNetworkImageProvider(list[index].socialInfo.avatar),
                  radius: 22.0),
              title: Text(
                "${list[index].socialInfo.name}",
                style: Theme.of(context)
                    .textTheme
                    .subtitle1
                    .copyWith(fontSize: 16),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
              onTap: () async {
                await showDialog(
                    context: context,
                    builder: (context) => CustomAlertDialog(
                        child: Column(
                          children: <Widget>[
                            Space(
                              height: 37.0,
                            ),
                            CircleAvatar(
                                backgroundImage: CachedNetworkImageProvider(
                                  list[index].socialInfo?.avatar,
                                ),
                                radius: 35),
                            Space(
                              height: 8.0,
                            ),
                            Center(
                              child: Text(
                                "${list[index].socialInfo?.name}",
                                style: Theme.of(context).textTheme.headline3,
                              ),
                            ),
                            Space(
                              height: 8.0,
                            ),
                            _buildPostWidget(
                                context, widget.post, widget.hash, widget.image)
                          ],
                        ),
                        textOk: "分享",
                        ok: () async {
                          bool result = await NavigatorUtil.goPage(
                              context,
                              (context) => ChatPage(list[index].socialInfo,
                                  post: widget.post,
                                  hash: widget.hash,
                                  image: widget.image));
                          if (result == true) {
                            Navigator.of(context).pop(true);
                            Navigator.of(context).pop(true);
                          }
                        }));
              },
              trailing: arrowRight(),
            ),
            itemCount: list.length,
            separatorBuilder: (BuildContext context, int index) => Divider(),
          );
        },
      ),
    );
  }
}

Widget _buildPostWidget(
    BuildContext context, Post post, String hash, String image) {
  Widget imageWidget(String image) {
    return ClipRRect(
        child: CachedNetworkImage(
          imageUrl: image,
          fit: BoxFit.cover,
          width: 50,
          height: 50,
        ),
        // 也可控件一边圆角大小
        borderRadius: new BorderRadius.all(Radius.circular(6.0)));
  }

  Widget contentWidget(String content) {
    return Expanded(
      child: Container(
        margin: const EdgeInsets.all(5.0),
        child: Text(content,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: Theme.of(context).textTheme.subtitle1),
      ),
    );
  }

  Widget contentMoreWidget() {
    return Expanded(
      child: Container(
        margin: const EdgeInsets.all(5.0),
        child: RichText(
          text: TextSpan(children: [
            TextSpan(
                text: Provider.of<UserModel>(context, listen: false).user.name,
                style: Theme.of(context)
                    .textTheme
                    .headline6
                    .copyWith(color: Color(0xffffc400))),
            TextSpan(
                text: "分享了他的运动记录，快来围观吧~",
                style: Theme.of(context).textTheme.subtitle1)
          ]),
        ),
      ),
    );
  }

  Widget sharePostWidget() {
    print("$image----------------------------");
    if (post != null) {
      return Row(
        children: <Widget>[
          if (post?.images != null && post.images.isNotEmpty)
            imageWidget(post?.images[0].src),
          contentWidget(post.content),
        ],
      );
    } else if (hash != null) {
      return Row(
        children: <Widget>[
          imageWidget(avatarList[4]),
          contentMoreWidget(),
        ],
      );
    } else if (image != null) {
      return Container(
        decoration: BoxDecoration(
            image: DecorationImage(
          image: FileImage(File(image)),
          fit: BoxFit.cover,
        )),
        constraints: BoxConstraints(maxHeight: 300, maxWidth: 200),
        child: CachedNetworkImage(
          imageUrl:image,
        ),
      );
    } else {
      return Container();
    }
  }

//  file unload asset

  return Container(
      margin: const EdgeInsets.symmetric(horizontal: 8.0),
      padding: const EdgeInsets.symmetric(vertical: 7.0, horizontal: 8.0),
      decoration: new BoxDecoration(
        color: Color(0xfff1f1f1), // 底色
        borderRadius: new BorderRadius.all(Radius.circular(10.0)),
      ),
      child: sharePostWidget());
}
