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

import 'package:flutter/material.dart';
import './../native_bridge.dart';

/// 目标位置距当前设备的距离
class RealtimeDistance extends StatefulWidget {
  const RealtimeDistance(
      {Key key, this.callJSMethod, this.distance, this.targetLanLat, this.msgType, this.currentLngLat, this.style})
      : super(key: key);

  final ExecuteJSMethod callJSMethod;
  final Map targetLanLat;
  final Map currentLngLat;
  final String distance;
  final String msgType;
  final TextStyle style;

  @override
  _RealtimeDistanceState createState() => _RealtimeDistanceState();
}

class _RealtimeDistanceState extends State<RealtimeDistance> {
  Timer _timer;

  @override
  void initState() {
    super.initState();
    distanceTimer();
    calcDistance();
  }

  @override
  Widget build(BuildContext context) {
    return Text(widget.distance != null ? '距您${widget.distance}    ' : '', style: widget.style);
  }

  void distanceTimer() {
    if (widget.currentLngLat.isNotEmpty && widget.targetLanLat.isNotEmpty) {
      Timer.periodic(const Duration(seconds: 10), (timer) {
        _timer = timer;
        calcDistance();
      });
    }
  }

  void calcDistance() {
    Function callback = widget.callJSMethod;
    String args = jsonEncode(
        {'currentLngLat': widget.currentLngLat, 'targetLanLat': widget.targetLanLat, 'msgType': widget.msgType});
    callback('getDistanceData($args)');
  }

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