import 'dart:async';

import 'package:amap_location_flutter_plugin/amap_location_flutter_plugin.dart';
import 'package:amap_location_flutter_plugin/amap_location_option.dart';
import 'package:flutter/material.dart';
import 'package:liftmanager/internal/friends/friends_router.dart';
import 'package:liftmanager/internal/friends/page/near_detail.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:permission_handler/permission_handler.dart';
import 'package:liftmanager/common/common.dart';

class NearList extends StatefulWidget {
  // QuestionList(this.index);

  // final String index;

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

class NearListState extends State<NearList> {
  // NewsDetailItem item = NewsDetailItem();

  Map<String, Object> _locationResult;
  StreamSubscription<Map<String, Object>> _locationListener;
  AmapLocationFlutterPlugin _locationPlugin = new AmapLocationFlutterPlugin();

  ScrollController _scrollController = new ScrollController();
  bool _hasData = false;
  List<dynamic> nearList = [];

  void initState() {
    super.initState();

    ///移除定位监听
    if (null != _locationListener) {
      _locationListener.cancel();
    }

    ///销毁定位
    if (null != _locationPlugin) {
      _locationPlugin.destroy();
    }

    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      setState(() {
        _locationPlugin.stopLocation();
        _locationResult = result;
//        address latitude longitude
        _locationResult.forEach((key, value) {
          print(111);
          print('key:$key :');
          print('value:$value :');
        });
        dynamic obj = {
          "lat": _locationResult["latitude"],
          "lon": _locationResult["longitude"],
          "userId": int.parse(FlutterStars.SpUtil.getString(Constant.userId))
        };
        getNearList(obj);
      });
    });
    getLocation();
  }

  ///获取定位权限
  Future<bool> requestPermission() async {
    final permissions = await PermissionHandler()
        .requestPermissions([PermissionGroup.location]);
    if (permissions[PermissionGroup.location] == PermissionStatus.granted) {
      return true;
    } else {
      NavigatorUtils.goBack(context);
      toasts('需要定位权限!');
      return false;
    }
  }

  void _setLocationOption() {
    if (null != _locationPlugin) {
      AMapLocationOption locationOption = new AMapLocationOption();

      ///是否单次定位
      locationOption.onceLocation = true;

      ///是否需要返回逆地理信息
      locationOption.needAddress = true;

      ///逆地理信息的语言类型
      locationOption.geoLanguage = GeoLanguage.DEFAULT;

      ///设置Android端连续定位的定位间隔
      locationOption.locationInterval = 20000;

      ///设置Android端的定位模式<br>
      ///可选值：<br>
      ///<li>[AMapLocationMode.Battery_Saving]</li>
      ///<li>[AMapLocationMode.Device_Sensors]</li>
      ///<li>[AMapLocationMode.Hight_Accuracy]</li>
      locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

      ///设置iOS端的定位最小更新距离<br>
      locationOption.distanceFilter = -1;

      ///设置iOS端期望的定位精度
      /// 可选值：<br>
      /// <li>[DesiredAccuracy.Best] 最高精度</li>
      /// <li>[DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度 </li>
      /// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
      /// <li>[DesiredAccuracy.Kilometer] 1000米</li>
      /// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
      locationOption.desiredAccuracy = DesiredAccuracy.NearestTenMeters;

      ///设置iOS端是否允许系统暂停定位
      locationOption.pausesLocationUpdatesAutomatically = false;

      ///将定位参数设置给定位插件
      _locationPlugin.setLocationOption(locationOption);
    }
  }

  ///获取位置信息
  getLocation() async {
    if (await requestPermission()) {
      if (null != _locationPlugin) {
        ///开始定位之前设置定位参数
        _setLocationOption();
        _locationPlugin.startLocation();
      }
    }
  }

  Future getNearList(obj) async {
    await NewApiService().nearListNoPage(obj, onSuccess: (res) {
      nearList = res;
      _hasData = true;

      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

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

    ///移除定位监听
    if (null != _locationListener) {
      _locationListener.cancel();
    }

    ///销毁定位
    if (null != _locationPlugin) {
      _locationPlugin.destroy();
    }
    super.dispose();
  }

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

    return Scaffold(
      appBar: MyAppBar(
        centerTitle: "附近的人",
      ),
      body: _hasData
          ? Container(
              child: ListView(children: <Widget>[orderListWidget(nearList)]),
            )
          : Center(
              child: Image.asset(
                "assets/images/search_friends.gif",
                width: width * 0.7,
                // height: ScreenUtil().setWidth(43),
                // alignment: Alignment.centerLeft,
              ),
            ),
    );
  }

  Widget orderListWidget(List<dynamic> list) {
    List<Widget> getListWdiget(context) => list.asMap().keys.map((i) {
          return Container(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Expanded(
                    child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () async {
                    await Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => NearDetail(model: list[i])));

                    dynamic obj = {
                      "lat": _locationResult["latitude"],
                      "lon": _locationResult["longitude"],
                      "userId": int.parse(
                          FlutterStars.SpUtil.getString(Constant.userId))
                    };
                    getNearList(obj);
                  },
                  child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        SizedBox(
                          width: 10,
                        ),
                        Container(
                          child: ClipRRect(
                            borderRadius: BorderRadius.all(Radius.circular(24)),
                            child: LoadNetworkImage(
                              list[i].avatarUrl,
                              width: 47,
                              height: 47,
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Expanded(
                            child: Container(
                                // height: 47,
                                padding: EdgeInsets.symmetric(vertical: 15),
                                decoration: BoxDecoration(
                                  border: Border(
                                    bottom: BorderSide(
                                        width: 0.5, color: Colours.line),
                                  ),
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Container(
                                      child: Text(
                                        list[i].remarks ?? list[i].name ?? "",
                                        style: TextStyle(
                                          fontSize: 16,
                                          color: Colors.black,
                                        ),
                                        textAlign: TextAlign.start,
                                      ),
                                    ),
                                    SizedBox(
                                      height: 10,
                                    ),
                                    Container(
                                      child: Text(
                                        (list[i].distance.toString() ?? "") +
                                            "米以内",
                                        style: TextStyle(
                                          color: Color(0xff666666),
                                          fontSize: 13,
                                        ),
                                        textAlign: TextAlign.start,
                                      ),
                                    ),
                                  ],
                                )))
                      ]),
                )),
              ],
            ),
          );
        }).toList();

    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: getListWdiget(context),
      ),
    );
  }
}
