/*
 * @Author       : WuWei
 * @LastEditors: wuwei
 * @Date         : 2021-08-17 15:05:36
 * @LastEditTime: 2024-01-15 11:02:07
 * @Description  : 巡逻、设备巡检、设备保养点位表单 store
 */
import 'dart:async';
import 'dart:io';
import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mobx/mobx.dart';
import 'package:task_package/src/impl/qrcode_impl.dart';
// import 'package:task_package/src/models/tak_operation_instruction.dart';
import 'package:task_package/src/models/task_operation_form.dart';
import 'package:task_package/src/models/task_operation_node_list.dart';
import 'package:task_package/src/pages/point_form/index.dart';
// import 'package:task_package/src/view_models/location_util_store.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
// import 'package:geolocator/geolocator.dart';
import 'dart:math' as math;
import '../models/task_operation_instruction_list.dart';
part 'point_form_store.g.dart';

const double X_PI = math.pi * 3000.0 / 180.0;
const double OFFSET = 0.00669342162296594323;
const double AXIS = 6378245.0;

// enum _PositionItemType {
//   log,
//   position,
// }

// class _TransformTmp {
//   double x, y;

//   _TransformTmp(this.x, this.y);
// }

// class _PositionItem {
//   _PositionItem(this.type, this.displayValue);

//   final _PositionItemType type;
//   final String displayValue;
// }

// ///百度坐标
class BdLatLng {
  double latitude;
  double longitude;
  BdLatLng({required this.latitude, required this.longitude});
}

class PointFormStore = _PointFormStore with _$PointFormStore;

abstract class _PointFormStore with Store, ChangeNotifier {
  ///上下文（请勿修改）
  final BuildContext context1;

  late Map<String, dynamic> routingArgs;
  _PointFormStore(this.context1) {
    routingArgs = (ModalRoute.of(context1)?.settings.arguments ??
            new Map<String, dynamic>()) as Map<String, dynamic>? ??
        {};
  }

  ///路由参数（请勿修改）
  PointFormPageArguments get arguments =>
      PointFormPageArguments.fromRouteArguments(context1);
  String? get id => arguments.id;
  String? get cid => arguments.cid;
  String? get type => arguments.type;
  String? get relationIds => arguments.relationIds;
  bool? get seqencing => arguments.seqencing ?? false;
  bool? get isEquipment => arguments.isEquipment ?? false;
  bool? get isDealAbnormalSolve => arguments.isDealAbnormalSolve ?? false;
  get detailData => arguments.detailData ?? null;
  get detailStatus => arguments.detailStatus ?? null;
  get routeList => arguments.route ?? null;
  get routeItem => arguments.routeItem ?? null;
  bool get isHistory => arguments.isHistory ?? false;

  GlobalKey infoKey = new GlobalKey();

  GlobalKey formKey = new GlobalKey();

  /// 位置信息
  // @observable
  // ObservableMap<String, Object>? locationResult;

  // StreamSubscription<Map<String, Object>>? locationListener;

  // final GeolocatorPlatform _geolocatorPlatform = GeolocatorPlatform.instance;
  // final List<_PositionItem> _positionItems = <_PositionItem>[];
  // StreamSubscription<Position>? _positionStreamSubscription;
  // StreamSubscription<ServiceStatus>? _serviceStatusStreamSubscription;
  // bool positionStreamStarted = false;

  /// 销毁
  // void destroy() {
  //   if (_positionStreamSubscription != null) {
  //     _positionStreamSubscription!.cancel();
  //     _positionStreamSubscription = null;
  //   }
  // }

  /// 初始化定位 采用持续定位 避免定位时间过长
  onInitLocation() async {
    // var locationStore = LocationUtilStore(context1);
    // // 初始化定位
    // final hasPermission = await locationStore.requestLocationPermission();
    // if (hasPermission != true) {
    //   final isHas = await locationStore.getLocationPermission();
    //   print(isHas);
    //   if (isHas) {
    //     _toggleServiceStatusStream();
    //   } else {
    //     /// 再次请求一遍
    //     final isHas = await locationStore.getLocationPermission();
    //     if (isHas) {
    //       _toggleServiceStatusStream();
    //     } else {
    //       final opened = await _geolocatorPlatform.openLocationSettings();
    //       if (opened == true) {
    //         _toggleServiceStatusStream();
    //       }
    //     }
    //   }
    // } else {
    //   print('kkkkkkkkkkkkkkkkkkkkkkkkkkkkk');
    //   _toggleServiceStatusStream();
    // }
  }

  // void _toggleServiceStatusStream() {
  //   if (_serviceStatusStreamSubscription == null) {
  //     final serviceStatusStream = _geolocatorPlatform.getServiceStatusStream();
  //     _serviceStatusStreamSubscription =
  //         serviceStatusStream.handleError((error) {
  //       _serviceStatusStreamSubscription?.cancel();
  //       _serviceStatusStreamSubscription = null;
  //     }).listen((serviceStatus) {
  //       String serviceStatusValue;
  //       if (serviceStatus == ServiceStatus.enabled) {
  //         if (positionStreamStarted) {
  //           _toggleListening();
  //         }
  //         serviceStatusValue = 'enabled';
  //       } else {
  //         if (_positionStreamSubscription != null) {
  //           _positionStreamSubscription?.cancel();
  //           _positionStreamSubscription = null;
  //           _updatePositionList(
  //               _PositionItemType.log, 'Position Stream has been canceled');
  //         }
  //         serviceStatusValue = 'disabled';
  //       }
  //       _updatePositionList(
  //         _PositionItemType.log,
  //         'Location service has been $serviceStatusValue',
  //       );
  //     });
  //   }
  // }

  // void _updatePositionList(_PositionItemType type, String displayValue) {
  //   _positionItems.add(_PositionItem(type, displayValue));
  // }

  // void _toggleListening() {
  //   if (_positionStreamSubscription == null) {
  //     final positionStream = _geolocatorPlatform.getPositionStream();
  //     _positionStreamSubscription = positionStream.handleError((error) {
  //       _positionStreamSubscription?.cancel();
  //       _positionStreamSubscription = null;
  //     }).listen((position) => _updatePositionList(
  //           _PositionItemType.position,
  //           position.toString(),
  //         ));
  //     _positionStreamSubscription?.pause();
  //   }

  //   if (_positionStreamSubscription == null) {
  //     return;
  //   }

  //   String statusDisplayValue;
  //   if (_positionStreamSubscription!.isPaused) {
  //     _positionStreamSubscription!.resume();
  //     statusDisplayValue = 'resumed';
  //   } else {
  //     _positionStreamSubscription!.pause();
  //     statusDisplayValue = 'paused';
  //   }

  //   _updatePositionList(
  //     _PositionItemType.log,
  //     'Listening for position updates $statusDisplayValue',
  //   );
  // }

  /// 作业标准内容弹框 已读标识
  @observable
  bool read = false;

  // onSetReadHidden() {
  //   setPlatformNodeRead();
  // }
  @action
  Future<void> setPlatformNodeRead(id) async {
    var res = await QrcodeServiceImpl.instance!.setPlatformNodeRead({
      'id': id,
    });
    if (res.data != null) {
      read = true;
    }
  }

  Map<String, String> repairPointType = {
    'patrolPoint': '巡逻点',
    'devicePoint': '设备',
    'deviceRoom': '设备间',
  };

  @observable
  bool isScan = false;
  @observable
  bool isShowBottom = false;

  @observable
  TaskOperationFormModel? detail;

  ///获取点位表单详情
  @action
  Future<void> onGetDetail() async {
    if (arguments.isHistory != true) {
      isShowBottom = true;
    }
    var res = await onHandleGetDetail(id, relationIds, cid);

    read = res?.data?.read ?? false;

    detail = res?.data ?? {};

    if (detail != null) {
      if (isHistory != true) {
        onGetInstructionList();
      }

      /// 去除下一个节点操作
      // onGetRoute();
    }

    initQrCodeData();
  }

  // 作业标准弹框
  onInitShowDialog() {
    return showGeneralDialog(
        context: WNavUtil.instance!.navigatorKey.currentContext!,
        barrierDismissible: false,
        barrierLabel: '',
        transitionDuration: Duration(milliseconds: 200),
        pageBuilder: (BuildContext context, Animation<double> animation,
            Animation<double> secondaryAnimation) {
          return StatefulBuilder(
            builder: (context, setState) {
              return Wisdom.row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  WorkDetailModalView(
                    instructionList: instructionListProp,
                    detail: detail,
                  ),
                ],
              );
            },
          );
        });
  }

  /// 跳转任务
  Future<void> toTask() async {
    await Get.toNamed(
      'task/detail',
      arguments: {
        'id': detail?.exPlatformId,
        'isChild': false,
      },
    );
  }

  Future<void> initQrCodeData() async {
    /// 未完成的节点任务才需要定位
    if (detail?.status == 'unFinished') {
      onInitLocation();
    }

    /// 未关联二维码节点可直接执行表单 无需扫码
    if ((type != null && detail?.status == 'unFinished') ||
        (detail?.isRelationQrCode == false && detail?.status == 'unFinished') ||
        detail?.status == 'finished') {
      await onGetFormList(detail?.formData);
    }
  }

  /// 填写表单详情
  /// 任务id，关联ids，任务节点id
  Future onHandleGetDetail(taskid, relationIds, cid) async {
    if (cid != null) {
      return await QrcodeServiceImpl.instance!.getOperationDetail({'id': cid});
    } else {
      /// 2024.01.05 任务节点id为空时使用任务id跟关联ids请求
      return await QrcodeServiceImpl.instance!.getTaskOperationDetail({
        'exPlatformId': taskid,
        'relationIds': relationIds,
      });
    }
  }

  /// 任务路线
  @observable
  dynamic routeListdata;

  /// 任务路线
  Future<void> onGetRoute() async {
    var res = await QrcodeServiceImpl.instance!.getOperationNodeList({
      'excutivePlatformId': id,
    });
    routeListdata = res.data ?? TaskOperationNodeList();
  }

  /// 获取表单答案
  @observable
  ObservableList formDetailList = ObservableList.of([]);
  @action
  Future<void> onGetFormDetail() async {
    var res = await QrcodeServiceImpl.instance!.getOperationNodeDetail({
      'excutivePlatformLinkId': detail?.id,
    });
    if (res.data != null) {
      formDetailList = ObservableList.of(res.data?.list ?? []);
      if (isDealAbnormalSolve == true) {
        setAbnormalItemList();
      }
    }
  }

  /// 过滤表单异常项
  @observable
  ObservableList abnormalItemList = ObservableList.of([]);
  @action
  setAbnormalItemList() {
    for (var index in formList.asMap().keys) {
      if (formDetailList[index] != null) {
        formList[index].answer = formDetailList[index];
      }
    }
    abnormalItemList = ObservableList.of(formList.where((item) =>
        item.answer != null &&
        item.answer.resultAbnormal == true &&
        item.answer.status == 'untreated'));
    if (arguments.isHistory == true &&
        (isDealAbnormalSolve == true && abnormalItemList.length > 0)) {
      isShowBottom = true;
    }
  }

  /// 跳转添加任务
  toCreateTaskByAbnormal(item) async {
    final answer = item.answer.workStandardRecord;
    final answerNames = item.workStandardExtends
        .where((e) => answer.contains(e['id']) == true)
        .map((e) => e['content']);
    final res = await Navigator.pushNamed(
      context1,
      'task/edit',
      arguments: {
        'id': null,
        'pid': detailData.id,
        'pData': detailData?.toJson(),
        'isChildAdd': false,
        'isAbnormalAdd': true,
        'operationRecordAnswerId': item.answer.operationRecordAnswerId,
        'data': {
          'title': routeItem?.nodeData['communityName'] +
              ' - ' +
              routeItem?.relationName,
          'content': item.title + ' - ' + answerNames.join('/'),
        }
      },
    );

    /// 异常项创建任务成功
    if (res is bool && res) {
      abnormalItemList =
          ObservableList.of(abnormalItemList.where((e) => item.id != e.id));
      if (abnormalItemList.length == 0) {
        Navigator.pop(context1);
      }
      WisStorageUtil.set(
          key: 'abnormal_list_refresh', data: abnormalItemList.length == 0);
    }
  }

  /// 预览图片
  void onShowImage(image) {
    List<ImageProvider> images = [];
    images.add(CachedNetworkImageProvider(AppParseUtil.image(image)));
    WisPhotoViewUtil.show(images, 0);
  }

  @observable
  ObservableList formList = ObservableList.of([]);
  // TaskOperationStandard formList;
  @observable
  ObservableList formValueList = ObservableList.of([]);

  /// 作业标准表单列表
  @action
  Future<void> onGetFormList(ids) async {
    var res = await QrcodeServiceImpl.instance!.getOperationStandardList({
      'ids': ids,
    });
    formList = ObservableList.of(res.data ?? []);
    notifyListeners();
    if (res.data != null && res.data!.length > 0) {
      /// 节点完成时
      if (detail?.status == 'finished') {
        await onGetFormDetail();
      } else {
        for (num i = 0; i < res.data!.length; i++) {
          formValueList.add(res.data![i as int].illustrate == true
              ? {
                  'workStandardId': res.data![i].id,
                  'workStandardRecord': null,
                  'resultAbnormal': false,
                  'remark': null,
                  'imgs': [],
                }
              : {
                  'workStandardId': res.data![i].id,
                  'workStandardRecord': null,
                  'resultAbnormal': false,
                  'imgs': [],
                });
        }
      }
    }
  }

  /// 表单值
  @action
  onSetFormPrs(index, value, isErr, {bool isImg = false}) {
    formValueList[index]['workStandardRecord'] = null;
    formValueList[index]['workStandardRecord'] = value;
    print(formValueList[index]['workStandardRecord']);
    print(value);
    formValueList[index]['resultAbnormal'] = isErr;
    formValueList = formValueList;
    notifyListeners();
    print(formValueList);
  }

  @action
  onSetList(list) {
    formValueList = list;
  }

  /// 异常项说明
  @action
  onSetFormPrsRemark(index, remark) {
    formValueList[index]['remark'] = '';
    formValueList[index]['remark'] = remark;
  }

  ///选择上传图片
  @action
  Future<void> onSelectedImg(List<FileEntity> files, index) async {
    // await onInitPicLocation(files, type, index);
    print(formList[index]?.workStandardExtends[0]['mostUploadCount']);
    print(files);
    onSetFormPrs(index, files, formValueList[index]['resultAbnormal']);
    notifyListeners();
  }

  // @action
  // Future<void> onInitPicLocation(
  //     List<FileEntity> files, String? type, index) async {
  //   WLoadingUtil.show();
  //   final futures = files.map((e) => onPostImg(e.file!)).toList();
  //   final pic = await Future.wait(futures);
  //   List imageArr = formValueList[index]['workStandardRecord'] ?? [];
  //   List imageArr2 = formValueList[index]['imgs'] ?? [];
  //   imageArr.addAll(pic.map((e) => e).toList());
  //   imageArr2.addAll(pic.map((e) => e['id']).toList());
  //   formValueList[index]['imgs'] = imageArr2;
  //   formValueList = formValueList;
  //   onSetFormPrs(index, imageArr, formValueList[index]['resultAbnormal']);
  //   notifyListeners();
  //   WLoadingUtil.hide();
  // }

  Future onUploadImgs(index) async {
    WLoadingUtil.showInfo(WisText('图片上传中~马上就好~', color: Colors.white));
    final files = formValueList[index]['workStandardRecord'] ?? [];
    List<Future<UploadImgModel?>> futures = [];
    for (final image in files) {
      futures.add(GlobalApi.postUploadImageObject2(image.file!));
    }
    final pics = await Future.wait(futures);
    List imageArr2 = [];
    pics.forEach((pic) {
      if (pic != null) {
        imageArr2.add(pic.id);
      }
    });

    formValueList[index]['imgs'] = imageArr2;
    formValueList = formValueList;
    notifyListeners();
    WLoadingUtil.hide();
  }

  /// 上传照片
  Future<UploadImgModel?> onPostImg(File file) async {
    return await GlobalApi.postUploadImageObject2(file);
  }

  // GlobalKey wmglkey = new GlobalKey();

  /// 添加水印
  // @action
  // Future<File?> addWaterMark(File file) async {
  //   /// 水印widget 转图片
  //   if (currentAddress != null) {
  //     var tempMark = await (capturePng(wmglkey) as FutureOr<Uint8List>);

  //     /// 水印
  //     ui.Image tempMarkImg = ui.decodeImage(tempMark)!;

  //     /// 照片
  //     ui.Image fileImg = ui.decodeImage(file.readAsBytesSync())!;

  //     /// 照片上加上水印
  //     ui.Image img = ui.drawImage(fileImg, tempMarkImg);
  //     List<int> wmImage = ui.encodeJpg(img);
  //     file.writeAsBytesSync(wmImage);
  //     return file;
  //   }
  //   return null;
  // }

  // 当前地址
  @observable
  String? currentAddress;
  @action
  void onSetCurrentAddr(String? addr) {
    currentAddress = addr;
  }

  // @observable
  // Position? currentLocation;
  // @action
  // Future<void> onSetCurrentLocation() async {
  //   Position res = await _geolocatorPlatform.getCurrentPosition(
  //       locationSettings: LocationSettings(
  //     accuracy: LocationAccuracy.best,
  //   ));
  //   currentLocation = res;
  // }

  ///表单删除图片
  @action
  onImageRemoveAt(itemIndex, index) {
    print(formValueList[itemIndex]['workStandardRecord']);
    formValueList[itemIndex]['workStandardRecord'].removeAt(index);
    formValueList[itemIndex]['imgs'] = [];
    formValueList = formValueList;
    notifyListeners();
  }

  @observable
  ObservableList instructionList = ObservableList.of([]);

  List<TaskOperationInstructionList> instructionListProp = [];

  /// 作业指导列表
  @action
  Future<void> onGetInstructionList() async {
    if (detail?.id == null) {
      WToastUtil.show('任务节点id不能为空');
      return;
    }
    var res = await QrcodeServiceImpl.instance!.getOperationInstructionList({
      // 'relationId': detail?.relationId,
      // 'relationType': detail?.relationType,
      // 'type': detail?.type,
      'platformNodeId': detail?.id,
    });
    instructionList = ObservableList.of(res.data ?? []);
    instructionListProp = res.data ?? [];

    if (read == false && instructionList.length > 0) {
      onInitShowDialog();
    }
  }

  /// 扫描点位二维码获取表单
  /// @excutivePlatformLinkId 任务环节id
  /// @scene 场景值
  Future onScanQRcode() async {
    final url = await WisScanUtil.instance.cameraScan(
      gallery: false,
    );
    if (url != null) {
      ///请求获取类型
      ///获取[jump]  根据[jump]映射[_route]路由
      WLoadingUtil.show();
      var json = await HttpUtil.instance.get(
        '/app/admin/qrCode/sweepCode',
        queryParameters: {
          'url': url,
          'type': 'smallEntrance',
          'communityId': detail?.nodeData?.communityId,
          'excutivePlatformLinkId': detail?.id,
        },
      );
      WLoadingUtil.hide();
      final data = ResModel<SceneScanModel>(
        json: json.data,
        to: (v) => v.toJson(),
        from: (v) => SceneScanModel.fromJson(v),
      ).data;
      if (data?.sceneValue != null) {
        await onGetFormList(data?.sceneValue);
      }
    }
  }

  /// 查看作业指导列表
  toWorkInstructionsList() async {
    await Navigator.pushNamed(
      context1,
      'task/work_instructions_list',
      arguments: {
        'platformNodeId': detail?.id,
        // 'relationId': detail?.relationId,
        // 'relationType': detail?.relationType,
        // 'type': detail?.type,
      },
    );
  }

  /// 查看作业指导
  toWorkInstructionsDetail() async {
    await Navigator.pushNamed(
      context1,
      'task/work_instructions_detail',
      arguments: {
        'id': instructionList[0].id,
      },
    );
  }

  /// 校验表单必填项目
  Future<bool> onHandleValidateForm() async {
    var count = 0;
    for (var i = 0; i < formList.length; i++) {
      if (formList[i]?.required == true &&
          (formValueList[i]['workStandardRecord'] == '' ||
              formValueList[i]['workStandardRecord'] == null ||
              (formValueList[i]['workStandardRecord'] is List &&
                  formValueList[i]['workStandardRecord'].length == 0))) {
        count += 1;
        WToastUtil.show('请完成带红色*必填项');
        break;
      }
      if (formList[i]?.type == 'text' &&
          formList[i]?.workStandardExtends[0]['inputRestrictionType'] ==
              'number' &&
          formValueList[i]['workStandardRecord'] != '' &&
          formValueList[i]['workStandardRecord'] != null &&
          onCheckInput(
                  formList[i], formValueList[i]['workStandardRecord'], i) ==
              false) {
        count = count + 1;
        break;
      }
      print(formValueList[i]['workStandardRecord']);
      if (formList[i]?.type == 'img' &&
          formValueList[i]['workStandardRecord'] != '' &&
          formValueList[i]['workStandardRecord'] != null &&
          (formList[i]?.workStandardExtends[0]['leastUploadCount'] != null &&
              formList[i]?.workStandardExtends[0]['leastUploadCount'] > 0 &&
              formList[i]?.workStandardExtends[0]['leastUploadCount'] >
                  formValueList[i]['workStandardRecord'].length)) {
        count += 1;
        WToastUtil.show(
            '请在${formList[i]?.title}上传至少${formList[i]?.workStandardExtends[0]['leastUploadCount']}张图片');
        break;
      }
    }
    return count == 0 ? true : false;
  }

  /// 校验多选的异常项
  bool onCheckErr(workExtends, value) {
    int count = 0;
    value.forEach((element) {
      if (workExtends[(workExtends
                  ?.indexWhere((extendsItem) => extendsItem['id'] == element))]
              ['exceptionItem'] ==
          true) {
        count += 1;
      }
    });
    return count > 0;
  }

  /// 校验表单的异常项
  int onCheckFormErr() {
    int count = 0;
    for (var i = 0; i < formValueList.length; i++) {
      if (formValueList[i]['resultAbnormal'] == true) {
        count += 1;
      }
    }

    return count;
  }

  /// 校验数字输入是否异常
  bool onCheckInputErr(item, value) {
    if (value == null || value == '') {
      return false;
    }
    if (item?.workStandardExtends[0]['normalRangeMinValue'] != null &&
        int.parse(value) <
            item?.workStandardExtends[0]['normalRangeMinValue']) {
      return true;
    }

    if (item?.workStandardExtends[0]['normalRangeMaxValue'] != null &&
        int.parse(value) >
            item?.workStandardExtends[0]['normalRangeMaxValue']) {
      return true;
    }

    return false;
  }

  /// 校验数字输入
  bool onCheckInput(item, value, index) {
    if (value == null || value == '') {
      return false;
    }
    if (item?.workStandardExtends[0]['minValue'] != null &&
        (int.parse(value) < item?.workStandardExtends[0]['minValue'])) {
      WToastUtil.show(
          '第${index + 1}项，请输入大于等于${item?.workStandardExtends[0]['minValue']}的数');
      return false;
    }

    if (item?.workStandardExtends[0]['maxValue'] != null &&
        (int.parse(value) > item?.workStandardExtends[0]['maxValue'])) {
      WToastUtil.show(
          '第${index + 1}项，请输入小于等于${item?.workStandardExtends[0]['maxValue']}的数');
      return false;
    }
    return true;
  }

  /// 上传表单内所有图片
  Future onHandleUplodAllImage() async {
    for (var i = 0; i < formList.length; i++) {
      if (formList[i]?.type == 'img' &&
          formValueList[i]['workStandardRecord'] != '' &&
          formValueList[i]['workStandardRecord'] != null &&
          formValueList[i]['workStandardRecord'].length > 0) {
        await onUploadImgs(i);
      }
    }
  }

  Future onCheckUplodImage() async {
    for (var i = 0; i < formList.length; i++) {
      if (formList[i]?.type == 'img' &&
          formValueList[i]['workStandardRecord'] != '' &&
          formValueList[i]['workStandardRecord'] != null &&
          formValueList[i]['workStandardRecord'].length > 0 &&
          (formValueList[i]['workStandardRecord'].length >
              formValueList[i]['imgs'].length)) {
        showDialog(
          context: context1,
          builder: (_) {
            return Wisdom(
                child: WisDialog(
              title: WisText('有图片尚未上传成功~'),
              insetPadding: EdgeInsets.symmetric(vertical: 0),
              content: Wisdom.column(
                height: 250.pt,
                width: 200.pt,
                color: Colors.white,
                padding: EdgeInsets.symmetric(vertical: 20.pt),
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Wisdom.column(
                    children: [
                      WisText(
                        '1、检查您所在的区域是否有良好的移动网络覆盖，有时在电梯、山区、地下室、或偏远地区，信号可能较弱。',
                        color: Colors.grey,
                        size: 15.pt,
                      ),
                      WisText(
                        '2、尝试移动到开阔的区域以改善信号质量，重新提交表单。',
                        color: Colors.grey,
                        size: 15.pt,
                      ),
                    ],
                  ),
                  // WisButton(
                  //   constraints:
                  //       BoxConstraints(minHeight: 44.pt, minWidth: 267.pt),
                  //   child: WisText('重新上传'),
                  //   onPressed: () => onHandleUplodAllImage(),
                  // )
                ],
              ),
            ));
          },
        );
      }
    }
  }

  /// 表单提交
  @action
  Future<void> onHandleSubmit() async {
    var res = await onHandleValidateForm();
    if (!res) {
      return;
    }

    await onHandleUplodAllImage();
    await onCheckUplodImage();

    int errCount = onCheckFormErr();

    /// 校验异常项
    if (errCount == 0) {
      onPostPointForm();
    } else {
      /// 有异常项 弹出提醒
      bool? confirm = await WModalUtil.showSync(
        '提交的任务中有$errCount个异常项，确认当前要提交吗？',
        title: '提交提醒',
      );
      if (confirm!) {
        onPostPointForm();
      }
    }
  }

  /// 提交点位表单
  Future<void> onPostPointForm() async {
    List tempList = [];
    // await onSetCurrentLocation();
    formValueList.forEach((element) => tempList.add(element));

    tempList.forEach((element) {
      if (element['workStandardRecord'] != null &&
          element['workStandardRecord'] is List) {
        element['workStandardRecord'] =
            element['imgs'] != null && element['imgs'].length > 0
                ? element['imgs'].join(',')
                : (element['workStandardRecord'] is List &&
                        element['workStandardRecord'].length > 0)
                    ? element['workStandardRecord'].join(',')
                    : null;
      }
      element.remove('imgs');
    });

    // if (currentLocation?.longitude == null ||
    //     currentLocation?.latitude == null) {
    //   return;
    // }

    // BdLatLng bdPosition = bdEncrypt(
    //     longitude: currentLocation?.longitude,
    //     latitude: currentLocation?.latitude);
    // BdLatLng res = tobd(currentLocation?.longitude, currentLocation?.latitude);

    late Map params = {
      'id': detail!.id,
      // 'longitude': currentLocation?.longitude,
      // 'latitude': currentLocation?.latitude,
      'workStandards': tempList,
    };

    print(params);

    try {
      WLoadingUtil.showInfo(WisText(
        '表单提交中~马上就好~',
        color: Colors.white,
      ));
      var res = await QrcodeServiceImpl.instance!.postOperationForm(params);
      if (res == 1) {
        WToastUtil.show('提交表单成功！');
        // destroy();
        onGetDetail();
      } else {
        WLoadingUtil.hide();
      }
    } finally {
      WLoadingUtil.hide();
    }
  }

  dynamic nextItem;

  /// 下一个任务节点 （已删除）

  /// 设备报修
  toRepair() async {
    await Navigator.pushNamed(context1, 'task/edit', arguments: {
      'id': null,
      'isChildAdd': false,
    });
  }
}

class SceneScanModel {
  String? entCode;
  String? jump;
  String? sceneValue;

  SceneScanModel({
    this.entCode,
    this.jump,
    this.sceneValue,
  });

  SceneScanModel.fromJson(json) {
    Map<String, dynamic> map = Map.from(json ?? {});

    entCode = map['entCode'];
    jump = map['jump'];
    sceneValue = map['sceneValue'];
  }

  Map<String, dynamic> toJson() {
    Map<String, dynamic> json = Map<String, dynamic>();

    json['entCode'] = this.entCode;
    json['jump'] = this.jump;
    json['sceneValue'] = this.sceneValue;

    return json;
  }
}
