import 'package:amos_iot_login_tpl/const/global_config.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/consts/Logger.dart';
import 'package:jcs_airport/consts/url_const.dart';
import 'package:jcs_airport/view/dispatch/event_bus.dart';
import 'package:jcs_airport/view/dispatch/h5_base_map.dart';
import 'package:webview_flutter/webview_flutter.dart';

///@Description     ChooseLocation
///@author          helinlin
///@create          2021-12-30 20:16
class ChooseLocation extends StatefulWidget {
  //经度
  double longitude;

  // 纬度
  double latitude;

  ChooseLocation(this.longitude, this.latitude);

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

class _ChooseLocationState extends State<ChooseLocation> {
  String h5Url;
  WebViewController webViewController;

  @override
  void initState() {
    super.initState();
    _initSPInfo();
    DispatchEvents.on((event) {
      if (event is EventData) {
        if (event.type == EventDataType.ChooseLocation) {
          widget.longitude = event.content['longitude'];
          widget.latitude = event.content['latitude'];
        }
      }
    }, DispatchTagNames.MAIN_MAP);
    Logger.warn('{longitude:${widget.longitude},latitude:${widget.latitude}');
  }

  @override
  void dispose() {
    super.dispose();
    DispatchEvents.cancel(DispatchTagNames.MAIN_MAP);
  }

  /// 初始化 SharedPreferences 数据
  Future<void> _initSPInfo() async {
    String _h5Url = await APIUrlManager.getH5Url();
    setState(() {
      h5Url = _h5Url ?? URLConst.MAP_H5_URL;
      h5Url += '?page=chooseLocation';
      if (widget.longitude != null) {
        h5Url += '&longitude=${widget.longitude}';
      }
      if (widget.latitude != null) {
        h5Url += '&latitude=${widget.latitude}';
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('位置选择'),
      ),
      body: Column(
        children: [
          Expanded(child: H5MapBase(h5Url: h5Url, onCreated: (wvc) => {webViewController = wvc})),
          Row(
            children: [
              Expanded(
                  child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 10),
                child: FlatButton(
                  onPressed: () {
                    Get.back(result: {'longitude': widget.longitude, 'latitude': widget.latitude});
                  },
                  child: const Text(
                    '确定',
                    style: TextStyle(color: Colors.white),
                  ),
                  color: Colors.blue,
                ),
              )),
            ],
          )
        ],
      ),
    );
  }
}
