AddressBookController

mail@pastecode.io avatar
unknown
dart
2 years ago
10 kB
1
Indexable
Never
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:google_place/google_place.dart';
import 'package:mobile/app/Dto/address_book_dto.dart';
import 'package:mobile/app/models/responses/get_all_cities.dart';
import 'package:mobile/app/providers/api_provider.dart';
import 'package:mobile/common/ui.dart';

class AddressBookController extends GetxController {
  @override
  void onInit() async {
    googlePlace = GooglePlace('AIzaSyA794Klcl_yyVCNL8t7Tu-jbRTt0737KoI').obs;
    print('Google Places Added');
    super.onInit();
    refeshListAddressBook();
    getAllCities();
  }

  List<AutocompletePrediction> predictions = <AutocompletePrediction>[].obs;

  Rx<GooglePlace> googlePlace;
  // final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
  Rx<TextEditingController> city = TextEditingController().obs;
  RxBool isloading = false.obs;
  Rx<TextEditingController> flat = TextEditingController().obs;
  Rx<TextEditingController> building = TextEditingController().obs;
  Rx<TextEditingController> street = TextEditingController().obs;
  Rx<TextEditingController> area = TextEditingController().obs;
  Rx<TextEditingController> direction = TextEditingController().obs;
  Rx<TextEditingController> manualAddress = TextEditingController().obs;
  Rx<TextEditingController> nickName = TextEditingController().obs;
  Rx<TextEditingController> autoComplete = TextEditingController().obs;

  String activeRequesterId = '';
  RxString nicknameStr = ''.obs;
  RxInt addressBookType = 0.obs; //Home ,Work ,Others
  RxInt addressBookOperation = 0.obs; //Add=1 ,Update=2;
  String latX;
  String longY;
  Rx<AddressBookDto> activeAddressBook = AddressBookDto().obs;
  List<AddressBookDto> AddressBookList = <AddressBookDto>[].obs;
  Position userCurrentPos;
  Future<void> refeshListAddressBook() async {
    AddressBookList.clear();
    await ApiProvider(httpClient: Dio()).getAllAdressBook().then((value) {
      print(value.toString());

      //
      value.data.items.forEach((v) {
        //languagesList.add(v);
        AddressBookList.add(v);
        // print(v.area);
      });
      print('length of ddress list=' + AddressBookList.length.toString());
    });
  }

  void populateData() {
    city.value.text = activeAddressBook.value.city ?? '';
    building.value.text = activeAddressBook.value.buildingNumber ?? '';
    street.value.text = activeAddressBook.value.street ?? '';
    area.value.text = activeAddressBook.value.area ?? '';
    direction.value.text = activeAddressBook.value.directions ?? '';
    // city.value.text = activeAddressBook.value.city ?? ''; for direction
    (nickName.value.text.toLowerCase().trim()) == 'home'
        ? addressBookType.value = 0
        : (nickName.value.text.toLowerCase().trim()) == 'work'
            ? addressBookType.value = 1
            : addressBookType.value = 2;
    nickName.value.text = activeAddressBook.value.nickName ?? '';
    nicknameStr.value = nickName.value.text;
  }

  void populateNewData() {
    city.value.text = '';
    building.value.text = '';
    street.value.text = '';
    area.value.text = '';
    direction.value.text = '';
    // city.value.text = activeAddressBook.value.city ?? ''; for direction
    addressBookType.value = 2;
    nickName.value.text = '';
    nicknameStr.value = '';
  }

  void populateNewMapData(String nameStr, String cityStr, String areaStr,
      String streetNameStr, String latStr, String longStr) {
    city.value.text = cityStr;
    building.value.text = '';
    street.value.text = streetNameStr;
    area.value.text = areaStr;
    direction.value.text = '';
    // city.value.text = activeAddressBook.value.city ?? ''; for direction
    addressBookType.value = 2;
    nickName.value.text = nameStr;
    nicknameStr.value = nameStr;
    latX = latStr.toString();
    longY = longStr.toString();
  }

  Future<void> addOrEditAddressBookItem() async {
    if (Get.locale.toString() == 'ar' ?  selectedCity.nameAr.trim() != '' : selectedCity.nameEn.trim() != '' &&
        building.value.text.trim() != '' &&
        street.value.text.trim() != '' &&
        area.value.text.trim() != '' &&
        nickName.value.text.trim() != '') {
      if (addressBookOperation.value == 1) {
        AddressBookDto addressBookItem = AddressBookDto(
            area: area.value.text.trim(),
            cityId: selectedCity.id,
            buildingNumber: building.value.text.trim(),
            city: Get.locale.toString() == 'ar'? selectedCity.nameAr : selectedCity.nameEn,
            directions: city.value.text.trim() ?? '',
            requesterId:
                activeRequesterId, // '91b1f328-ff61-4577-a71d-0a4bb8d8008b',
            street: street.value.text.trim(),
            nickName: nickName.value.text.trim(),
            isDefault: false,
            isDeleted: false,
            latitude: latX.toString(),
            longitude: longY.toString(),
            region: city.value.text.trim());

        await addAddressBookItem(addressBookItem);
        //.whenComplete(() => Get.back()); //.then((value) => Get.back());
      }
      if (addressBookOperation.value == 2) {
        AddressBookDto addressBookItem = AddressBookDto(
            area: area.value.text.trim(),
            cityId: selectedCity.id,
            buildingNumber: building.value.text.trim(),
            city: Get.locale.toString() == 'ar'? selectedCity.nameAr.trim() ?? '' : selectedCity.nameEn.trim() ?? '',
            directions: city.value.text.trim() ?? '',
            requesterId: activeAddressBook.value.requesterId,
            street: street.value.text.trim(),
            nickName: nickName.value.text.trim(),
            isDefault: activeAddressBook.value.isDefault ?? '',
            isDeleted: activeAddressBook.value.isDeleted ?? '',
            createdBy: activeAddressBook.value.createdBy ?? '',
            createdDate: activeAddressBook.value.createdDate,
            id: activeAddressBook.value.id,
            requesterName: activeAddressBook.value.requesterName ?? '',
            latitude: activeAddressBook.value.latitude ?? '',
            longitude: activeAddressBook.value.longitude ?? '',
            modifiedBy: activeAddressBook.value.modifiedBy ?? '',
            modifiedDate: activeAddressBook.value.createdDate ?? '',
            region: Get.locale.toString() == 'ar'? selectedCity.nameAr.trim() ?? '' : selectedCity.nameEn.trim() ?? '');
        await editAddressBookItem(addressBookItem);
        //.whenComplete(() => Get.back()); //.then((value) => Get.back());
      }
    }
  }

  Future<void> addAddressBookItem(AddressBookDto addressBookItem) async {
    await ApiProvider(httpClient: Dio())
        .requesterAddAddressBook(addressBookItem)
        .then((val) {
      print("val=" + val.toString());
      if (val != 'error')
        Get.showSnackbar(Ui.SuccessSnackBar(
          title: 'Success'.tr,
          message: 'Address Added Successfully'.tr,
        )).whenComplete(
            () => Get.back()); //.then((value) => refeshListAddressBook()

      // );
      // return val.toString();

      // Get.back();
    });
    selectedCity = null;
    // await ApiProvider(httpClient: Dio())
    //     .getAllProviderStatistics()
    //     .then((value) => {
    //           _accountController.getAllproviderStatistics(),
    //         });
  }

  Future<void> editAddressBookItem(AddressBookDto addressBookItem) async {
    // addressBookItem.isDefault = true;
    await ApiProvider(httpClient: Dio())
        .requesterEditAddressBook(addressBookItem)
        .then((val) {
      // return val.toString() ?? '';
      Get.showSnackbar(Ui.SuccessSnackBar(
        title: 'Success'.tr,
        message: 'Address Updated Successfully'.tr,
      )).whenComplete(() => Get.back());
    });
    //.whenComplete(() => Get.back());
    // await ApiProvider(httpClient: Dio())
    //     .getAllProviderStatistics()
    //     .then((value) => {
    //           _accountController.getAllproviderStatistics(),
    //         });
    // return "";
  }

  Future<void> deleteAddressBookItem(AddressBookDto addressBookItem) async {
    await ApiProvider(httpClient: Dio())
        .requesterDeleteAddressBook(addressBookItem)
        .then((val) {
      // Get.showSnackbar(Ui.SuccessSnackBar(
      //   title: 'Success'.tr,
      //   message: 'Address Deleted Successfully'.tr,
      // ));
    }); //.whenComplete(() => Get.back());
    // await ApiProvider(httpClient: Dio())
    //     .getAllProviderStatistics()
    //     .then((value) => {
    //           _accountController.getAllproviderStatistics(),
    //         });
  }

  RxList<AddressBookDto> providerNotifications = RxList<AddressBookDto>();

  Future<void> checkLocationPermission() async {
    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.deniedForever) {
        return Future.error(
            'Location permissions are permanently denied, we cannot request permissions.');
      }

      if (permission == LocationPermission.denied) {
        return Future.error('Location permissions are denied');
      }
    }

    userCurrentPos = await Geolocator.getCurrentPosition();
  }

  RxList<CityItems> citiesList = RxList<CityItems>();
  TextEditingController cityController = TextEditingController();
  CityItems selectedCity;

    getAllCities() async {
    await ApiProvider(httpClient: Dio()).GetAllCitis().then((value) {
      value.data.items.forEach((v) {
        citiesList.add(v);
        print(v);
      });
    });
  }

    void onCityChange(CityItems value) {
    selectedCity = value;
  }
}