import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:provider/provider.dart';
import 'package:sport/bean/forum.dart';
import 'package:sport/bean/post.dart';
import 'package:sport/bean/post_user.dart';
import 'package:sport/bean/user_friend.dart';
import 'package:sport/bean/user_info.dart';
import 'package:sport/pages/social/block_user_list_page.dart';
import 'package:sport/pages/social/chat_page.dart';
import 'package:sport/pages/social/post_widget.dart';
import 'package:sport/pages/social/private_message_page.dart';
import 'package:sport/provider/lib/provider_widget.dart';
import 'package:sport/provider/lib/view_state_lifecycle.dart';
import 'package:sport/provider/user_detail_model.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/userid.dart';
import 'package:sport/utils/toast.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/button_primary.dart';
import 'package:sport/widgets/dialog/request_dialog.dart';
import 'package:sport/widgets/error.dart';
import 'package:sport/widgets/image.dart';
import 'package:sport/widgets/loading.dart';
import 'package:sport/widgets/misc.dart';
import 'package:sport/widgets/persistent_header.dart';
import 'package:sport/widgets/popmenu_bg.dart';
import 'package:sport/widgets/space.dart';

class UserDetailPage extends StatefulWidget {
  final PostUser user;
  final List<UserFriend> userFriends;

  UserDetailPage(this.user, {this.userFriends});

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

class _PageState extends ViewStateLifecycle<UserDetailPage, UserDetailModel> with InjectApi, UserId {
  ScrollController _controller;
  double _expandedHeight = 0;
  int _brightness = 0;
  String _name = "";
  String _genderLabel = "他";
  static const List<String> _sort = ["时间倒序", "点赞最多", "评论最多"];
  String _sortType = _sort[0];
  ValueNotifier<UserInfo> _valueNotifierUserInfo;
  ValueNotifier<List<Forum>> _valueNotifierForums;

  @override
  void initState() {
    super.initState();
    _valueNotifierUserInfo = ValueNotifier(UserInfo.fromJson(widget.user.toJson()));
    _valueNotifierForums = ValueNotifier([]);
    _controller = ScrollController()
      ..addListener(() {
        if (_controller.position.pixels >= _expandedHeight - 70) {
          if (_brightness == 0) {
            setState(() {
              _brightness = 1;
            });
          }
        } else {
          if (_brightness == 1) {
            setState(() {
              _brightness = 0;
            });
          }
        }
      });
    _genderLabel = selfId == widget.user.id ? "我" : "她";
    api.getUserInfo(widget.user.id).then((value) {
      _valueNotifierUserInfo.value = value.data;
      _name = value.data.name;
      _genderLabel = selfId == widget.user.id ? "我" : value.data.gender == 1 ? "他" : "她";
    });
    api.getForumIndex().then((value) {
      _valueNotifierForums.value = [Forum(name: "全部")]..addAll(value.results ?? []);
    });
  }

  bool isSelf() {
    return selfId == widget.user.id;
  }

  @override
  void dispose() {
    super.dispose();
    _controller?.dispose();
    _valueNotifierUserInfo?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _expandedHeight = MediaQuery.of(context).size.width * (isSelf() ? 455.0 : 604.0) / 750.0 - MediaQuery.of(context).padding.top;
//    print(MediaQuery.of(context));
    return Scaffold(
      backgroundColor: Colors.white,
      body: ProviderWidget<UserDetailModel>(
          model: model,
          onModelReady: (model) => model.initData(),
          builder: (_, model, __) {
            return EasyRefresh.builder(
                controller: model.refreshController,
                enableControlFinishRefresh: true,
                enableControlFinishLoad: true,
                onRefresh: () => model.refresh(),
                onLoad: model.isIdle ? () => model.loadMore() : null,
                header: buildClassicalHeader(),
                footer: buildClassicalFooter(),
                builder: (context, physics, header, footer) {
                  return CustomScrollView(
                    controller: _controller,
                    physics: physics,
                    slivers: <Widget>[
                      SliverAppBar(
                        expandedHeight: _expandedHeight,
                        pinned: true,
                        elevation: 0,
                        forceElevated: true,
                        iconTheme: IconThemeData(color: _brightness == 0 ? Colors.white : Colors.black),
                        brightness: _brightness == 0 ? Brightness.dark : Brightness.light,
                        backgroundColor: _brightness == 0 ? Colors.transparent : Colors.white,
                        leading: IconButton(
                          icon: Image.asset("lib/assets/img/topbar_return${_brightness == 0 ? "_white" : ""}.png"),
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                        ),
                        title: _brightness == 0
                            ? Text("")
                            : Text(
                                "$_name",
                                style: titleStyle,
                              ),
                        actions: <Widget>[
                          PopupMenuTheme(
                              data: PopupMenuThemeData(shape: PopmenuShape(borderRadius: BorderRadius.all(Radius.circular(10.0)))),
                              child: PopupMenuButton(
                                icon: _brightness == 0 ? iconMore() : iconMoreGray(),
                                onSelected: (val) async {
                                  switch (val) {
                                    case 'block':
                                      await request(context, () async {
                                        var resp = await model.api.postForumBlockUser("${_valueNotifierUserInfo.value?.id}");
                                        if (resp?.code == 0) {
                                          ToastUtil.show("屏蔽成功");
                                        }
                                      });
                                      break;
                                    case 'list':
                                      NavigatorUtil.goPage(context, (context) => BlockUserListPage());
                                      break;
                                  }
                                },
                                offset: Offset(0, kToolbarHeight / 2 + 15),
                                itemBuilder: (_) => [
                                  if (isSelf()) menuItemCenter('list', '屏蔽列表'),
                                  if (!isSelf()) menuItemCenter('block', '屏蔽此人'),
                                ],
                              ))
                        ],
                        flexibleSpace: FlexibleSpaceBar(
                          collapseMode: CollapseMode.pin,
                          stretchModes: [],
                          background: Stack(
                            alignment: AlignmentDirectional.bottomCenter,
                            children: <Widget>[
                              Image.asset(
                                "lib/assets/img/bg_userprofile_bbs.png",
                                fit: BoxFit.cover,
                                width: MediaQuery.of(context).size.width,
                              ),
                              Positioned(
                                left: 0,
                                right: 0,
                                bottom: -1,
                                child: Container(
                                  height: 10,
                                  decoration: BoxDecoration(borderRadius: BorderRadius.vertical(top: Radius.circular(10)), color: Colors.white),
                                ),
                              ),
                              ValueListenableBuilder(
                                valueListenable: _valueNotifierUserInfo,
                                builder: (BuildContext context, UserInfo user, Widget child) {
                                  if (user == null) {
                                    return Container();
                                  }
                                  return Container(
                                    child: Column(
                                      mainAxisSize: MainAxisSize.min,
                                      children: <Widget>[
                                        CircleAvatar(
                                          backgroundImage: userAvatarProvider(user.avatar),
                                          radius: 40,
                                        ),
                                        Space(
                                          height: 12,
                                        ),
                                        Text(user.name, style: TextStyle(color: Colors.white, fontSize: 18)),
                                        Space(
                                          height: 6,
                                        ),
                                        Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: <Widget>[
                                            Image.asset("lib/assets/img/mine_icon_${user.gender == 1 ? "manl" : "girl"}_white.png"),
                                            Space(
                                              width: 4,
                                            ),
                                            Text(
                                              user.gender == 1 ? "男" : "女",
                                              style: TextStyle(color: Colors.white, fontSize: 12),
                                            ),
                                            Space(
                                              width: 10,
                                            ),
                                            Text(
                                              user.age != null ? "${user.age}岁" : "",
                                              style: TextStyle(color: Colors.white, fontSize: 12),
                                            ),
                                            if ((user.districtId ?? 0) != 0)
                                              Padding(
                                                padding: const EdgeInsets.only(left: 10.0),
                                                child: Text(
                                                  "${user.province}${user.province == user.city ? '' : user.city}",
                                                  style: TextStyle(color: Colors.white, fontSize: 12),
                                                ),
                                              )
                                          ],
                                        ),
                                        if (selfId != widget.user.id)
                                          Padding(
                                            padding: const EdgeInsets.only(top: 20.0),
                                            child: selfId == '${user.id}'
                                                ? Container(height: 35)
                                                : Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
                                                    PrimaryButton(
                                                      width: 120,
                                                      height: 35,
                                                      callback: () {
                                                        // 先尝试换一下
                                                        NavigatorUtil.goPage(context, (context) => ChatPage(user.name,user.id));
                                                        // NavigatorUtil.goPage(context, (context) => PrivateMessagePage(user));
                                                      },
                                                      content: '',
                                                      shadow: false,
                                                      child: Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
                                                        Image.asset("lib/assets/img/mine_icon_message.png"),
                                                        Space(
                                                          width: 6,
                                                        ),
                                                        Text(
                                                          "私信",
                                                          strutStyle: fixedLine,
                                                          style: Theme.of(context).textTheme.subtitle1.copyWith(color: Colors.white),
                                                        )
                                                      ]),
                                                    ),
                                                    Space(
                                                      width: 12,
                                                    ),
                                                    user.isFriend()
                                                        ? GestureDetector(
                                                            child: Container(
                                                              width: 120,
                                                              height: 35,
                                                              alignment: Alignment.center,
                                                              child: Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
                                                                Image.asset("lib/assets/img/mine_icon_followed.png"),
                                                                Space(
                                                                  width: 6,
                                                                ),
                                                                Text(
                                                                  "已关注",
                                                                  strutStyle: fixedLine,
                                                                  style: Theme.of(context).textTheme.subtitle1.copyWith(color: Theme.of(context).accentColor),
                                                                )
                                                              ]),
                                                              decoration: BoxDecoration(
                                                                borderRadius: BorderRadius.circular(20),
                                                                border: Border.all(
                                                                  color: Theme.of(context).accentColor,
                                                                  width: .5,
                                                                ),
                                                              ),
                                                            ),
                                                            onTap: () async {
                                                              await request(context, () async {
                                                                var resp = await model.api.userUnFollow(uid: user.id).catchError((onError) {});
                                                                if (resp?.code == 0) {
                                                                  user.followStatus = "none";
                                                                  widget.userFriends?.firstWhere((element) => element.uid == user.id)?.isFriends = "0";
                                                                  setState(() {});
                                                                  ToastUtil.show("取关成功");
                                                                }
                                                              });
                                                            },
                                                          )
                                                        : PrimaryButton(
                                                            width: 120,
                                                            height: 35,
                                                            callback: () async {
                                                              await request(context, () async {
                                                                var resp = await model.api.userFollow(uid: user.id).catchError((onError) {});
                                                                if (resp?.code == 0) {
                                                                  user.followStatus = "followed";
                                                                  var db = widget.userFriends?.firstWhere((element) => element.uid == user.id);
                                                                  if (db != null) {
                                                                    db.isFriends = "1";
                                                                    db.isIgnore = 0;
                                                                  }
                                                                  setState(() {});
                                                                  ToastUtil.show("关注成功");
                                                                }
                                                              });
                                                            },
                                                            content: '',
                                                            shadow: false,
                                                            child: Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
                                                              Image.asset("lib/assets/img/mine_icon_follow.png"),
                                                              Space(
                                                                width: 6,
                                                              ),
                                                              Text(
                                                                "关注",
                                                                strutStyle: fixedLine,
                                                                style: Theme.of(context).textTheme.subtitle1.copyWith(color: Colors.white),
                                                              )
                                                            ]),
                                                          ),
                                                  ]),
                                          ),
                                        Space(
                                          height: 32,
                                        ),
                                      ],
                                    ),
                                  );
                                },
                              )
                            ],
                          ),
                        ),
                      ),
                      header,
                      SliverToBoxAdapter(
                        child: Container(
                          color: Colors.white,
                          child: ValueListenableBuilder<UserInfo>(
                              valueListenable: _valueNotifierUserInfo,
                              builder: (_, data, ___) => (data == null || data.achievements == null || data.achievements.isEmpty)
                                  ? Container()
                                  : Column(
                                      children: <Widget>[
                                        Padding(
                                          padding: const EdgeInsets.all(12.0),
                                          child: Stack(
                                            alignment: Alignment.center,
                                            children: <Widget>[
                                              Image.asset(
                                                "lib/assets/img/mine_image_achievement.png",
                                                fit: BoxFit.fitWidth,
                                                width: 240,
                                              ),
                                              Text(
                                                "${widget.user.id == Provider.of<UserModel>(context).user.id.toString() ? '我' : '$_genderLabel'}的成就",
                                                style: Theme.of(context).textTheme.subtitle1,
                                              )
                                            ],
                                          ),
                                        ),
                                        Padding(
                                          padding: const EdgeInsets.all(12.0),
                                          child: achievementGroupWidget(data?.achievements),
                                        ),
                                        Divider()
                                      ],
                                    )),
                        ),
                      ),
                      SliverPersistentHeader(
                        delegate: PersistentHeader(
                            min: 50,
                            max: 50,
                            child: Container(
                              color: Colors.white,
                              padding: EdgeInsets.only(bottom: 5),
                              child: Row(
                                children: <Widget>[
                                  Expanded(
                                    child: Padding(
                                      padding: const EdgeInsets.all(12.0),
                                      child: Text(
                                        "$_genderLabel的帖子",
                                        style: Theme.of(context).textTheme.headline3,
                                      ),
                                    ),
                                  ),
                                  ValueListenableBuilder<List<Forum>>(
                                    builder: (_, snapshot, __) {
                                      var list = snapshot;
                                      if (list.isEmpty) return Container();
                                      return PopupMenuButton(
                                        onSelected: (v) {
                                          setState(() {
                                            model.forumBy(v);
                                          });
                                        },
                                        itemBuilder: (BuildContext context) {
                                          return divideMenus(
                                              list.map((e) => menuItemSelected(e, e.name, model.forum == e || model.forum == null && e.name == "全部")).toList());
                                        },
                                        child: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: <Widget>[
                                            Text(
                                              model.forum?.name ?? "全部",
                                              style: Theme.of(context).textTheme.bodyText1,
                                            ),
                                            Padding(
                                              padding: const EdgeInsets.fromLTRB(6, 6, 12.0, 6),
                                              child: arrowBottom(),
                                            )
                                          ],
                                        ),
                                      );
                                    },
                                    valueListenable: _valueNotifierForums,
                                  ),
                                  Space(
                                    width: 12,
                                  ),
                                  PopupMenuButton(
                                    onSelected: (v) {
                                      setState(() {
                                        _sortType = v;
                                        model.sortBy(_sortType);
                                      });
                                    },
                                    itemBuilder: (BuildContext context) {
                                      return divideMenus(_sort.map((e) => menuItemSelected(e, e, _sortType == e)).toList());
                                    },
                                    child: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: <Widget>[
                                        Text(
                                          _sortType,
                                          style: Theme.of(context).textTheme.bodyText1,
                                        ),
                                        Padding(
                                          padding: const EdgeInsets.fromLTRB(6, 6, 12.0, 6),
                                          child: arrowBottom(),
                                        )
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            )),
                        pinned: true,
                      ),
                      if (model.isBusy) SliverToBoxAdapter(child: RequestLoadingWidget()),
                      if (model.isEmpty)
                        SliverFillRemaining(child: Center(child: RequestErrorWidget(null, msg: "暂无帖子~", assets: RequestErrorWidget.ASSETS_NO_INVITATION))),
                      if (model.isIdle)
                        SliverList(
                          delegate: SliverChildBuilderDelegate(
                            (context, index) {
                              Post post = model.list[index];
                              return PostWidget(
                                post,
                                model,
                                selfId == post.userId,
                                jump: false,
                                showForum: true,
                                showTopButton: true,
                                callback: () {
                                  model?.initData();
                                },
                              );
                            },
                            childCount: model.list.length,
                          ),
                        ),
                    ],
                  );
                });
          }),
    );
  }

  @override
  createModel() => UserDetailModel(widget.user.id.toString());
}
