Untitled

 avatar
unknown
plain_text
a year ago
10 kB
7
Indexable
// offline Shout add & delete
  void deleteOfflineShout(OfflineShoutModel item) async {
    final offlineShoutsBox = Hive.box<OfflineShoutModel>('offlineShouts');

    final index = offlineShoutsBox.values.toList().indexOf(item);

    await offlineShoutsBox.deleteAt(index);
    offlineShoutList.remove(item);
    back();
    DialogHelper.globalDialog(
      message: 'The offline shout incident was deleted successfully',
      isSuccess: true,
      onTap: () {
        back();
      },
    );
  }

  void syncOfflineShouts() async {
    isSubmitOfflineShout.value = true;

    final offlineShoutsBox = Hive.box<OfflineShoutModel>('offlineShouts');
    final allOfflineShouts = offlineShoutsBox.values.toList();

    final List<MultipartFile> attachments = [];

    for (final item in allOfflineShouts) {
      for (final imgItem in item.files!) {
        final img = await MultipartFile.fromBytes(
          imgItem.toList(),
          filename: '${getUniqeId()}.jpg',
        );

        attachments.add(img);
      }

      final mapData = item.toJson();

      mapData['files'] = attachments;

      final body = FormData.fromMap(mapData);

      final res = await postDynamic(
        path: ApiEndpoint.addShoutIncidentForm(),
        body: body,
        authentication: true,
      );

      attachments.clear();
      kLog(res.data);

      if (res != null) {
        if (res.data['status'] != null && res.data['status'].contains('successful') == true) {
          isSubmit.value = false;

          if (res.data['data']['data']['shoutProcessStatus'] == 2) {
            DialogHelper.globalDialogMultipleMessage(
              message: res.data['message'][0],
              detailsMessage: 'No Officer Found',
              isSuccess: true,
              onTap: () {
                back();
                back();
              },
            );
          } 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();
              },
            );
          } 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 = '';
        } else {
          isSubmit.value = false;
          DialogHelper.globalDialog(
            message: 'Something went wrong',
            isSuccess: false,
            onTap: () {
              back();
              back();
            },
          );
        }
      } else {
        DialogHelper.globalDialog(
          message: 'Something went wrong',
          isSuccess: false,
          onTap: () {
            back();
            back();
          },
        );
      }

      await 2.delay();
    }

    await offlineShoutsBox.clear();

    offlineShoutList.clear();

    isSubmitOfflineShout.value = false;
  }

  void initOfflineShouts() {
    final offlineShoutsBox = Hive.box<OfflineShoutModel>('offlineShouts');
    final allOfflineShouts = offlineShoutsBox.values.toList();

    offlineShoutList.addAll(allOfflineShouts);
  }

  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 = false;
    try {
      // 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) {
            isSubmit.value = false;

            // 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 = '';
          } else {
            isSubmit.value = false;
            DialogHelper.globalDialog(
              message: 'Something went wrong',
              isSuccess: false,
              onTap: () {
                back();
                back();
                menuC.currentIndex.value = 2;
              },
            );
          }
        } else {
          DialogHelper.globalDialog(
            message: 'Something went wrong',
            isSuccess: false,
            onTap: () {
              // push(HomePage());
              back();
              back();
              menuC.currentIndex.value = 2;
            },
          );
        }
      } 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;
          },
        );
      }
    } catch (e) {
      print(e);
    }
  }
Editor is loading...
Leave a Comment