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:flutter/material.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/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:permission_handler/permission_handler.dart';

class SignPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return SignPageState();
  }
}

class SignPageState extends State<SignPage> {

  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;

  startTime() async {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (!mounted) return;
      setState(() {
        _nowTimeStr = DateTime.now().toString().split(" ")[1].split(".")[0];
      });
    });
  }

  @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;
    startTime();
    getSignConfig();
    getTodayList();
    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() {
    _timer.cancel();
    if (null != _locationListener) {
      _locationListener.cancel();
    }

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

  getSignConfig() {
    ApiService(context: context).signConfig(
        onSuccess: (res) {
          configItem = res;
          setState(() {});
        },
        onError: (code, msg) {});
  }

  getTodayList() {
    ApiService(context: context).signList(
        1, 10, DateTime.now().toString().split(" ")[0], onSuccess: (data) {
      list = data.rows;
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  getSignAdd() {
    if (configItem.topTime.length == 0) {
      toasts("未设置打卡");
      return;
    }
    if (currentAddress.length == 0) {
      toasts("定位正在初始化,请重试。");
      return;
    }
    NavigatorUtils.pushResult(context,
        "${SignRouter.signAddPage}?address=${Uri.encodeComponent(currentAddress)}&coordinate=${latLng.longitude},${latLng.latitude}&toptime=${configItem.topTime}&downtime=${configItem.downTime}&toptimepm=${configItem.topTimePm}&downtimepm=${configItem.downTimePm}&toptimeot=${configItem.topTimeOt}&downtimeot=${configItem.downTimeOt}",
        (res) {
      getTodayList();
    });
  }

  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: "考勤",
        actions: <Widget>[
          FlatButton(
            child: Text("考勤记录", key: const Key('actionName')),
            textColor: Colours.dark_text,
            highlightColor: Colors.transparent,
            onPressed: () {
              NavigatorUtils.push(context, SignRouter.signListPage);
            },
          )
        ],
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Container(
                color: ThemeUtils.getTabsBg(context),
                padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      flex: 1,
                      child: Text(
                        "当前位置:${currentAddress ?? ''}",
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    )
                  ],
                )),
            Container(
                height: 345,
                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,
                        ));
                      },
                    ),
//                    AmapView(
//                      mapType: MapType.Standard,
//                      // 是否显示缩放控件
//                      showZoomControl: false,
//                      // 是否显示指南针控件
//                      showCompass: false,
//                      // 是否显示比例尺控件
//                      showScaleControl: false,
//                      // 是否使能缩放手势
//                      zoomGesturesEnabled: true,
//                      // 是否使能滚动手势
//                      scrollGesturesEnabled: true,
//                      // 是否使能旋转手势
//                      rotateGestureEnabled: true,
//                      // 是否使能倾斜手势
//                      tiltGestureEnabled: true,
//                      // 缩放级别
//                      zoomLevel: 18,
////                      markers: _markers,
//                      // 中心点坐标
//                      centerCoordinate: latLng,
//                      // 标记
//                      onMapCreated: (controller) async {
//                        if (await requestPermission()) {
//                          await controller.showMyLocation(MyLocationOption(show: true));
//                        }
////                        await getLocation();
////                        _markers = [
////                          MarkerOption(
////                              title: "我的位置",
////                              latLng: latLng,
////                              iconUri: _assetsIcon,
////                              imageConfig:
////                                  createLocalImageConfiguration(mContext),
////                              width: 28,
////                              height: 28)
////                        ];
////                        controller.setCenterCoordinate(latLng);
////                        controller.showMyLocation(MyLocationOption());
////                        setState(() {});
//                      },
//                    ),
//                    BoxShadow(color: Colors.grey[300],offset: Offset(1, 1),
//                      ///模糊阴影半径
//                      blurRadius: 5,
//                    )
                    Positioned(
                      right: 14,
                      bottom: 19,
                      child: GestureDetector(
                        onTap: () {
                          getSignAdd();
                        },
                        child: Container(
                          height: 75,
                          width: 75,
                          decoration: BoxDecoration(
                              color: Colours.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: 13,
                                    fontWeight: FontWeight.w500,
                                    color: Colors.white),
                              ),
                              Text("${_nowTimeStr}",
                                  style: TextStyle(
                                      fontSize: 13,
                                      fontWeight: FontWeight.w500,
                                      color: Colors.white))
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                )),
            Container(
              padding: EdgeInsets.only(left: 10),
              alignment: Alignment.centerLeft,
              height: 45,
              decoration: BoxDecoration(
                border: Border(
                  bottom: BorderSide(width: 0.5, color: Colours.line),
                ),
              ),
              child: Text(
                "今日打卡记录",
                style: TextStyle(fontSize: 14, color: Color(0xFF333333)),
              ),
            ),
            Expanded(
                flex: 1,
                child: ListView.separated(
                  shrinkWrap: true,
                  itemCount: list.length,
                  separatorBuilder: (BuildContext context, int index) {
                    return Container(
                      height: 0.5,
                      color: Color(0xFFF5F5F5),
                    );
                  },
                  itemBuilder: (_, index) {
                    return Container(
                      color: Colors.white,
                      padding: const EdgeInsets.symmetric(
                          horizontal: 15.0, vertical: 12.0),
                      alignment: Alignment.centerLeft,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          Text("类型：${list[index].typeDesc}"),
                          Text("时间：${list[index].createDate}"),
                          Text("地址：${list[index].address}"),
                          Text("状态：${list[index].statusDesc}")
                        ],
                      ),
                    );
                  },
                ))
          ],
        ),
      ),
    );
  }
}
