Untitled

 avatar
unknown
plain_text
a year ago
7.5 kB
6
Indexable
Future<void> updateLoc() async {
    final currentLocation = await Geolocator.getCurrentPosition();
    if (currentLocation != null) {
      locationC.latLng.value = LatLng(
        currentLocation.latitude,
        currentLocation.longitude,
      );
    }
  }

  Future<bool> shoutValidationCheck() async {
    final location = Location();
    bool isServiceEnable = false;

    if (await location.serviceEnabled()) {
      updateLoc();
      isServiceEnable = true;
    } else if (await location.requestService()) {
      updateLoc();
      isServiceEnable = true;
    }
    return isServiceEnable;
  }

  Future<void> addShout({
    required String subcategoryId,
    required String? categoryName,
    required String? categoryNameEn,
    required String subcategoryName,
    required bool broadcastAllowed,
    required String attentionType,
  }) async {
    // var list = [];
    isSubmit.value = true;
    try {
      if (await shoutValidationCheck()) {
        // var shoutData = Hive.box('shoutData');
        final username = Get.put(UserController()).username;
        // final selectedAgency = Get.put(AgencyController()).selectedAgency;

        final List<MultipartFile> attachments = [];
        final List<Uint8List> offlineAttachments = [];

        for (var img in imagefiles) {
          final fileName = getFileName(path: img.path);
          final imgFile = await MultipartFile.fromFile(
            img.path,
            filename: '${getUniqeId()}$fileName',
          );

          attachments.add(imgFile);

          offlineAttachments.add(await img.readAsBytes());

          // kLog('attachment length: ${attachments.length}');
        }
        Map<String, dynamic> bodyData = {
          "apiKey": ApiEndpoint.SHOUT_API_KEY,
          "appCode": ApiEndpoint.SHOUT_APP_CODE,
          "subcategoryIds": subcategoryId,
          "categoryName": categoryNameEn ?? 'N/A',
          "subcategoryName": subcategoryName,
          "broadcastAllowed": broadcastAllowed,
          if (attentionType == 'Dropdown')
            "agencyIds": selectedAttentionDropdown.value != null ? selectedAttentionDropdown.value?.agencyId : null,
          if (attentionType != 'Dropdown')
            "agencyIds": selectedAttentionDropdown.value != null ? selectedAttentionDropdown.value?.agencyId : null,
          if (attentionType == 'Dropdown')
            "agencyName": selectedAttentionDropdown.value != null ? selectedAttentionDropdown.value?.agencyName : null,
          if (attentionType != 'Dropdown')
            "agencyName": selectedAttentionDropdown.value != null ? selectedAttentionDropdown.value?.agencyName : null,
          "countryCode": serverLocationController.countryCode.value,
          "username": username,
          "latitude": selectedLocation.value != null ? '${selectedLocation.value!.latitude}' : '${locationC.latLng.value.latitude}',
          "longitude": selectedLocation.value != null ? '${selectedLocation.value!.longitude}' : '${locationC.latLng.value.longitude}',
          "urgencyLevel": urgencyLevel.value.isEmpty ? "Immediate" : urgencyLevel.value,
          "remarks": remarks.value.isEmpty ? "" : remarks.value,
          "uiCodes": ["000000"],
          "wasAnonymous": keepMeAnonymous.value,
          "reportedAt": DateTime.now().toString(),
          "files": authC.loginType.value == 'online' ? attachments : offlineAttachments,
        };

        final body = FormData.fromMap(bodyData);

        if (authC.loginType.value == 'online') {
          final res = await postDynamic(
            path: ApiEndpoint.addShoutIncidentForm(),
            body: body,
            authentication: true,
          );

          if (res != null) {
            if (res.data['status'] != null && res.data['status'].contains('successful') == true) {
              // is trace enabled
              if (broadcastAllowed) {
                await CtsGetStorage().write('isTraceEnabled', true);
              } else {
                await CtsGetStorage().write('isTraceEnabled', false);
              }
              if (res.data['data']['data']['shoutProcessStatus'] == 2) {
                DialogHelper.globalDialogMultipleMessage(
                  message: res.data['message'][0],
                  detailsMessage: 'No officer found',
                  isSuccess: true,
                  onTap: () {
                    back();
                    back();
                    menuC.currentIndex.value = 2;
                  },
                );
              } else if (res.data['data']['data']['shoutProcessStatus'] == 1) {
                DialogHelper.globalDialogMultipleMessage(
                  message: res.data['message'][0],
                  detailsMessage:
                      'Sorry, We are unable to process this service because there is no agency for this service. Your shout is under consideration.',
                  isSuccess: true,
                  onTap: () {
                    back();
                    back();
                    menuC.currentIndex.value = 2;
                  },
                );
              } else {
                DialogHelper.globalDialog(
                  message: res.data['message'][0],
                  isSuccess: true,
                  onTap: () {
                    back();
                    back();
                    menuC.currentIndex.value = 2;
                  },
                );
              }

              imagefiles.clear();
              selectedAttentionDropdown.value = null;
              selectedAttentionSearch.value = '';
              selectedLocation.value = null;
              knownLocation.value = false;
              remarks.value = '';
              urgencyLevel.value = '';
              searchAttentionAgencyName.value = '';
              isSubmit.value = false;
            } else {
              DialogHelper.globalDialog(
                message: 'Something went wrong',
                isSuccess: false,
                onTap: () {
                  back();
                  back();
                  menuC.currentIndex.value = 2;
                },
              );
              isSubmit.value = false;
            }
          } else {
            DialogHelper.globalDialog(
              message: 'Something went wrong',
              isSuccess: false,
              onTap: () {
                // push(HomePage());
                back();
                back();
                menuC.currentIndex.value = 2;
              },
            );
            isSubmit.value = false;
          }
        } else {
          // Offline shout logic
          final offlineShoutsBox = Hive.box<OfflineShoutModel>('offlineShouts');

          final offlineShout = OfflineShoutModel.fromJson(bodyData);
          await offlineShoutsBox.add(offlineShout);
          offlineShoutList.add(offlineShout);

          DialogHelper.globalDialog(
            message: 'Offline shout has been saved!',
            isSuccess: true,
            onTap: () {
              back();
              back();
              menuC.currentIndex.value = 2;
            },
          );
          isSubmit.value = false;
        }
      } else {
        addShout(
          attentionType: attentionType,
          broadcastAllowed: broadcastAllowed,
          categoryName: categoryName,
          categoryNameEn: categoryNameEn,
          subcategoryId: subcategoryId,
          subcategoryName: subcategoryName,
        );
      }
    } catch (e) {
      isSubmit.value = false;
      print(e);
    }
  }
Editor is loading...
Leave a Comment