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:amap_map_fluttify/amap_map_fluttify.dart';
// import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/internal/sign/model/sign_config_item.dart';
import 'package:liftmanager/internal/sign/model/sign_list_entity.dart';
import 'package:liftmanager/internal/sign/sign_router.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:permission_handler/permission_handler.dart';

class ExpertCheckPage extends StatefulWidget {
  Function(double lat, double lon, String address) backFun;

  ExpertCheckPage({this.backFun});
  @override
  State<StatefulWidget> createState() {
    return ExpertCheckPageState();
  }
}

class ExpertCheckPageState extends State<ExpertCheckPage> {
  Map<String, Object> _locationResult;
  StreamSubscription<Map<String, Object>> _locationListener;
  AmapLocationFlutterPlugin _locationPlugin = new AmapLocationFlutterPlugin();

  // 计时器。
  // Timer _timer;
  // String _nowTimeStr = "";
  LatLng latLng = LatLng(0, 0);
  String currentAddress = "";
  SignConfigItem configItem = SignConfigItem();
  List<SignListItem> list = [];
  BuildContext mContext;
  AmapController _controller;

  @override
  void initState() {
    super.initState();
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      setState(() {
        _locationPlugin.stopLocation();
        _locationResult = result;
//        address latitude longitude
        _locationResult.forEach((key, value) {
          if (key == 'address') {
            currentAddress = '$value';
            setState(() {});
          } else if (key == 'latitude') {
            latLng.latitude = double.parse('$value');
            setState(() {});
          } else if (key == 'longitude') {
            latLng.longitude = double.parse('$value');
            setState(() {});
          }
          print(111);
          print('key:$key :');
          print('value:$value :');
        });
      });
    });
    mContext = context;

    getLocation();
  }

  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);
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    mContext.dependOnInheritedWidgetOfExactType();
  }

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

  @override
  void dispose() {
    if (null != _locationListener) {
      _locationListener.cancel();
    }

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

  getSignAdd() {
    if (currentAddress.length == 0) {
      toasts("定位正在初始化,请重试。");
      return;
    }

    widget.backFun(latLng.latitude, latLng.longitude, currentAddress);
    Navigator.of(context).pop();
  }

  Future<bool> requestPermission() async {
    final permissions = await PermissionHandler()
        .requestPermissions([PermissionGroup.location]);

    if (permissions[PermissionGroup.location] == PermissionStatus.granted) {
//      toasts("已经定位.");
      return true;
    } else {
      toasts('需要定位权限!');
      return false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: "定位打卡",
      ),
      body: Container(
        color: Colors.white,
        child: Column(
          children: <Widget>[
            Container(
                height: ScreenUtil().setHeight(250),
                child: Stack(
                  children: <Widget>[
                    AmapView(
                      mapType: MapType.Standard,
                      showZoomControl: false,
                      centerCoordinate: latLng,
                      zoomLevel: 17,
                      maskDelay: Duration(milliseconds: 500),
                      onMapCreated: (controller) async {
                        _controller = controller;
                        await _controller?.showMyLocation(MyLocationOption(
                          myLocationType: MyLocationType.Locate,
                        ));
                      },
                    ),
                    Positioned(
                        top: ScreenUtil().setHeight(140),
                        left: ScreenUtil().setWidth(130),
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(4),
                          child: Container(
                            width: ScreenUtil().setWidth(222),
                            padding: EdgeInsets.all(5),
                            color: Colours.blue_app_main,
                            child: Text(
                              " 当前位置:${currentAddress ?? ''} ",
                              style: TextStyle(color: Colors.white),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ))

//
                  ],
                )),
            Container(
                // padding: EdgeInsets.only(left: 10),
                alignment: Alignment.centerLeft,
                height: 45,
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(width: 0.5, color: Colours.line),
                  ),
                ),
                child: Row(
                  children: [
                    Container(
                      // margin: EdgeInsets.only(left: 10),
                      height: 13, width: 2, color: Colours.blue_app_main,
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Text(
                      "打卡信息",
                      style: TextStyle(fontSize: 14, color: Colours.text),
                    ),
                  ],
                )),
            Container(
              child: Row(
                children: [
                  SizedBox(
                    width: 5,
                  ),
                  Icon(
                    const IconData(0xe638, fontFamily: "Iconfont"),
                    size: 17.0,
                    color: Colours.blue_app_main,
                  ),
                  Text(
                    '$currentAddress',
                    style: TextStyle(color: Colours.blue_app_main),
                  ),
                ],
              ),
            ),
            Expanded(child: Container()),
            GestureDetector(
              onTap: () {
                getSignAdd();
              },
              child: Container(
                height: 110,
                width: 110,
                decoration: BoxDecoration(
                    color: Colours.blue_app_main,
                    boxShadow: [
                      ///阴影颜色/位置/大小等
                      BoxShadow(
                        color: Colors.grey[300], offset: Offset(1, 1),

                        ///模糊阴影半径
                        blurRadius: 5,
                      ),
                      BoxShadow(
                          color: Colors.grey[300],
                          offset: Offset(-1, -1),
                          blurRadius: 5),
                      BoxShadow(
                          color: Colors.grey[300],
                          offset: Offset(1, -1),
                          blurRadius: 5),
                      BoxShadow(
                          color: Colors.grey[300],
                          offset: Offset(-1, 1),
                          blurRadius: 5)
                    ],
                    borderRadius: BorderRadius.circular(73)),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      "打卡",
                      style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                          color: Colors.white),
                    ),
                  ],
                ),
              ),
            ),
            SizedBox(
              height: ScreenUtil().setHeight(30),
            )
          ],
        ),
      ),
    );
  }
}
