import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:sport/bean/rank_game_info.dart';
import 'package:sport/bean/user.dart';
import 'package:sport/pages/my/shop_detail.dart';
import 'package:sport/provider/user_model.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/router/routes.dart';
import 'package:sport/services/api/inject_api.dart';
import 'package:sport/services/userid.dart';
import 'package:sport/widgets/area.dart';
import 'package:sport/widgets/decoration.dart';
import 'package:sport/widgets/image.dart';
import 'package:sport/widgets/loading.dart';
import 'package:sport/widgets/space.dart';
import 'package:sport/widgets/persistent_header.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
import 'package:shared_preferences/shared_preferences.dart';

class RankDetailPage extends StatefulWidget {
  final String id;
  final String type;

  RankDetailPage(this.id, this.type);

  @override
  State<StatefulWidget> createState() {
    return _RankDetailPageState();
  }
}

class _RankDetailPageState extends State<RankDetailPage>
    with TickerProviderStateMixin, InjectApi, UserId {
  bool _isLoading;
  RankGameInfoData _data;
  String _id;
  ScrollController _controller = new ScrollController();
  final ItemScrollController itemScrollController = ItemScrollController();
  final ItemPositionsListener itemPositionsListener =
      ItemPositionsListener.create();
  TabController _tabController;
  final List<String> _tabs = [
    '世界榜',
    '好友榜',
  ];
  String _rank;
  final List<String> rankImages = [
    "",
    "rank_icon_first.png",
    "rank_icon_second.png",
    "rank_icon_third.png",
  ];

  @override
  void initState() {
    super.initState();
    // 简单的缓存...
    if (_data == null || _id != widget.id) {
      _isLoading = true;
      initData();
      _id = widget.id;
    } else {
      _isLoading = false;
    }
    _tabController =
        TabController(length: _tabs.length, initialIndex: 0, vsync: this)
          ..addListener(() async {
            SharedPreferences prefs = await SharedPreferences.getInstance();
            String _scope = _tabController.index == 0 ? "world" : "friend";
            if (widget.type == "1") {
              _data = (await api.getRankGameInfo(widget.id, scope: _scope)).data;
            }else{
              _data = (await api.getRankSportInfo(widget.id,scope: _scope)).data;
            }
            if (_data.user != null && _data.user.position > 10) {
              _data.records.add(_data.user);
            } else if (_data.user == null) {
              _data.records.add(new User(
                userName: prefs.getString("name"),
                userAvatar: prefs.getString("avatar"),
              ));
            }
            // 忘了空set 一手...
            setState(() {});
          });
  }

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

  // 缓存数据...
  initData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (widget.type == "1") {
      api.getRankGameInfo(widget.id).then((data) {
        setState(() {
          _data = data.data;
          print("${data.data.user}====================");
          if (data.data.user != null && data.data.user.position > 10) {
            _data.records.add(data.data.user);
          } else if (data.data.user == null) {
            _data.records.add(new User(
                userName: prefs.getString("name"),
                userAvatar: prefs.getString("avatar"),
                userId: int.parse(selfId),
            ));
          }
          _isLoading = false;
        });
      });
    } else {
      api.getRankSportInfo(widget.id).then((data) {
        setState(() {
          _data = data.data;
          print("${data.data.user}====================");
          if (data.data.user != null && data.data.user.position > 10) {
            _data.records.add(data.data.user);
          } else if (data.data.user == null) {
            _data.records.add(new User(
                userName: prefs.getString("name"),
                userAvatar: prefs.getString("avatar")));
          }
          _isLoading = false;
        });
      });
    }
  }

  // area(bool all, bool province, int provinceId, int cityId) {
  //   setState(() {
  //     _isLoading = true;
  //   });
  //   if (widget.type == "1") {
  //     api
  //         .getRankGameInfo(widget.id,
  //             )
  //         .then((data) {
  //       setState(() {
  //         _data = data.data;
  //         _isLoading = false;
  //       });
  //     });
  //   } else {
  //     api
  //         .getRankSportInfo(widget.id,
  //             provinceId: all ? null : provinceId,
  //             cityId: all ? null : province ? null : cityId)
  //         .then((data) {
  //       setState(() {
  //         _data = data.data;
  //         _isLoading = false;
  //       });
  //     });
  //   }
  // }

  initUser(int rank) {
    return User(position: rank, userName: '虚位以待', score: 0, id: 0);
  }

  Widget _buildRankWidget() {
    dynamic user1 = initUser(1),
        user2 = initUser(2),
        user3 = initUser(3),
        user4;
    if (_data != null && _data.records != null) {
      for (var i = 0; i < _data.records.length; i++) {
        var item = _data.records[i];
        if (i == 0) {
          user1 = item;
        } else if (i == 1) {
          user2 = item;
        } else if (i == 2) {
          user3 = item;
        }
      }
    }

    return Column(
      children: <Widget>[
        Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              Container(
                  width: 94,
                  child: user2 != null
                      ? _buildRankHeaderWidget(user2)
                      : _buildRankHeaderWidget(initUser(2))),
              Container(
                  width: 120,
                  child: user1 != null
                      ? _buildRankHeaderWidget(user1)
                      : _buildRankHeaderWidget(initUser(1))),
              Container(
                  width: 94,
                  child: user3 != null
                      ? _buildRankHeaderWidget(user3)
                      : _buildRankHeaderWidget(initUser(3))),
            ],
          ),
        ),
        Space(
          height: 10,
        ),
        Divider(
          height: 1,
          indent: 12,
          endIndent: 12,
        )
      ],
    );
  }

  Widget _buildRankHeaderWidget(User user) {
    int rank = user.position;
    return InkWell(
      child: Column(
        children: <Widget>[
          rank == 1
              ? Stack(
                  alignment: Alignment.center,
                  children: <Widget>[
                    CircleAvatar(
                        backgroundImage: userAvatarProvider(
                            user.userAvatar == null ? "" : user.userAvatar),
                        radius: 46.0),
                    Image.asset(
                      "lib/assets/img/rank_image_no$rank.png",
                    )
                  ],
                )
              : Stack(
                  alignment: Alignment.topCenter,
                  children: <Widget>[
                    Positioned(
                        top: 3,
                        child: CircleAvatar(
                            backgroundImage: userAvatarProvider(
                                user.userAvatar == null ? "" : user.userAvatar),
                            radius: 35.0)),
                    Image.asset(
                      "lib/assets/img/rank_image_no$rank.png",
                    )
                  ],
                ),
          Space(
            height: 6,
          ),
          Text(
            "${user.userName}",
            style: Theme.of(context).textTheme.subtitle1,
            maxLines: 1,
          ),
          Space(
            height: 4,
          ),
          _dataText(_data.rank, user)
        ],
      ),
      onTap: () {
        if (user.id != 0)
          NavigatorUtil.goRankPeopleDetails(context, details: user);
      },
    );
  }

  Widget _buildRankItemWidget(int number, User data) {
    // print("lib/assets/img/${rankImages[number]}")
    return Column(
      children: <Widget>[
        InkWell(
          onTap: () {
            if (data is User) {
              if (data.id != 0 && data.duration != null)
                NavigatorUtil.goRankPeopleDetails(context, details: data);
            }
          },
          child: Container(
            decoration: data.userId == int.parse(selfId) || data.userId == null
                ? BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage("lib/assets/img/rank_bg_my.png"),
                    ),
                  )
                : null,
            padding: EdgeInsets.symmetric(horizontal: 12.0, vertical: 6.0),
            child: Row(
              children: <Widget>[
                _buildTitle(number, data.id != null),
                Padding(
                  padding: const EdgeInsets.fromLTRB(0, 6, 10.0, 6),
                  child: CircleAvatar(
                      backgroundColor: Colors.transparent,
                      backgroundImage: userAvatarProvider(
                          data.userAvatar == null ? "" : data.userAvatar),
                      radius: 22),
                ),
                Expanded(
                  child: Text(
                    data.userName,
                    style: Theme.of(context).textTheme.subtitle1,
                    maxLines: 1,
                  ),
                ),
                _dataText(_data.rank, data),
              ],
            ),
          ),
        ),
        Divider(
          height: 1,
          indent: 12,
          endIndent: 12,
        ),
      ],
    );
  }

  List<Widget> getRankItems() {
    List<Widget> rankItems = [];
    if (_data != null && _data.records != null) {
      for (var i = 0; i < _data.records.length; i++) {
        var item = _data.records[i];
        rankItems.add(_buildRankItemWidget(i + 1, item));
      }
    }
    if (rankItems.length < 7) {
      int start = rankItems.length;
      for (var i = start; i < 7; i++) {
        var item = initUser(i + 4);
        rankItems.add(_buildRankItemWidget(i + 4, item));
      }
    }
    return rankItems;
  }

  Widget getUserRank() {
    return Positioned(
      bottom: -36.0,
      left: 12.0,
      right: 12.0,
      child: Container(
        width: MediaQuery.of(context).size.width * 0.95,
        height: 72.0,
        decoration: BoxDecoration(
            // color: Colors.white, // 底色
            borderRadius:
                new BorderRadius.all(Radius.circular(10.0)), // 也可控件一边圆角大小
            boxShadow: [
              BoxShadow(
                  offset: Offset(0.0, 0),
                  blurRadius: 7,
                  spreadRadius: 0,
                  color: Color.fromRGBO(0, 0, 0, 0.07))
            ],
            image: _data.user != null
                ? DecorationImage(
                    image: AssetImage("lib/assets/img/rank_bg_my.png"),
                  )
                : null),
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 12.0),
          child: Row(
            children: <Widget>[
              _data.user != null
                  ? Container(
                      padding: EdgeInsets.only(right: 8),
                      child: Text(
                        "${_data.user.position}",
                        style: Theme.of(context).textTheme.bodyText2,
                      ),
                    )
                  : Container(),
              _data.user != null
                  ? _data.user.up != 0 && _data.user.upNew != 0
                      ? Padding(
                          padding: EdgeInsets.only(right: 8),
                          child: Image.asset(
                              "lib/assets/img/rand_icon_${_data.user.up >= 0 ? 'top' : 'down'}.png"),
                        )
                      : Container()
                  : Container(),
              Expanded(
                child: Container(
                  child: Consumer<UserModel>(
                    builder: (_, model, __) {
                      return Row(
                        mainAxisSize: MainAxisSize.max,
                        children: <Widget>[
                          CircleAvatar(
                              backgroundImage: userAvatarProvider(
                                  model?.user?.avatar != null
                                      ? model.user.avatar
                                      : ""),
                              radius: 22),
                          SizedBox(
                            width: 10,
                          ),
                          Expanded(
                            child: Text(
                              model.user.name,
                              overflow: TextOverflow.ellipsis,
                              style: Theme.of(context).textTheme.subtitle1,
                            ),
                          ),
                          SizedBox(
                            width: 10,
                          ),
                        ],
                      );
                    },
                  ),
                ),
              ),
              _data.user == null
                  ? Text(
                      "暂无记录",
                      style: Theme.of(context).textTheme.bodyText1,
                    )
                  : _data.rank.userCountMax < _data.user.position
                      ? Text(
                          "暂未上榜",
                          style: Theme.of(context).textTheme.bodyText1,
                        )
                      : _dataText(_data.rank, _data.user),
              Container(
                width: 12.0,
                height: 14.0,
                margin: EdgeInsets.only(left: 18.0),
                child: Image.asset(
                  "lib/assets/img/rank_icon_location.png",
                  fit: BoxFit.cover,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _dataText(Rank rank, User user) {
    var unit = _dataUnit(rank);
    if (rank != null) {
      if (rank.field == null || rank.field == "") {
        return Text(
            user.score == null || user.score == 0
                ? "暂无成绩"
                : "${user.score.toStringAsFixed(1)}$unit",
            style: TextStyle(color: Color.fromRGBO(255, 196, 0, 1)));
      } else {
        if (rank.field == 'consume') {
          return Text(
              user.consume == null ? "" : "${user.consume.round()}$unit",
              style: TextStyle(color: Color.fromRGBO(255, 196, 0, 1)));
        } else if (rank.field == 'duration') {
          return Text(user.duration == null ? "" : "${user.duration}$unit",
              style: TextStyle(color: Color.fromRGBO(255, 196, 0, 1)));
        }
      }
    }
    return Container();
  }

  String _dataUnit(Rank rank) {
    if (rank != null) {
      if (rank.field == null || rank.field == "") {
        return "分";
      } else {
        if (rank.field == 'consume') {
          return "kal";
        } else if (rank.field == 'duration') {
          return "分钟";
        }
      }
    }
    return "";
  }

  Widget _buildTitle(int number, bool isInRank) {
    // 直接先未上榜的...
    if (number > 10 || !isInRank)
      return Container(
        width: 40,
        margin: EdgeInsets.fromLTRB(5, 0, 5, 0),
        child: Text(
          "未上榜",
          style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 11.0),
        ),
      );
    // 这里是 看是 前三 还是后七
    if (number <= rankImages.length - 1 && rankImages[number] != null)
      return Container(
          margin: EdgeInsets.fromLTRB(0, 0, 5, 0),
          width: 25.0,
          child: Image.asset("lib/assets/img/${rankImages[number]}"));
    else {
      return Container(
        width: 20,
        margin: EdgeInsets.fromLTRB(5, 0, 5, 0),
        child: Text(
          "$number",
          style: Theme.of(context).textTheme.bodyText2,
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    // if(_data?.records?.length != null){
    //   for(var i = 0;i<_data.records.length;i++){
    //     print("${_data.records[i].toJson()}-=============-=-=-=-=-=-=-=-=-=-=-=-=-=-");
    //   }
    // }
    return AnnotatedRegion<SystemUiOverlayStyle>(
        value: SystemUiOverlayStyle.light,
        child: Scaffold(
            backgroundColor: Colors.white,
            body: Stack(
              fit: StackFit.expand,
              children: <Widget>[
                Align(
                  alignment: Alignment.topCenter,
                  child: Container(
                      width: MediaQuery.of(context).size.width,
                      height: _data?.rank?.isGame != 1
                          ? MediaQuery.of(context).size.width * 611 / 1125
                          : MediaQuery.of(context).size.width * 500 / 750,
                      decoration: _data?.rank?.isGame == null
                          ? null
                          : BoxDecoration(
                              image: DecorationImage(
                                  image: _data?.rank?.isGame != 1
                                      ? AssetImage("lib/assets/img/rank_bg.png")
                                      : AssetImage(
                                          "lib/assets/img/rand_bg_consume.png"),
                                  fit: BoxFit.cover)),
                      child: SafeArea(
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 12),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisSize: MainAxisSize.min,
                              children: <Widget>[],
                            ),
                          ),
                        ),
                      )),
                ),
                if (!_isLoading)
                  _data?.rank?.isGame != 1
                      ? SafeArea(
                          child: Padding(
                            padding: EdgeInsets.fromLTRB(24.0, 36.0, 0, 0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisSize: MainAxisSize.min,
                              children: <Widget>[
                                Padding(
                                  padding: EdgeInsets.symmetric(vertical: 6.0),
                                  child: Text(
                                    "${_data.rank.name}",
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 20,
                                        fontWeight: FontWeight.w600),
                                  ),
                                ),
                                Padding(
                                  padding: EdgeInsets.symmetric(vertical: 2.0),
                                  child: Text(
                                    "${_data.rank.introduce}",
                                    style:
                                        Theme.of(context).textTheme.bodyText1,
                                  ),
                                ),
                                GestureDetector(
                                    onTap: () {
                                      itemScrollController.scrollTo(
                                          index: _data?.user?.position != null ? _data.user.position - 1 :
                                              _data.records.length - 1,
                                          duration: Duration(microseconds: 10));
                                    },
                                    child: Container(
                                        margin: EdgeInsets.fromLTRB(
                                            0.0, 12.0, 0, 0),
                                        child: Image.asset(
                                          "lib/assets/img/rank_btn_myrank.png",
                                          width: 103.0,
                                          height: 28.0,
                                        ))),
                              ],
                            ),
                          ),
                        )
                      : SafeArea(
                          child: Column(
                            children: <Widget>[
                              Padding(
                                  padding: EdgeInsets.only(top: 16.0),
                                  child: ClipRRect(
                                      borderRadius: BorderRadius.circular(8),
                                      child: CachedNetworkImage(
                                          imageUrl: _data.rank.logo,
                                          width: 100,
                                          height: 100))),
                              Padding(
                                padding: EdgeInsets.only(top: 10.0),
                                child: Text(
                                  "${_data.rank.name}",
                                  style: TextStyle(
                                      fontSize: 16.0, color: Color(0xffffffff)),
                                ),
                              ),
                              GestureDetector(
                                  onTap: () {
                                    itemScrollController.scrollTo(
                                        index: _data?.user?.position != null ? _data.user.position - 1 :
                                        _data.records.length - 1,
                                        duration: Duration(microseconds: 10));
                                  },
                                  child: Container(
                                      margin:
                                          EdgeInsets.fromLTRB(0.0, 12.0, 0, 0),
                                      child: Image.asset(
                                        "lib/assets/img/rank_btn_myrank.png",
                                        width: 103.0,
                                        height: 28.0,
                                      ))),
                            ],
                          ),
                        ),
                if (_isLoading) Container(child: RequestLoadingWidget()),
                Positioned(
                    left: 0.0,
                    top: 0.0,
                    child: SafeArea(
                      child: IconButton(
                        icon: Image.asset(
                            "lib/assets/img/topbar_return_white.png"),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                    )),
                Positioned(
                    top: 0,
                    right: 0,
                    child: SafeArea(
                      child: IconButton(
                        icon: Image.asset("lib/assets/img/topbar_problom.png"),
                        onPressed: () {
                          if (_data == null) return;
                          NavigatorUtil.go(context,
                              "${Routes.rankIntroduce}?data=${Uri.encodeComponent(json.encode(_data))}");
                        },
                      ),
                    )),
                if (!_isLoading)
                  Positioned(
                      top: _data?.rank?.isGame != 1
                          ? MediaQuery.of(context).size.width * 611 / 1125 - 10
                          : MediaQuery.of(context).size.width * 500 / 750 - 10,
                      left: 0,
                      right: 0,
                      bottom: 0,
                      child: CustomScrollView(
                        controller: _controller,
                        slivers: <Widget>[
                          SliverPersistentHeader(
                            delegate: PersistentHeader(
                                min: 60,
                                max: 60,
                                child: Container(
                                  height: 80.0,
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.only(
                                        topRight: Radius.circular(10.0),
                                        topLeft: Radius.circular(10.0)),
                                    color: Colors.white,
                                  ),
                                  padding:
                                      EdgeInsets.only(bottom: 10, top: 10.0),
                                  child: TabBar(
                                    isScrollable: true,
                                    indicatorPadding:
                                        EdgeInsets.symmetric(horizontal: 8),
                                    indicatorWeight: 3,
                                    labelPadding:
                                        EdgeInsets.symmetric(horizontal: 30),
                                    controller: _tabController,
                                    tabs:
                                        _tabs.map((e) => Tab(text: e)).toList(),
                                  ),
                                )),
                            pinned: true,
                          ),
                          SliverFillRemaining(
                            child: ScrollablePositionedList.builder(
                              itemCount: _data.records.length,
                              itemBuilder: (context, index) {
                                return _buildRankItemWidget(
                                    index + 1, _data.records[index]);
                              },
                              itemScrollController: itemScrollController,
                              itemPositionsListener: itemPositionsListener,
                            ),
                          ),
                        ],
                      ))
              ],
            )));
  }
}
