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:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/common/user_db.dart';
import 'package:liftmanager/internal/repair/model/repair_list_entity.dart';
import 'package:liftmanager/internal/repair/repair_router.dart';
import 'package:liftmanager/internal/repair/widgets/time_axis.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/click_tel_item.dart';
import 'package:liftmanager/widgets/my_button.dart';
import 'package:oktoast/oktoast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

class RepairDetailPage extends StatefulWidget {
  RepairDetailPage(this.repairItem);

  RepairItem repairItem;

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

class RepairDetailPageState extends State<RepairDetailPage> {
  Map<String, Object> _locationResult;
  StreamSubscription<Map<String, Object>> _locationListener;
  AmapLocationFlutterPlugin _locationPlugin = new AmapLocationFlutterPlugin();

  int _currentStatus = -1;
  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 :');
        });
      });
    });
    getLocation();
    getRepairDetail();
    getHasRole();
  }

  bool noRole = true;
  getHasRole() async {
    var role = await User().getCompanyRole();
    if (role == Constant.RoleAdmin ||
        role == Constant.RoleRegion ||
        role == Constant.RoleWork) {
      noRole = false;
      setState(() {});
    }
  }

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

  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);
    }
  }

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

  void _callCallerTel(telNum) async {
    var url = 'tel:${telNum}';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  ///获取急修详情
  void getRepairDetail() {
    ApiService(context: context).repairDetail(widget.repairItem.id,
        onSuccess: (data) {
      if (data != null) {
        widget.repairItem = data;
        setState(() {});
      }
    }, onError: (code, msg) {
      showToast(msg);
    });
  }

  /// 选择时间
  Future<void> _selectTime() async {
    DatePicker.showDateTimePicker(context,
        showTitleActions: true, onChanged: (date) {}, onConfirm: (date) {
      if (_currentStatus == 1) {
        sendTaking("${date.toString().split(".")[0]}");
      } else if (_currentStatus == 2) {
        sendArrive("${date.toString().split(".")[0]}");
      }
    }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  ///接单时间
  void sendTaking(String time) {
    showLoading(context, "正在执行...");
    ApiService(context: context).repairTaking(widget.repairItem.id, time,
        onSuccess: (data) {
      dismissLoading(context);
      if (data != null && data) {
        widget.repairItem.takingTime = time;
        setState(() {});
      } else {}
    }, onError: (code, msg) {
      dismissLoading(context);
      toasts(msg);
    });
  }

  ///到达时间
  void sendArrive(String time) {
    if (currentAddress.length == 0) {
      showToast("位置获取失败");
      return;
    }
    showLoading(context, "正在执行...");

    ApiService(context: context).repairArrive(
        widget.repairItem.id, time, currentAddress, onSuccess: (data) {
      dismissLoading(context);
      if (data != null && data) {
        widget.repairItem.arriveTime = time;
        setState(() {});
      } else {}
    }, onError: (code, msg) {
      dismissLoading(context);
      toasts(msg);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //resizeToAvoidBottomPadding: false,
      appBar: const MyAppBar(
        centerTitle: "急修详情",
      ),
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: defaultTargetPlatform == TargetPlatform.iOS
                  ? FormKeyboardActions(child: _buildBody())
                  : SingleChildScrollView(child: _buildBody()),
            )
          ],
        ),
      ),
    );
  }

  _buildBody() {
    return Padding(
      padding: EdgeInsets.only(bottom: 30),
      child: Container(
          color: ThemeUtils.getBackgroundColor(context),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Offstage(
                  offstage: _currentStatus != 0,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.fromLTRB(15, 20, 15, 0),
                        color: Color(0xffF9FBFF),
                        // ThemeUtils.getTabsBg(context),
                        child: Row(
                          children: <Widget>[
                            Icon(
                                const IconData(0xe644, fontFamily: "Iconfont")),
                            SizedBox(
                              width: 10,
                            ),
                            // &#xe644;
                            Text(
                              "急修单已完成",
                              style: TextStyle(fontSize: 24),
                            )
                          ],
                        ),
                      ),
                      // Container(
                      //   margin: EdgeInsets.only(bottom: 8),
                      //   padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
                      //   decoration: BoxDecoration(
                      //     color: ThemeUtils.getTabsBg(context),
                      //   ),
                      //   child: Row(
                      //     mainAxisAlignment: MainAxisAlignment.start,
                      //     children: <Widget>[
                      //       Offstage(
                      //         offstage:noRole || widget.repairItem.status == 2 &&
                      //             widget.repairItem.hasEvaluate == 1,
                      //         child: FlatButton(
                      //           color: const Color(0xFFE1EAFA),
                      //           textColor: Colours.app_main,
                      //           child: const Text(
                      //             "评价",
                      //             style: TextStyle(fontSize: Dimens.font_sp14),
                      //           ),
                      //           onPressed: () {
                      //             NavigatorUtils.pushResult(context,
                      //                 "${RepairRouter.repairEvaluatePage}?islook=0&id=${widget.repairItem.id}",
                      //                 (res) {
                      //               if (res != null && res) {
                      //                 widget.repairItem.hasEvaluate = 1;
                      //                 getRepairDetail();
                      //               }
                      //             });
                      //           },
                      //         ),
                      //       ),
                      //       Gaps.hGap16,
                      //       FlatButton(
                      //         color: Colours.app_main,
                      //         textColor: Colors.white,
                      //         child: const Text(
                      //           "急修单",
                      //           style: TextStyle(fontSize: Dimens.font_sp14),
                      //         ),
                      //         onPressed: () {
                      //           RepairItem item = widget.repairItem;
                      //           String jsonString = convert.jsonEncode(item);
                      //           NavigatorUtils.push(context,
                      //               "${RepairRouter.repairOrderPage}?item=${Uri.encodeComponent(jsonString)}");
                      //         },
                      //       ),

                      //     ],
                      //   ),
                      // )
                    ],
                  )),
              // Offstage(
              //     offstage: widget.repairItem.hasEvaluate == 0,
              //     child: ClickItem(
              //       title: "评价信息",
              //       content: "",
              //       onTap: () {
              //         NavigatorUtils.pushResult(context,
              //             "${RepairRouter.repairEvaluatePage}?islook=1&id=${widget.repairItem.id}&service=${widget.repairItem.evaluation.serviceLevel}&star=${widget.repairItem.evaluation.starLevel}&advice=${Uri.encodeComponent(widget.repairItem.evaluation.advice)}&imgurl=${Uri.encodeComponent(widget.repairItem.evaluation.imgUrl)}",
              //                 (res) {
              //               if (res != null && res) {
              //                 widget.repairItem.hasEvaluate = 1;
              //                 getRepairDetail();
              //               }
              //             });
              //       },
              //     )),
              Gaps.vGap8,
              ClickItem(
                  title: "项目名称", content: "${widget.repairItem.projectName}"),
              ClickItem(
                  title: "电梯注册代码",
                  content: "${widget.repairItem.registrationCode}"),
              Offstage(
                offstage: widget.repairItem.callerName.length == 0,
                child: ClickTelItem(
                  title: "召修人",
                  content: "${widget.repairItem.callerName}",
                  onTap: () {
                    _callCallerTel("${widget.repairItem.callerTel}");
                  },
                ),
              ),
              ClickItem(
                  title: "故障原因",
                  content:
                      "${widget.repairItem.repairReason == 1 ? "停电" : widget.repairItem.repairReason == 2 ? "故障" : "其他"}"),
              ClickItem(
                  title: "是否关人",
                  content: "${widget.repairItem.isTrapped == 1 ? "是" : "否"}"),
              ClickItem(
                  title: "是否紧急",
                  content: "${widget.repairItem.isCritical == 1 ? "是" : "否"}"),
              ClickItem(
                  title: "故障描述",
                  content: "${widget.repairItem.callerFaultDescription}"),
              ClickTelItem(
                title: "急修负责人",
                content: "${widget.repairItem.workerName}",
                onTap: () {
                  _callCallerTel("${widget.repairItem.workerTel}");
                },
              ),
              Gaps.vGap8,
              ClickItem(title: "最新动态", content: ""),
              Column(
                children: timeAxis(),
              ),
              Offstage(
                  offstage:
                      _currentStatus == 0 || widget.repairItem.status >= 2,
                  child: Container(
                      color: ThemeUtils.getTabsBg(context),
                      child: Padding(
                        padding: const EdgeInsets.all(16),
                        child: MyButton(
                          fontSize: 14,
                          onPressed: () {
                            if (_currentStatus == 3) {
                              RepairItem item = widget.repairItem;
                              String jsonString = convert.jsonEncode(item);
                              NavigatorUtils.pushResult(context,
                                  "${RepairRouter.repairSafePage}?item=${Uri.encodeComponent(jsonString)}",
                                  (res) {
                                if (res != null && res) {
                                  getRepairDetail();
                                }
                              });
                            } else if (_currentStatus == 4) {
                              RepairItem item = widget.repairItem;
                              String jsonString = convert.jsonEncode(item);
                              NavigatorUtils.pushResult(context,
                                  "${RepairRouter.repairSubmitPage}?item=${Uri.encodeComponent(jsonString)}",
                                  (res) {
                                if (res != null && res) {
                                  getRepairDetail();
                                }
                              });
                            } else {
                              _selectTime();
                            }
                          },
                          text:
                              "${_currentStatus == 1 ? "接单" : _currentStatus == 2 ? "到达" : _currentStatus == 3 ? "安全确认并停梯" : "填写急修单"}",
                        ),
                      ))),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Expanded(
                    child: MyButton(
                      backColor: Colors.white,
                      borderColor: Colours.blue_app_main,
                      textColor: Colours.blue_app_main,
                      onPressed: () {
                        NavigatorUtils.pushResult(context,
                            "${RepairRouter.repairEvaluatePage}?islook=0&id=${widget.repairItem.id}",
                            (res) {
                          if (res != null && res) {
                            widget.repairItem.hasEvaluate = 1;
                            getRepairDetail();
                          }
                        });
                      },
                      text: "评价",
                    ),
                  ),
                  Expanded(
                    child: MyButton(
                      onPressed: () {
                        RepairItem item = widget.repairItem;
                        String jsonString = convert.jsonEncode(item);
                        NavigatorUtils.push(context,
                            "${RepairRouter.repairOrderPage}?item=${Uri.encodeComponent(jsonString)}");
                      },
                      text: "急修单",
                    ),
                  )
                ],
              )
            ],
          )),
    );
  }

  List<Widget> timeAxis() {
    List<Widget> list = [];
    _currentStatus = 0;
    list.add(LogisticsInformationItem(
        topColor: Colors.transparent,
        title: "报修时间",
        text: "${widget.repairItem.callerDate}"));
    list.add(LogisticsInformationItem(
        title: "派工时间", text: "${widget.repairItem.assignTime}"));
    if (widget.repairItem.takingTime.length == 0) {
      _currentStatus = 1;
      return list;
    }
    list.add(LogisticsInformationItem(
        title: "接单时间", text: "${widget.repairItem.takingTime}"));
    if (widget.repairItem.arriveTime.length == 0) {
      _currentStatus = 2;
      return list;
    }
    list.add(LogisticsInformationItem(
        title: "到达时间", text: "${widget.repairItem.arriveTime}"));
    if (widget.repairItem.stopDate.length == 0) {
      _currentStatus = 3;
      return list;
    }
    list.add(LogisticsInformationItem(
        title: "停梯时间", text: "${widget.repairItem.stopDate}"));
    if (widget.repairItem.recoveryDate.length == 0) {
      _currentStatus = 4;
      return list;
    }
    list.add(LogisticsInformationItem(
        bottomColor: Colors.transparent,
        title: "恢复时间",
        text: "${widget.repairItem.recoveryDate}"));
    return list;
  }
}
