import 'dart:convert';

import 'package:camera/camera.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:image_picker/image_picker.dart';
import 'package:page_transition/page_transition.dart';
import 'package:provider/provider.dart';
import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
import 'package:telnow_mobile_new/src/injector/injector.dart';
import 'package:telnow_mobile_new/src/layouts/components/camera.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/request_success.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/layouts/web/request_success.dart';
import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:telnow_mobile_new/src/utils/cache_manager.dart';
import 'package:telnow_mobile_new/src/utils/provider.dart';

import 'package:image/image.dart' as img;
import 'package:telnow_mobile_new/src/utils/ui_service.dart';
import 'package:uuid/uuid.dart';

class RequestFunction{
  final ApiAuthProvider apiAuthProvider = ApiAuthProvider();
  final SharedPreferencesManager sharedPreferencesManager = locator<SharedPreferencesManager>();

  getData(BuildContext context, String? _keyword, widget) async {
    bool _inGroup = widget.groupCode != null ? true : false;
    bool _isEmpty = true;
    if(!Provider.of<RequestModule>(context, listen: false).isLoad()){
      Provider.of<RequestModule>(context, listen: false).setIsLoad(true);
      Provider.of<RequestModule>(context, listen: false).setKeyword(_keyword != null ? _keyword : "");
      try{
        String tenant = '';
        String filter = '';
        String search = '';
        String group = '';
        String url = '';

        if(_keyword != null){
          String subject = U.realColumn(context.locale, 'subject');
          search = ',{"f":["$subject","LIKE","%$_keyword%"]}';
        }

        if(widget.groupCode != null){
          url = '/api/requests/search/custom';
          group = ',{"f":["${U.servantDisplay()?'servantGroupCode':'requestGroup.code'}","EQ","${widget.groupCode}"]}';
          filter = '{"and":[{"or":[{"f":["scope","EQ","ALL"]},{"f":["scope","EQ","${widget.scope}"]}]}$search$group]}';
        }
        else{
          url = '/api/requests/search/menu';
          filter = '{"and":[{"or":[{"f":["scope","EQ","ALL"]},{"f":["scope","EQ","${widget.scope}"]}]}$search]}';
        }

        String key = '$url-$filter';
        if (_inGroup && _keyword == null) {
          try {
            await CacheMan.readData(key).then((val){
              if (val != null) {
                Provider.of<RequestModule>(context, listen: false).setData(val['data']);
                _isEmpty = false;
              }
            });
          } catch(e){}
        }
        List tempData = [];

        var res = await apiAuthProvider.getData(url, {'filter': filter, 'nopage': 'true'});
        if (res != null && res.toString() != "[]") {
          if (res.containsKey('_embedded')) {
            for (int i = 0; i < res['_embedded']['requests'].length; i++) {
              tempData.add(res['_embedded']['requests'][i]);
            }

            if(tempData.length > 0) _isEmpty = false;
          }
        }
        Provider.of<RequestModule>(context, listen: false).setEmpty(_isEmpty);

        if (U.getInternetStatus()) {
          Provider.of<RequestModule>(context, listen: false).setData(tempData);
          if (_inGroup && _keyword == null) CacheMan.writeData(key, tempData);
        }

        Provider.of<RequestModule>(context, listen: false).setIsLoad(false);
      } catch(e){
        print(e);
        Provider.of<RequestModule>(context, listen: false).setIsLoad(false);
      }
    }
  }

  Future getSuggestionLocation(BuildContext context) async{
    var res = await apiAuthProvider.getData('/api/requestHistories/search/location/suggestion', null);
    if(res != null){
      Provider.of<CreateSerModule>(context, listen: false).setSuggestion(res);
    }
  }

  Future getImageNew(BuildContext context, media) async {
    try {
      Provider.of<CreateSerModule>(context, listen: false).setSetLoadingEffect(true);
      XFile? pickedFile;
      if(media == ImageSource.camera){
        await availableCameras().then((camera) => Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: OpenCamera(cameras: camera))).then((value) async{
          if(value!=null){
            pickedFile = value;
          }
        }));
      }
      else{
        pickedFile = await ImagePicker().pickImage(source: media);
      }

      if (pickedFile != null) {
        var image = img.decodeImage(await pickedFile!.readAsBytes());
        var imgPercent = (1000 / (image!.width / 100)).toDouble();
        if (image.width > 1000) {
          image = img.copyResize(image, width: ((image.width / 100) * imgPercent).toInt(), height: ((image.height / 100) * imgPercent).toInt());
        }
        var compressed = img.encodeJpg(image, quality: 60);

        Provider.of<CreateSerModule>(context, listen: false).setSetLoadingEffect(false);
        return compressed;
      }
      else{
        Provider.of<CreateSerModule>(context, listen: false).setSetLoadingEffect(false);
        return null;
      }
    } catch (e) {
      Provider.of<CreateSerModule>(context, listen: false).setSetLoadingEffect(false);
      return null;
    }
  }

  sendRequest(BuildContext context, widget, controllerNote, controllerReferenceNumber, controllerLocation, controllerDateString, currentSliderValue, dynamic asset) async{
    // showLoading(context, lottie: kIsWeb && !isCanvasKit ? null : 'Paperplane.json', text: 'sendingRequest'.tr());
    UIService.showLoading(text: 'sendingRequest'.tr(), lottie: kIsWeb && !isCanvasKit ? null : 'Paperplane.json' );
    var data;
    data = {
      'note': controllerNote.text.trim() == '' ? '' : controllerNote.text.trim(),
      'parentTicket': controllerReferenceNumber.text.trim() == '' ? null : controllerReferenceNumber.text.trim(),
      'location': Provider.of<CreateSerModule>(context, listen: false).locationType() == 2 ? controllerLocation.text.trim() : Provider.of<CreateSerModule>(context, listen: false).defaultLocation(),
      'sendLater': Provider.of<CreateSerModule>(context, listen: false).sendLater(),
      'datetimeScheduled': controllerDateString.text.trim(),
      'requestPriority': getPrioValue(currentSliderValue),
      'assetCode': asset
    };

    if(!kIsWeb && !U.getInternetStatus()){
      closeLoading(context);
      sendRequestNoInternet(context, widget, controllerLocation, controllerNote, data: data, others: false);
    }
    else{
      List imageEncode = Provider.of<CreateSerModule>(context, listen: false).images();
      imageEncode.forEach((element) {
        element = base64Encode(element);
      });
      data['images'] = imageEncode;

      var res = await apiAuthProvider.postData('/api/requestHistories/search/request/' + widget.request['type'] + '/' + widget.request['id'].toString() + '/' + widget.request['noteFormat'] + '/submit', null, data);
      if (res != null) {
        Future.delayed(Duration(seconds: 3), (){
          closeLoading(context);
          navigateTo(context, U.webView(context) ? WebReqSuccessPage(user: widget.user, ticketNo: res['ticketNo'], fromSearch: widget.fromSearch) : MobReqSuccessPage(user: widget.user, ticketNo: res['ticketNo'], fromSearch: widget.fromSearch)).then((res){
            while (Navigator.canPop(context)){
              Navigator.pop(context);
            }
          });
        });
      }
      else{
        closeLoading(context);
      }
    }
  }

  getPrioValue(currentSliderValue){
    switch(currentSliderValue){
      case 0: return 'RENDAH';
      case 50: return 'NORMAL';
      case 100: return 'TINGGI';
      default: return 'NORMAL';
    }
  }

  sendRequestToOthers(BuildContext context, widget, controllerUserId, controllerNote, controllerReferenceNumber, controllerLocation, controllerDateString, currentSliderValue) async{
    showLoading(context, lottie: kIsWeb && !isCanvasKit ? null : 'Paperplane.json', text: 'sendingRequest'.tr());
    var data;
    data = {
      'user_id': controllerUserId.text.trim(),
      'req': [{
        'request_code': widget.request['code'],
        'qty': 1,
        'note': controllerNote.text.trim() == '' ? '' : controllerNote.text.trim(),
        'parentTicket': controllerReferenceNumber.text.trim() == '' ? null : controllerReferenceNumber.text.trim(),
        'tenantCode': widget.request['tenantCode'],
        'location': Provider.of<CreateSerModule>(context, listen: false).locationType() == 2 ? controllerLocation.text.trim() : Provider.of<CreateSerModule>(context, listen: false).defaultLocation(),
        'datetimeScheduled': controllerDateString.text.trim(),
        'requestPriority': getPrioValue(currentSliderValue)
      }]
    };

    if(!kIsWeb && !U.getInternetStatus()){
      closeLoading(context);
      sendRequestNoInternet(context, widget, controllerLocation, controllerNote, data: data, others: true);
    }
    else{
      List imageEncode = Provider.of<CreateSerModule>(context, listen: false).images();
      imageEncode.forEach((element) {
        element = base64Encode(element);
      });
      data['req'][0]['images'] = imageEncode;

      try{
        var res = await apiAuthProvider.postData('/api/receptionists/send/request', null, data);
        print("res ##> $res");
        if (res != null) {
          Future.delayed(Duration(seconds: 3), (){
            closeLoading(context);
            navigateTo(context, U.webView(context) ? WebReqSuccessPage(user: widget.user, ticketNo: res['ticketNo'], fromSearch: widget.fromSearch) : MobReqSuccessPage(user: widget.user, ticketNo: res['ticketNo'], fromSearch: widget.fromSearch)).then((res){
              while (Navigator.canPop(context)){
                Navigator.pop(context);
              }
            });
          });
        } else {
          closeLoading(context);
        }
      }catch(e){
        print("error: $e");
        closeLoading(context);
      }
    }
  }

  sendRequestNoInternet(BuildContext context, widget, controllerLocation, controllerNote, {data, others})async{
    List list = sharedPreferencesManager.isKeyExists(SharedPreferencesManager.keyPendingData)!?jsonDecode(sharedPreferencesManager.getString(SharedPreferencesManager.keyPendingData)!):[];
    List imageEncode = [];
    Provider.of<CreateSerModule>(context, listen: false).images().forEach((element) {
      imageEncode.add(base64Encode(element));
    });

    var params = {
      'uniqueId': Uuid().v1(),
      'others': others,
      'title': widget.request['subject'],
      'image': widget.request['_mobileImage'],
      'sub': widget.request['_requestGroupDescription'],
      'subEn': widget.request['_requestGroupDescriptionEn'],
      'subJa': widget.request['_requestGroupDescriptionJa'],
      'subKo': widget.request['_requestGroupDescriptionKo'],
      'subZh': widget.request['_requestGroupDescriptionZh'],
      'desc': widget.request['subjectDescription'],
      'descEn': widget.request['subjectDescriptionEn'],
      'descJa': widget.request['subjectDescriptionJa'],
      'descKo': widget.request['subjectDescriptionKo'],
      'descZh': widget.request['subjectDescriptionZh'],
      'type': widget.request['type'],
      'id': widget.request['id'],
      'noteFormat': widget.request['noteFormat'],
      'location': Provider.of<CreateSerModule>(context, listen: false).locationType() == 2 ? controllerLocation.text.trim() : Provider.of<CreateSerModule>(context, listen: false).defaultLocation(),
      'note': controllerNote.text.trim() == '' ? '' : controllerNote.text.trim(),
      'data': data,
      'imageList': imageEncode,
      'datetimeRequest': DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now())
    };

    list.add(params);
    await sharedPreferencesManager.putString(SharedPreferencesManager.keyPendingData, jsonEncode(list));
    navigateTo(context, U.webView(context)?WebReqSuccessPendingPage(data: params, fromSearch: widget.fromSearch):MobReqSuccessPendingPage(data: params, fromSearch: widget.fromSearch)).then((res){
      while (Navigator.canPop(context)){
        Navigator.pop(context);
      }
    });
  }
}