import 'package:flutter/material.dart';
import 'package:flutter_bmfbase/BaiduMap/bmfmap_base.dart';
import 'package:flutter_bmfmap/BaiduMap/bmfmap_map.dart';
import 'package:flutter_screenutil/screen_util.dart';
import 'package:hyzp_ybqx/components/commonFun.dart';
import 'package:hyzp_ybqx/components/hyxx_data_handle.dart';

import '../../../components/dioFun.dart';
import 'dwInfoDialog.dart';
import 'dwInfo_data.dart';

class BasicMap extends StatefulWidget {
  BasicMap({this.hyshlx = 'dwdt', this.title = "点位地图"});

  String hyshlx;
  String title;

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

class _BasicMapState extends State<BasicMap> {
  Size screenSize;
  BMFMapOptions mapOptions;
  BMFMapController myMapController;

  try_setState() {
    try {
      setState(() {});
    } catch (e) {
      print('setState(() {})异常：${e}');
    }
  }

  @override
  void initState() {
    super.initState();
    mapOptions = BMFMapOptions(
      //center: BMFCoordinate(39.965, 116.404),//北京市
      //30 116.395645038,39.9299857781 北京-北京市
      //center: BMFCoordinate(34.263161, 108.948024), //西安市
      /// 设置地图显示中心点坐标，必须是百度官方发布的百度地图-城市中心点坐标
      /// 为宜宾市翠屏白塔山： BMFCoordinate(104.644079, 28.77914)
      //center: BMFCoordinate(104.644079, 28.77914),  //宜宾市翠屏白塔山，无效，经纬度搞反了
      //52 104.633019062,28.7696747963 四川省-宜宾市翠屏

      ///Flutter百度地图采坑注意：
      // BMFCoordinate(this.latitude, this.longitude);
      // BMFCoordinate 构造方法参数是纬度在前、经度在后，latitude 纬度，longitude 经度
      // 注意：百度官方发布的城市中心点坐标是经度在前、纬度在后，必须对调才行，否则无法正确显示指定城市的地图
      // 比如：//52 104.633019062,28.7696747963 四川省-宜宾市翠屏
      // 必须将经纬度对调才行：center: BMFCoordinate(28.7696747963, 104.633019062),  //四川省-宜宾市翠屏
      //center: BMFCoordinate(28.7696747963, 104.633019062), //四川省-宜宾市翠屏
      //center: BMFCoordinate(28.77914, 104.644079),
      //宜宾市翠屏白塔山
      //宜宾市翠屏白塔山

      // 注意：百度官方发布的城市中心点坐标是经度在前、纬度在后，必须对调才行，否则无法正确显示指定城市的地图
      // BMFCoordinate BMFCoordinate(double latitude (纬度), double longitude (经度)) //中国领域一般经度大些
      // center: BMFCoordinate(28.77914, 104.644079), //宜宾市翠屏白塔山
      center: BMFCoordinate(center_latitude, center_longitude),
      // 不同区县的中心纬度、经度坐标不一样
      showMapPoi: _showMapPoi,
      //设定地图是否显示底图poi标注(不包含室内图标注)，默认true
      zoomLevel: g_zoomLevel,
      maxZoomLevel: g_zoomMax,
      minZoomLevel: g_zoomMin,
      mapPadding: BMFEdgeInsets(left: 30, top: 0, right: 30, bottom: 0),
      //showMapScaleBar: true,
    );

    iPage = 0;
    listDwspGetList2.clear();

    ///从接口 mapHyshlx[hyshlx]['api'] 获取第 iPage 页的列表数据，返回 list
    getPageList(theHyshlx: widget.hyshlx, bShowToast: false).then((value) async {
      //mapHyshlx[hyshlx]['api'];
      listDwspGetList2 = value;
      listDwinfoGetList2 = value;
      //try_setState();

      //按照用户选择的_selectedValue、_descending对listDwspGetList2进行排序，并延时更新

      // int len = listDwspGetList2.length;
      // for (int i = 0; i < len; i++) {
      //   getDwspUrl(index: listDwspGetList2[i]['id']).then((value) {
      //     listDwspGetList2[i]['dwsp_ok'] = true;
      //     if (value == '' || value == null) {
      //       listDwspGetList2[i]['dwsp_ok'] = false;
      //     }
      //     setState(() {});
      //   });
      // }
    });
    //为播放点位视频读取数据
    //在 Page1_Works 页面，获取 startGetStatisData() 时，便已经获取了 listDwinfoGetList2

    // ///从接口 mapHyshlx[hyshlx]['api'] 获取第 iPage 页的列表数据，返回 list
    // getPageList(theHyshlx: 'dwxx', bShowToast: false).then((value) async {
    //   //mapHyshlx[hyshlx]['api'];
    //   listDwspGetList2 = value;
    //
    //   //按_selectedValue排序，升序
    //   listDwspGetList2
    //       .sort((a, b) => (a[mapWzxxDataText['点位编号']]).compareTo(b[mapWzxxDataText['点位编号']]));
    // });
  }

  //设定地图是否显示底图poi标注(不包含室内图标注)，默认true
  bool _showMapPoi = true;

  /// 创建完成回调
  void onBMFMapCreated(BMFMapController controller) async {
    myMapController = controller;

    /// 设置地图状态改变完成后回调接口
    myMapController?.setMapStatusDidChangedCallback(callback: () {
      myMapController.getZoomLevel().then((zoomLevel) {
        print('Current zoomLevel = $zoomLevel');
        g_zoomLevel = zoomLevel; //缩放倍数

        getListBMFMarker().then((value) async {
          ///先清除地图上的所有Marker
          await myMapController?.removeMarkers(g_listBMFMarker);

          ///批量添加定位标记
          await myMapController?.addMarkers(g_listBMFMarker);

          ///批量添加文字标记，作为定位标记的说明文字
          for (var text in g_listBMFText) {
            //text.setMethodChannel(MethodChannel());
            await myMapController?.addText(text);
          }

          //加在此处无效
          //点击Marker时会回调BaiduMap.OnMarkerClickListener，监听器的实现方式示例如下：
          /// 地图marker点击回调
          //myMapController?.setMapClickedMarkerCallback(callback: _markerCallback);
        });
        setState(() {});
      });
    });

    /// 地图加载回调
    myMapController?.setMapDidLoadCallback(callback: () {
      print('mapDidLoad-地图加载完成');
    });

    ///批量添加定位标记
    getListBMFMarker().then((value) {
      myMapController?.addMarkers(g_listBMFMarker);

      ///批量添加文字标记，作为定位标记的说明文字
      for (var text in g_listBMFText) {
        myMapController?.addText(text);
      }

      ///1、底图标注 点击回调：
      // 点中底图标注后会回调此接口
      myMapController?.setMapOnClickedMapPoiCallback(callback: (BMFMapPoi mapPoi) async {
        print('mapPoi = ${mapPoi.toMap().toString()}');
        myMapController.getZoomLevel().then((value) {
          g_zoomLevel = value;
          print('myMapController.getZoomLevel() = ${value.toString()}');
        });
        //I/flutter (11895): mapPoi = {text: 森林小区, pt: {latitude: 28.765632464539106, longitude: 104.60481101089357}, uid: ea4cae6307501c5f4d2fdfe9}
        onMarkerClicked(mapPoi.pt);
      });

      ///2、底图空白处 点击回调
      // 点中底图空白处会回调此接口
      /// coordinate 经纬度
      myMapController?.setMapOnClickedMapBlankCallback(callback: (BMFCoordinate coordinate) {
        print('点击底图空白处响应：coordinate = ${coordinate.toMap().toString()}');
        myMapController.getZoomLevel().then((value) {
          g_zoomLevel = value;
          print('myMapController.getZoomLevel() = ${value.toString()}');
        });
        onMarkerClicked(coordinate);
      });

      //3、Marker 点击响应，点击文本标签没反应，加在此处有效
      //点击Marker时会回调BaiduMap.OnMarkerClickListener，监听器的实现方式示例如下：
      /// 地图marker点击回调
      myMapController?.setMapClickedMarkerCallback(callback: (String id, dynamic extra) async {
        myMapController.getZoomLevel().then((value) {
          g_zoomLevel = value;
          print('myMapController.getZoomLevel() = ${value.toString()}');
        });
        print('点击 Marker 标签响应：id = ${id}');
        //百度地图的脑残设计，需要在添加BMFMarker时自己保存ID
        //g_listBMFMarkerIDmap.add({marker.getId(): listDwinfo[i]["id"]});
        print('Marker的 标签响应：id = ${listDwinfoGetList2[g_map_BMFMarkerID_dwIndex[id]]["dwmc"]}');

        _markerCallback(id, 'test'); //响应用户点击
      });
    });
    //批量添加定位标记
  }

  Map mapBMFTextCoordinateList = {};

  //1、江北振兴大道	估算坐标区域
  // 左上角 coordinate = {latitude: 28.807221307340154, longitude: 104.60667948635371}
  // 右下角 coordinate = {latitude: 28.805069070677582, longitude: 104.62110627283919}
  // listMarkerCoordinate是包含13个Map点位标记的List，每个Map元素包括4个子元素，
  // 分别是左上角坐标（纬度 latitude，经度 longitude）、右下角坐标（纬度 latitude，经度 longitude）
  List listMarkerCoordinate1 = [
    {
      'topLatitude': 28.807221307340154,
      'leftLongitude': 104.60667948635371,
      'bottomLatitude': 28.805069070677582,
      'rightLongitude': 104.62110627283919
    }
  ];

  //12、大麦坝
  //左上角 coordinate = coordinate = {latitude: 28.8044360513459, longitude: 104.63110441316194}
  //右下角 coordinate = coordinate = {latitude: 28.803415299489192, longitude: 104.63598221207951}
  // listMarkerCoordinate是包含13个Map点位标记的List，每个Map元素包括4个子元素，
  // 分别是左上角坐标（纬度 latitude，经度 longitude）、右下角坐标（纬度 latitude，经度 longitude）
  //15倍放大时设置，地图放到18倍时，点击没有问题，
  //缩小到13倍时，不行了
  //15倍放大
  //左下角coordinate = {latitude: 28.79913436190729, longitude: 104.66847392236468}
  //左上角coordinate = {latitude: 28.806612039019615, longitude: 104.62731356391107}
  List listMarkerCoordinate = [
    {
      'topLatitude': 28.80778309701711,
      'leftLongitude': 104.63028695514814,
      'bottomLatitude': 28.79801859852449,
      'rightLongitude': 104.66974951618843
    }
  ];

  //以13倍放大时的数据设置
  //左下角coordinate = {latitude: 28.80399293550177, longitude: 104.63028695514814}
  //左上角coordinate = {latitude: 28.79801859852449, longitude: 104.66974951618843}

  // 中国在世界地图上的经纬度范围？  // 2019-04-14 · 把复杂的事情简单说给你听

  // top    北起黑龙江省漠河以北的黑龙江主航道的中心线 北纬 53°31′
  // bottom 南达南海南沙群岛的曾母内暗沙 北纬 4°15′
  // left   西起新容疆维吾尔自治区乌恰县以西的帕米尔高原 东经 73°
  // right  东至黑龙江省抚远县境内的黑龙江与乌苏里江汇合处 东经 135°。
  //
  // 中国位于地球的东半球北半部、亚欧大陆的东南部、亚洲的东部和中部、太平洋的西岸。

  int i = 0;

  //纬度 latitude，经度 longitude
  Future onMarkerClicked(BMFCoordinate coordinate) {
    //double scale = g_zoomLevel / 15;
    if (listMarkerCoordinate[i]['topLatitude'] > coordinate.latitude &&
        coordinate.latitude > listMarkerCoordinate[i]['bottomLatitude'] &&
        listMarkerCoordinate[i]['rightLongitude'] > coordinate.longitude &&
        coordinate.longitude > listMarkerCoordinate[i]['leftLongitude']) {
      _markerCallback('123', 'test');
    } //响应用户点击
  }

  bool isDoing = false;

  Future _markerCallback(String id, dynamic extra) async {
    if (isDoing) {
      print('正在处理中...，不能重复进入');
      return;
    }
    print('开始处理');
    print('mapClickedMarker--\n marker = $id');

    //已经能够弹出Flutter对话框。但只有点击 Marker 标签有反应，点击文本标签没反应。

    //百度地图的脑残设计，需要在添加BMFMarker时自己保存ID
    //g_listBMFMarkerIDmap.add({marker.getId(): listDwinfo[i]["id"]});
    int dwIndex = g_map_BMFMarkerID_dwIndex[id];
    print('Marker的 标签响应：id = ${listDwinfoGetList2[dwIndex]["dwmc"]}');

    getStatisData(statisType: 'zptj', ip: listDwinfoGetList2[dwIndex]['dwip'])
        .then((mapStatisData) async {
      // String title =
      //     listDwinfoGetList2[dwIndex]["id"].toString() + '、' + listDwinfoGetList2[dwIndex]["dwmc"];
      String title = (dwIndex + 1).toString() + '、' + listDwinfoGetList2[dwIndex]["dwmc"];

      List listCoordinate = listDwinfoGetList2[dwIndex]["dwzb"].trim().split('|');
      String content = listDwinfoGetList2[dwIndex]["dwms"] +
          '。\n经度：${listCoordinate[0]}\n纬度：${listCoordinate[1]}' +
          '\n今日抓拍：${mapStatisData['today']['total']}， 累计抓拍：${mapStatisData['all']}' +
          '\n运行状态：${listDwinfoGetList2[dwIndex]['dwzt']}';
      await Navigator.of(context)
          .push(
        PageRouteBuilder(
          opaque: false,
          pageBuilder: (context, animation, secondaryAnimation) =>
              dwInfoDialog(id: id, dwIndex: dwIndex, title: title, content: content),
        ),
      )
          .then((value) async {
        print('value = $value');
        if (value) {
          print('用户已确认，开始处理推送交警！');
          //return;
        } else {
          print('用户取消了推送交警操作');
        }
      });

      setState(() {
        // _markerID = id;
        // _action = "点击";
      });
      isDoing = false;
    });
  }

  double _widthBtn = 45;
  double _heightBtn = 45;
  double _edge = 16;

  @override
  Widget build(BuildContext context) {
    screenSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(ScreenUtil().setHeight(173)), // 设置appBar高度
        // 设置appBar高度
        child: AppBar(
          automaticallyImplyLeading: false,
          centerTitle: true,
          titleSpacing: 0.0,
          //设置title的左边距
          flexibleSpace: Container(
            //SizedBox(height: ScreenUtil().statusBarHeight), //显示顶部状态栏
            // SizedBox(height: ScreenUtil().setHeight(10)), //显示顶部状态栏
            padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight), //留出顶部状态栏高度
            child: Container(
              //height: ScreenUtil().setHeight(173),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  colors: [
                    Color.fromRGBO(12, 186, 156, 1),
                    Color.fromRGBO(39, 127, 235, 1),
                  ],
                ),
              ),
              // decoration: BoxDecoration(
              //   gradient: LinearGradient(colors: [
              //     Color(0xFF0018EB),
              //     Color(0xFF01C1D9),
              //   ], begin: Alignment.bottomCenter, end: Alignment.topCenter),
              // ),
            ),
          ),
          title: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              getIconAndTextButton(
                iconColor: Colors.white,
                iconData: Icons.chevron_left_outlined,
                onPress: () {
                  Navigator.pop(context);
                },
              ),
              Expanded(
                child: Text(widget.title + '（${g_zoomLevel}倍）',
                    style: TextStyle(color: Colors.white, fontSize: 20),
                    textAlign: TextAlign.center,
                    overflow: TextOverflow.ellipsis),
              ),
              SizedBox(width: 10),
            ],
          ),
          actions: <Widget>[
            Row(
              children: [
                //SizedBox(width: ScreenUtil().setWidth(45)),
                InkWell(
                  onTap: () {
                    //Navigator.pushNamed(context, '/registerFirst');
                    this.setState(() {
                      _showMapPoi = !_showMapPoi;
                      myMapController?.updateMapOptions(BMFMapOptions(showMapPoi: _showMapPoi));
                    });
                  },
                  child: Container(
                    alignment: Alignment(0, 0),
                    //width: 150,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text('标注：', style: TextStyle(fontSize: 20, color: Colors.white)),
                        Container(
                          alignment: Alignment(0, 0),
                          height: 25,
                          width: 25,
                          padding: EdgeInsets.only(top: ScreenUtil().setHeight(6)),
                          child: _showMapPoi
                              ? Icon(Icons.check_box, color: Colors.white)
                              : Icon(Icons.check_box_outline_blank, color: Colors.white),
                        ),
                        SizedBox(width: ScreenUtil().setWidth(65)),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
      body: Stack(
        children: <Widget>[
          Align(
            alignment: Alignment.center,
            child: Container(
              height: screenSize.height,
              width: screenSize.width,
              child: BMFMapWidget(
                onBMFMapCreated: (controller) {
                  onBMFMapCreated(controller);
                },
                mapOptions: mapOptions,
              ),
            ),
          ),
          Align(
            alignment: Alignment(1, 1),
            child: Padding(
              padding: EdgeInsets.only(bottom: 5, right: _edge),
              child: Container(
                width: _widthBtn,
                height: _heightBtn * 2 + 3,
                decoration: new BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(2.0)),
                  border: new Border.all(width: 1, color: Colors.blue),
                ),
                child: Column(
                  children: [
                    Container(
                      width: _widthBtn,
                      height: _heightBtn,
                      //color: Colors.white,
                      child: InkWell(
                        // child: Icon(Icons.my_location_outlined, color: Colors.black45),
                        child: Icon(Icons.add, color: g_zoomLevel < g_zoomMax ? Colors.blue : Colors.grey),
                        onTap: g_zoomLevel < g_zoomMax
                            ? () {
                                //放大按钮，缩放限制g_zoomMin-g_zoomMax
                                if (g_zoomLevel < g_zoomMax) {
                                  g_zoomLevel++;
                                  myMapController
                                      ?.updateMapOptions(BMFMapOptions(zoomLevel: g_zoomLevel));
                                }
                              }
                            : null,
                      ),
                    ),
                    Divider(height: 1.0, color: Colors.blue),
                    Container(
                      width: _widthBtn,
                      height: _heightBtn,
                      //color: Colors.white,
                      child: InkWell(
                        // child: Icon(Icons.my_location_outlined, color: Colors.black45),
                        child: Icon(Icons.horizontal_rule,
                            color: g_zoomLevel > g_zoomMin ? Colors.blue : Colors.grey),
                        onTap: g_zoomLevel > g_zoomMin
                            ? () {
                                //缩小按钮，缩放限制10-18
                                g_zoomLevel--;
                                myMapController
                                    ?.updateMapOptions(BMFMapOptions(zoomLevel: g_zoomLevel));
                              }
                            : null,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Align(
            alignment: Alignment(-1, 1),
            child: Padding(
              padding: EdgeInsets.only(bottom: 50, left: _edge),
              child: Container(
                decoration: new BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(2.0)),
                  border: new Border.all(width: 1, color: Colors.blue),
                ),
                width: _widthBtn,
                height: _heightBtn,
                //color: Colors.white,
                child: InkWell(
                  // child: Icon(Icons.my_location_outlined, color: Colors.black45),
                  // 没有
                  child: Icon(Icons.radio_button_checked_rounded,
                      color: g_zoomLevel == g_zoomLevel_default ? Colors.grey : Colors.blue),
                  onTap: () {
                    g_zoomLevel = g_zoomLevel_default;
                    //还原按钮，重新设置中心位置、缩放级别
                    //myMapController.setCenterCoordinate(coordinate, animated);
                    //没有myMapController.getCenterCoordinate，无法简单地获取当前中心坐标;
                    // myMapController?.updateMapOptions(
                    //     BMFMapOptions(center: BMFCoordinate(28.77914, 104.644079)));
                    myMapController?.updateMapOptions(BMFMapOptions(
                        center:
                            BMFCoordinate(center_latitude, center_longitude))); // 不同区县的中心纬度、经度坐标不一样
                    myMapController?.updateMapOptions(BMFMapOptions(zoomLevel: g_zoomLevel));
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
