import 'dart:async';
import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart' hide NestedScrollView;
import 'package:flutter_dong_scan/scan.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:provider/provider.dart';
import 'package:qr_flutter/qr_flutter.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/user_detail_page.dart';
import 'package:sport/provider/lib/provider_widget.dart';
import 'package:sport/provider/lib/simple_model.dart';
import 'package:sport/provider/lib/view_state_lifecycle.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/utils/DateFormat.dart';
import 'package:sport/utils/click.dart';
import 'package:sport/utils/toast.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/button_cancel.dart';
import 'package:sport/widgets/dialog/scan_add_new_friend_dialog.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/space.dart';

class UserFriendAddPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _PageState();
}

class _PageState extends ViewStateLifecycle<UserFriendAddPage, SimpleModel>
    with InjectApi {
  TextEditingController _controller;
  FocusNode _focusNode;
  ValueNotifier<String> _searchValue = ValueNotifier<String>("");

  var userCode; // 用户自己的二维码
  UserInfo _newFriendUserInfo; // 扫码出来的那个逼的userInfo(请求回来的)
  //  int dialogType;                 // 弹窗类型
  String newFriendCode; // 扫码出来的要加的那个逼的二维码
  List<UserFriend> allUserFriends = []; // 等待添加的好友队列
  bool isWaiting = false; // 上锁解决
  Timer timerIsFriend; // 轮询是否是好友
  Timer timerAllFriend; // 轮询是否有好友加你
  int currentIndex = 0; // 不要用栈的方法 用指针的方法...

  @override
  SimpleModel createModel() => SimpleModel((page) async {
        if (_searchValue.value == "") return [];
        return (await api.userSearch(kw: _searchValue.value, page: page))
            .pageResult
            .results;
      });

//  // 试试 写写 ViewModel
//  SimpleDataModel friendModel() => SimpleDataModel<NewFriend>((code) async {
//        return (await api.getNewFriend(code)).data;
//      });

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
    _controller = new TextEditingController(text: '');
    initFriendCode();
    pollGetFriendRequest();
  }

  @override
  void dispose() {
    super.dispose();
    _focusNode?.dispose();
    _controller?.dispose();
    timerIsFriend?.cancel();
    timerAllFriend?.cancel();
  }

  // 初始化 好友码...
  initFriendCode() async {
    var code = await api.getNewFriendCode();
    setState(() {
      userCode = jsonEncode(code.data);
    });
  }

  void _showConfirmDialog() async {
    await showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => ScanAddFriendCustomAlertDialog(
              userInfo: _newFriendUserInfo,
              newFriendCode: newFriendCode,
            ));
  }

  void pollGetFriendRequest() async {
    // 获取 userFriends
    timerIsFriend = Timer.periodic(Duration(seconds: 5), (timer) async {
      List<UserFriend> userFriends = (await api.getFriendRequest()).results;
      if (userFriends.length > 0) {
        if (allUserFriends.length <= 0) {
          allUserFriends.addAll(userFriends);
        } else {
          Iterable<int> allUserFriendsId =
              allUserFriends.map((e) => e.socialInfo.id);
          // 去重...
          for (UserFriend _userfriend in userFriends) {
            if (!allUserFriendsId.contains(_userfriend.socialInfo.id)) {
              allUserFriends.add(_userfriend);
            }
          }
        }
      }
    });
    // 暂时这样解决
    timerAllFriend = Timer.periodic(Duration(seconds: 2), (timer) async {
      // 终极解决方案... 上锁 + 指针 / 用栈的话 还是会 有多次的。用指针就不会了
      if (!isWaiting &&
          allUserFriends.length > 0 &&
          currentIndex < allUserFriends.length) {
        isWaiting = true; //正在等待的意思...
        UserFriend currentUserFriend = allUserFriends[currentIndex];
        bool flag = await showDialog(
            context: context,
            barrierDismissible: false,
            builder: (context) => ScanAddFriendCustomAlertDialog(
                  userInfo: currentUserFriend.socialInfo,
                  isWaitAdd: true,
                ));
        if (flag != null) {
          isWaiting = false;
          currentIndex += 1;
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        leading: buildBackButton(context),
        title: Text(
          "添加好友",
          style: titleStyle,
        ),
        actions: <Widget>[
          IconButton(
            icon: Image.asset("lib/assets/img/fiends_image_scanning.png"),
            onPressed: () {
              ScanConfig scanConfig = ScanConfig();
              SDScan scan =
                  SDScan().setScanEventListener((dynamic friendData) async {
                // 扫描之后就去这个逼的 主页 爱关注 不关注的...
                var data = json.decode(friendData);

                UserInfo _userInfo =
                    (await api.getUserInfo('${data['uid']}')).data;

                setState(() {
                  _newFriendUserInfo = _userInfo;
                  newFriendCode = data['code'];
                  _showConfirmDialog();
                });
              });
              scan.startScan(config: scanConfig);
            },
          ),
        ],
      ),
      body: ProviderWidget<SimpleModel>(
          model: model,
          onModelReady: (model) => model.initData(),
          builder: (_, model, __) {
            return EasyRefresh.custom(
              firstRefresh: false,
              onRefresh: () => model.refresh(),
              onLoad: () => model.loadMore(),
              enableControlFinishRefresh: true,
              controller: model.refreshController,
              header: buildClassicalHeader(),
              footer: buildClassicalFooter(),
              slivers: <Widget>[
                SliverPersistentHeader(
                  delegate: PersistentHeader(
                      min: 50,
                      max: 50,
                      child: Container(
                        color: Colors.white,
                        child: _searchWidget(context),
                      )),
                  pinned: true,
                ),
                if (model.isBusy)
                  SliverToBoxAdapter(
                    child: RequestLoadingWidget(),
                  ),
                if (model.isEmpty || model.isError)
                  SliverToBoxAdapter(
                    child: RequestErrorWidget(
                      null,
                      msg: _searchValue.value == "" ? "请输入搜索的关键字" : "暂无相关用户~",
                    ),
                  ),
                if (model.isIdle)
                  SliverList(
                    delegate: SliverChildBuilderDelegate(
                      (context, index) {
                        return _buildItem(model.list[index]);
                      },
                      childCount: model.list.length,
                    ),
                  ),
                if (!model.isIdle && userCode != null)
                  SliverToBoxAdapter(
                      child: Padding(
                    padding: EdgeInsets.only(top: 20.0),
                    child: Consumer<UserModel>(
                        builder: (_, model, __) => model.user == null
                            ? Center(
                                child: QrImage(
                                data: userCode,
                                version: QrVersions.auto,
                                size: 170,
                                gapless: false,
                              ))
                            : InkWell(
                                child: Center(
                                    child: QrImage(
                                        data: userCode,
                                        version: QrVersions.auto,
                                        size: 170,
                                        gapless: false,
                                        embeddedImage: userAvatarProvider(
                                            model.user.avatar))),
                              )),
                  )),
              ],
            );
          }),
    );
  }

  Widget _buildItem(UserInfo user) {
    Widget child = Row(
      children: <Widget>[
        CircleAvatar(
          backgroundImage: userAvatarProvider(user?.avatar),
          radius: 22,
        ),
        SizedBox(
          width: 8,
        ),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                "${user?.name}",
                style: Theme.of(context).textTheme.headline3,
              ),
              SizedBox(
                height: 4,
              ),
              Text(
                "ID: ${user?.id}",
                style: Theme.of(context).textTheme.bodyText2,
              ),
            ],
          ),
        ),
        user.isFriend()
            ? Container(
                width: 64,
                height: 30,
                margin: EdgeInsets.only(left: 8.0),
                alignment: Alignment.center,
                child: Text(
                  "已关注",
                  strutStyle: fixedLine,
                  style: Theme.of(context)
                      .textTheme
                      .bodyText2
                      .copyWith(color: Theme.of(context).accentColor),
                ),
              )
            : GestureDetector(
                child: Container(
                  width: 64,
                  height: 30,
                  margin: EdgeInsets.only(left: 8.0),
                  alignment: Alignment.center,
                  child: Text(
                    "关注",
                    strutStyle: fixedLine,
                    style: Theme.of(context)
                        .textTheme
                        .bodyText2
                        .copyWith(color: Theme.of(context).accentColor),
                  ),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20),
                    border: Border.all(
                      color: Theme.of(context).accentColor,
                      width: .5,
                    ),
                  ),
                ),
                onTap: () async {
                  if (user.isFriend()) return;
                  await request(context, () async {
                    var resp = await model.api
                        .userFollow(uid: user?.id)
                        .catchError((onError) {});
                    if (resp?.code == 0) {
                      ToastUtil.show("关注成功");
                      setState(() {
                        user.followStatus = "followed";
                      });
                    }
                  });
                },
              )
      ],
    );
    return Column(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(12.0),
          child: InkWell(
              onTap: () async {
                List<UserFriend> friends = model.list
                    .map((e) => UserFriend(
                        uid: user.id,
                        socialInfo: user,
                        isFriends: user.isFriend() ? "1" : "0"))
                    .toList();
                await NavigatorUtil.goPage(
                    context,
                    (context) => UserDetailPage(
                        PostUser(
                            id: "${user?.id}",
                            name: user?.name,
                            avatar: user?.avatar),
                        userFriends: friends));
                user.followStatus = friends
                            .firstWhere((element) => element.uid == user.id)
                            ?.isFriends ==
                        "1"
                    ? "followed"
                    : "none";
                setState(() {});
              },
              child: child),
        ),
        Divider(
          height: 1,
        )
      ],
    );
  }

  Widget _searchWidget(BuildContext context) {
    return Container(
      margin: EdgeInsets.fromLTRB(12.0, 6.0, 12.0, 6.0),
      height: 40,
      padding: EdgeInsets.fromLTRB(12.0, 0, 12.0, 0),
      decoration: BoxDecoration(
        color: Color(0xffF1F1F1),
        shape: BoxShape.rectangle,
        borderRadius: BorderRadius.all(Radius.circular(50)),
      ),
      child: Row(
        children: <Widget>[
          Image.asset("lib/assets/img/searchbar_icon_search.png"),
          SizedBox(
            width: 6,
          ),
          Expanded(
            child: TextField(
              controller: _controller,
              maxLines: 1,
              focusNode: _focusNode,
              decoration: InputDecoration(
                hintText: '输入账号/用户昵称',
                // contentPadding: EdgeInsets.all(10),
                border: InputBorder.none,
              ),
              onChanged: debounceValueChanged((value) {
                _searchValue.value = value;
                model.initData();
              }),
              onSubmitted: (value) {
                _focusNode?.unfocus();
              },
            ),
          ),
          Visibility(
              visible: _searchValue.value?.isNotEmpty == true,
              child: GestureDetector(
                onTap: () {
                  _searchValue.value = "";
                  model.initData();
                  _controller.clear();
                },
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Image.asset("lib/assets/img/searchbar_btn_no.png"),
                ),
              )),
        ],
      ),
    );
  }
}
