import 'dart:math';

import 'package:chat/data/UserData.dart';
import 'package:chat/map/google_map_location_picker.dart';
import 'package:chat/map/location_result.dart';
import 'package:chat/models/group_info_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../data/constants.dart';
import '../../generated/i18n.dart';
import '../../utils/CustomUI.dart';

class TravelButlerPage extends StatefulWidget {
  final GroupInfoModel groupInfoModel;

  TravelButlerPage({Key key, this.groupInfoModel}) : super(key: key);

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

class TravelButlerPageState extends State<TravelButlerPage> {

  LocationResult startResult;
  LocationResult endResult;

  double distance=0.0;
  double distanceB=0.0;

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

  @override
  void dispose() {
//    MessageMgr().off('Update Group Info', updateGroupInfo);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget appBar = AppBar(
      backgroundColor: AppColors.NewAppbarBgColor,
      title: Text(
        I18n.of(context).travel_butler,
        textScaleFactor: 1.0,
        style: TextStyle(color: AppColors.NewAppbarTextColor),
      ),
//      leading: CustomUI.buildCustomLeading(context),
      centerTitle: true,
    );

    return Scaffold(
      appBar: appBar,
      body: SafeArea(
        child: ListView(
          children: <Widget>[
            InkWell(
              child: Text(
                I18n.of(context).travel_butler+'起点',
                textScaleFactor: 1.0,
                style: TextStyle(color: AppColors.NewAppbarTextColor,fontSize: 30),
              ),
              onTap: () async{
               startResult =await  _openMap(context);
              },
            ),
            InkWell(
              child: Text(
                I18n.of(context).travel_butler+'终点',
                textScaleFactor: 1.0,
                style: TextStyle(color: AppColors.NewAppbarTextColor,fontSize: 30),
              ),
              onTap: () async{
             endResult = await  _openMap(context);
              },
            ),

            InkWell(
              child: Text(
                '距离查询',
                textScaleFactor: 1.0,
                style: TextStyle(color: AppColors.NewAppbarTextColor,fontSize: 30),
              ),
              onTap: () async{

                if(startResult!=null && endResult!=null){
                  distanceB =await  Geolocator().distanceBetween(startResult.latLng.latitude,startResult.latLng.longitude,endResult.latLng.latitude,endResult.latLng.longitude);

                  setState(() {
              print('开始计算');
              distance =getDistance(startResult.latLng.latitude,startResult.latLng.longitude,endResult.latLng.latitude,endResult.latLng.longitude);



            });
                }else{
                  print('参数为空');
                }


              },
            ),


//            Text('距离为: ${getDistanceStr(distance)}'),
//            Text('距离为: ${getDistanceStr(distanceB)}')
            Text('距离为: $distance'),
            Text('距离为: $distanceB'),

          ],
        ),
      ),
    );
  }


  getDistanceStr(double m){


    if(m<1000){
      return '${m.toInt()} M';
    }else{
      return '${(m/1000).toStringAsFixed(2)} KM';
    }

  }


  getDistance(double lat1, double lng1, double lat2, double lng2) {
    double radLat1 = rad(lat1);
    double radLat2 = rad(lat2);
    double a = radLat1 - radLat2;
    double b = rad(lng1) - rad(lng2);
    double s = 2 *
        asin(sqrt(pow(sin(a / 2), 2) +
            cos(radLat1) * cos(radLat2) * pow(sin(b / 2), 2)));
    return s * 6378138.0;
  }

  double rad(double d) {
    return d * pi / 180.0;
  }

   _openMap(BuildContext context) async {
    if (await CustomUI.showPermissionSetting(
        context, PermissionGroup.location, I18n.of(context).open_location)) {
     return LocationPicker.pickLocation(
          context, 'AIzaSyAb9JNtW0BEZ_qLeDg87ZhvxSmZply-7hU',
          initialCenter: LatLng(UserData().latitude, UserData().longitude));


//      print('地图结果 ${result}');
//      return result;


    }
  }
}
