import 'package:flutter/material.dart';
import 'package:liftmanager/internal/bbs/page/chat_room.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/iconfont.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/internal/friends/model/near_model.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';

import '../friends_router.dart';
import 'package:liftmanager/internal/friends/model/friend_model.dart';

class NearDetail extends StatefulWidget {
  final NearModel model;
  final Records friendModel;

  const NearDetail({Key key, this.model, this.friendModel}) : super(key: key);

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

class NearDetailState extends State<NearDetail> {
  ScrollController _scrollController = new ScrollController();
  String targetUserId;
  int distance;
  String avatarUrl;
  String name;

  void initState() {
    super.initState();

    targetUserId = widget.model != null
        ? widget.model.userId.toString()
        : widget.friendModel.targetUserId;
    distance = widget.model != null ? widget.model.distance : null;
    avatarUrl = widget.model != null
        ? widget.model.avatarUrl
        : widget.friendModel.avatarUrl;
    name = widget.model != null
        ? widget.model.remarks ?? widget.model.name
        : widget.friendModel.remarks ?? widget.friendModel.userName;
  }

  Future createPrivateChatRoom(id) async {
    await NewApiService().createPrivateChatRoom(id.toString(),
        onSuccess: (res) async {
      print(res["room"]);
      String roomId = res["room"];

      await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (_) => ChatDetailPage(
              id: roomId, type: 'nearToOne', toUserId: id, title: name),
        ),
      );
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

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

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;

    return Scaffold(
      appBar: MyAppBar(
        centerTitle: widget.model != null ? "附近的人" : '圈子',
      ),
      body: Container(
        child: Column(children: <Widget>[
          SizedBox(
            height: 10,
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              SizedBox(width: 10),
              ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(29)),
                child: LoadNetworkImage(
                  avatarUrl,
                  width: 57,
                  height: 57,
                  // alignment: Alignment.centerLeft,
                ),
              ),
              SizedBox(width: 10),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      name ?? "",
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.black,
                      ),
                      textAlign: TextAlign.start,
                    ),
                    if (distance != null)
                      Text(
                        '距离: $distance 米以内',
                        style:
                            TextStyle(color: Color(0xff666666), fontSize: 13),
                        textAlign: TextAlign.start,
                      ),
                  ],
                ),
              ),
            ],
          ),
          SizedBox(
            height: 20,
          ),
          Divider(
            height: 0.5,
            thickness: 0.5,
            color: Color(0xffF8F8F8),
          ),
          GestureDetector(
            onTap: () async {
              if (widget.model != null) {
                NavigatorUtils.pushResult(context,
                    "${FriendsRouter.remarks}?id=${targetUserId}&remarks=${Uri.encodeComponent(widget.model.remarks ?? '')}",
                    (res) {
                  setState(() {
                    widget.model.remarks = res;
                    name = res;
                  });
                });
              } else {
                NavigatorUtils.pushResult(context,
                    "${FriendsRouter.remarks}?id=${targetUserId}&remarks=${Uri.encodeComponent(widget.friendModel.remarks ?? '')}",
                    (res) {
                  setState(() {
                    widget.friendModel.remarks = res;
                    name = res;
                  });
                });
              }
            },
            child: Container(
              color: Colors.white,
              height: 50,
              child: Row(
                children: [
                  SizedBox(
                    width: 10,
                  ),
                  Text(
                    '备注名',
                    style: TextStyle(
                      color: Color(0xff333333),
                      fontSize: 14,
                    ),
                  ),
                  Spacer(),
                  Icon(
                    Iconfont.gengduo,
                    color: Color(0xffcccccc),
                    size: 14,
                  ),
                  SizedBox(
                    width: 10,
                  ),
                ],
              ),
            ),
          ),
          Divider(
            height: 5,
            thickness: 5,
            color: Color(0xffF8F8F8),
          ),
          FlatButton(
            height: 50,
            child: Text(widget.model != null ? "打招呼" : "发消息"),
            textColor: Color(0xff5589FF),
            onPressed: () async {
              if (widget.model != null) {
                createPrivateChatRoom(targetUserId);
              } else {
                if (widget.friendModel.dataTable == 3) {
                  await Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (_) => ChatDetailPage(
                          id: widget.friendModel.sessionid,
                          type: 'nearToOne',
                          toUserId: widget.friendModel.userId,
                          title: widget.friendModel.remarks ??
                              widget.friendModel.userName),
                    ),
                  );
                }
              }
            },
          ),
          Expanded(
            child: Container(
              color: Color(0xfff8f8f8),
            ),
          )
        ]),
      ),
    );
  }
}
