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

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/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:liftmanager/internal/maintenance/maintenance_router.dart';
import 'package:liftmanager/internal/maintenance/model/maintenance_list_entity.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:liftmanager/widgets/click_item.dart';
import 'package:liftmanager/widgets/my_button.dart';
import 'package:liftmanager/widgets/radio_item.dart';
import 'package:permission_handler/permission_handler.dart';

class MaintenanceSafePage extends StatefulWidget {
  MaintenanceSafePage(this.item);

  MaintenanceListItem item;

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

class MaintenanceSafePageState extends State<MaintenanceSafePage> {
  List<String> groupValue = ["", "", "", "", "", ""];

  Map<String, Object> _locationResult;
  StreamSubscription<Map<String, Object>> _locationListener;
  AmapLocationFlutterPlugin _locationPlugin = new AmapLocationFlutterPlugin();
  LatLng latLng = LatLng(0, 0);
  String currentAddress = "";
  @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('key:$key :');
          print('value:$value :');
        });
      });
    });
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      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 dispose() {
    if (null != _locationListener) {
      _locationListener.cancel();
    }

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

  ///全选
  _allSelected() {
    groupValue = ["1", "1", "1", "1", "1", "1"];
    setState(() {});
  }

  ///确认
  _stopAndSafe() async {
//    if (_location == null) {
//      toasts("正在获取定位信息,请稍后");
//      return;
//    }
    int isRegular = 0;
    int isRepair = 0;
    if (DateTime.parse(widget.item.planDate).isAfter(DateTime.now())) {
      isRegular = 1;
    }

    if (widget.item.status == "-1") {
      isRepair = 1;
    }

//    String address = await _location.address;
//    print("${latlng.longitude}");
//    print("${latlng.latitude}");
    showLoading(context, "正在执行...");
    ApiService(context: context).maintenanceRecordAdd(
        widget.item.planId,
        widget.item.workerId,
        widget.item.liftId,
        widget.item.liftType,
        widget.item.projectId,
        widget.item.maintenanceType,
        groupValue.toString().substring(1, groupValue.toString().length - 1),
        "${latLng.longitude},${latLng.latitude}",
        currentAddress,
        isRegular,
        isRepair, onSuccess: (data) {
      dismissLoading(context);
      if (data != null) {
        widget.item.recordId = data;

        String mType = "1";

        if (widget.item.maintenanceType == "6" ||
            widget.item.maintenanceType == "18") {
          mType = "2";
        } else if (widget.item.maintenanceType == "12") {
          mType = "3";
        } else if (widget.item.maintenanceType == "24") {
          mType = "4";
        }
        widget.item.maintenanceType = mType;
        String jsonString = convert.jsonEncode(widget.item);

        NavigatorUtils.pushResult(context,
            "${MaintenanceRouter.maintenanceSubmit}?item=${Uri.encodeComponent(jsonString)}",
            (res) {
              NavigatorUtils.goBackWithParams(context, true);
          print(res);
        });
      }
    }, onError: (code, msg) {
      dismissLoading(context);
      toasts(msg);
    });
  }

  ///获取位置信息
  getLocation() async {

    if (await requestPermission()) {
      if (null != _locationPlugin) {
        ///开始定位之前设置定位参数
        _setLocationOption();
        _locationPlugin.startLocation();
      }
    }
  }

  ///获取定位权限
  Future<bool> requestPermission() async {
    final permissions = await PermissionHandler()
        .requestPermissions([PermissionGroup.location]);
    if (permissions[PermissionGroup.location] == PermissionStatus.granted) {
      return true;
    } else {
      toasts('需要定位权限!');
      return false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        //resizeToAvoidBottomPadding: false,
        appBar: const MyAppBar(
          centerTitle: "安全确认",
        ),
        body: SafeArea(
          child: Container(
            color: ThemeUtils.getBackgroundColor(context),
            child: Column(
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: defaultTargetPlatform == TargetPlatform.iOS
                      ? FormKeyboardActions(child: _buildBody())
                      : SingleChildScrollView(child: _buildBody()),
                ),
                Container(
//                    color: Colours.bg_color,
                    child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: MyButton(
                    fontSize: 14,
                    onPressed: () {
                      _stopAndSafe();
                    },
                    text: "确定",
                  ),
                ))
              ],
            ),
          ),
        ));
  }

  _buildBody() {
    return Padding(
      padding: EdgeInsets.only(bottom: 30),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          ClickItem(
              title: "电梯位置",
              hintText: "",
              content: "${widget.item.devicePosition}"),
          Container(
              padding: EdgeInsets.only(left: 15, right: 15),
              height: 32.5,
              child: Row(
                children: <Widget>[
                  Expanded(
                      flex: 1,
                      child: Text(
                        "安全防护确认",
                        style: TextStyle(
                            fontSize: 12, color: Colours.dark_text_gray),
                      )),
                  GestureDetector(
                      onTap: _allSelected,
                      child: Text(
                        "全选",
                        style: TextStyle(fontSize: 12, color: Colours.app_main),
                      )),
                ],
              )),
          RadioItem(
              title: "用电安全",
              value: "1",
              groupValue: groupValue[0],
              onTap: () {
                groupValue[0] = groupValue[0] == "1" ? "0" : "1";
                setState(() {});
              }),
          RadioItem(
              title: "护栏",
              value: "1",
              groupValue: groupValue[1],
              onTap: () {
                groupValue[1] = groupValue[1] == "1" ? "0" : "1";
                setState(() {});
              }),
          RadioItem(
              title: "手套",
              value: "1",
              groupValue: groupValue[2],
              onTap: () {
                groupValue[2] = groupValue[2] == "1" ? "0" : "1";
                setState(() {});
              }),
          RadioItem(
              title: "安全帽",
              value: "1",
              groupValue: groupValue[3],
              onTap: () {
                groupValue[3] = groupValue[3] == "1" ? "0" : "1";
                setState(() {});
              }),
          RadioItem(
              title: "电器防护",
              value: "1",
              groupValue: groupValue[4],
              onTap: () {
                groupValue[4] = groupValue[4] == "1" ? "0" : "1";
                setState(() {});
              }),
          RadioItem(
              title: "照明",
              value: "1",
              groupValue: groupValue[5],
              onTap: () {
                groupValue[5] = groupValue[5] == "1" ? "0" : "1";
                setState(() {});
              }),
          Container(
              padding: EdgeInsets.only(left: 15, right: 15),
              height: 32.5,
              child: Row(
                children: <Widget>[
                  Expanded(
                      flex: 1,
                      child: Text(
                        "请对已安全防护选项进行勾选，确保已做好安全防护工作",
                        style: TextStyle(fontSize: 12, color: Colours.app_main),
                      ))
                ],
              )),
        ],
      ),
    );
  }
}
