import 'dart:convert';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
import 'package:telnow_mobile_new/src/api/jwt_token.dart';
import 'package:telnow_mobile_new/src/injector/injector.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/request_create.dart';
import 'package:telnow_mobile_new/src/layouts/web/request_create.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';

class HistoryFunction{
  final JwtToken token = JwtToken();
  final ApiAuthProvider apiAuthProvider = ApiAuthProvider();
  final SharedPreferencesManager sharedPreferencesManager = locator<SharedPreferencesManager>();

  List doneList = [
    {'title': 'stateFinish'.tr(), 'value': 3, 'filter': '{"or":[{"f":["currentState","EQ","DISELESAIKAN"]},{"f":["currentState","EQ","TUNTAS"]}]}'},
    {'title': 'stateCancel'.tr(), 'value': 4, 'filter': '{"f":["currentState","EQ","DIBATALKAN"]}'},
  ];
  List ongoingList = [
    {'title': 'stateQueue'.tr(), 'value': 1, 'filter': '{"or":[{"f":["currentState","EQ","DIANTRIKAN"]},{"f":["currentState","EQ","DIPROSES"]}]}'},
    {'title': 'stateDone'.tr(), 'value': 2, 'filter': '{"f":["currentState","EQ","DIMULAI"]}'},
    {'title': 'hold'.tr(), 'value': 3, 'filter': '{"f":["currentState","EQ","HOLD"]}'},
  ];

  getActiveForum(BuildContext context, {bool loadAfterAction = false}) async {
    try {
      String urlForum = '/api/notifications/search/forumNotification';

      var val = await CacheMan.readData(urlForum);
      if (val != null) {
        Provider.of<HistoryModule>(context, listen: false).setActiveForum(val['data']);
      }

      var data = await apiAuthProvider.getData(urlForum, null, context);
      if (data != null) {
        Provider.of<HistoryModule>(context, listen: false).setActiveForum(data);
        CacheMan.writeData(urlForum, data);
        getUser(context);
      }
      else{
        getUser(context);
      }
    } catch (e) {
      print(e.toString());
    }
  }

  getUser(BuildContext context) async {
    try {
      var res = await token.getUserData(context);
      if (res != null) {
        Provider.of<UserModule>(context, listen: false).setList(res);
        getMission(context);
      } else {
        Provider.of<UserModule>(context, listen: false).setResetData(true);
      }
    } catch (e) {
      Provider.of<UserModule>(context, listen: false).setResetData(true);
    }
  }

  getMission(BuildContext context) async {
    try {
      if (!Provider.of<HistoryModule>(context, listen: false).isLoadHistory() && !Provider.of<HistoryModule>(context, listen: false).stopLoadHistory()) {
        Provider.of<HistoryModule>(context, listen: false).setLoadHistory(true);
        var sort = ['datetimeRequest,desc'];
        var filter = '';

        if (Provider.of<HistoryModule>(context, listen: false).selectedFilter() == 0) {
          if (Provider.of<HistoryModule>(context, listen: false).pressAttention() != 0) {
            for (int i = 0; i < doneList.length; i++) {
              if (Provider.of<HistoryModule>(context, listen: false).checkPressAttention(doneList[i]['value'])) {
                filter = doneList[i]['filter'];
              }
            }
          } else {
            filter = '{"or":[{"f":["currentState","EQ","DISELESAIKAN"]},{"f":["currentState","EQ","TUNTAS"]},{"f":["currentState","EQ","DIBATALKAN"]}]}';
          }
        } else {
          if((Provider.of<HistoryModule>(context, listen: false).pressAttention() == 0 || Provider.of<HistoryModule>(context, listen: false).pressAttention() == 1) && U.newServerVersion(1709864293) && !U.getInternetStatus()){
            List pendingList = sharedPreferencesManager.isKeyExists(SharedPreferencesManager.keyPendingData)!?jsonDecode(sharedPreferencesManager.getString(SharedPreferencesManager.keyPendingData)!):[];
            Provider.of<HistoryModule>(context, listen: false).setPendingData(pendingList);
          }

          if (Provider.of<HistoryModule>(context, listen: false).pressAttention() != 0) {
            for (int i = 0; i < ongoingList.length; i++) {
              if (Provider.of<HistoryModule>(context, listen: false).checkPressAttention(ongoingList[i]['value'])) {
                filter = ongoingList[i]['filter'];
              }
            }
          } else {
            filter = '{"or":[{"f":["currentState","EQ","DIANTRIKAN"]},{"f":["currentState","EQ","DIPROSES"]},{"f":["currentState","EQ","DIMULAI"]}]}';
          }
        }

        String url = '/api/requestHistories/search/myReqHistory';

        String key = url + filter;
        var val = await CacheMan.readData(key);
        if (val != null && Provider.of<HistoryModule>(context, listen: false).page() == 0) {
          Provider.of<HistoryModule>(context, listen: false).setMisi(val['data']);
        }

        var misi = await apiAuthProvider.getData(url, {'size': '30', 'page': Provider.of<HistoryModule>(context, listen: false).page().toString(), 'sort': sort, 'filter': filter}, context);
        if (misi != null) {
          List tempData = [];
          if (misi.containsKey('_embedded')) {
            for (int i = 0; i < misi['_embedded']['requestHistories'].length; i++) {
              var _isFrm = false;
              var _id = null;
              var _msg = null;

              Provider.of<HistoryModule>(context, listen: false).activeForum().forEach((el) {
                if (el['ticketId'] == misi['_embedded']['requestHistories'][i]['ticketNo']) {
                  _id = el['id'];
                  _msg = el['desc'];
                }
              });

              if (_id != null) _isFrm = true;
              misi['_embedded']['requestHistories'][i]['_hasForum'] = _isFrm;
              misi['_embedded']['requestHistories'][i]['_forumId'] = _id;
              misi['_embedded']['requestHistories'][i]['_forumMsg'] = _msg;

              tempData.add(misi['_embedded']['requestHistories'][i]);
            }
          }

          Provider.of<HistoryModule>(context, listen: false).setLoadHistory(false);
          if (tempData.length == 0) {
            Provider.of<HistoryModule>(context, listen: false).setStopLoadHistory(true);
            Provider.of<HistoryModule>(context, listen: false).clearMisi();
            CacheMan.writeData(key, tempData);
          } else {
            if (Provider.of<HistoryModule>(context, listen: false).page() == 0) {
              CacheMan.writeData(key, tempData);
              Provider.of<HistoryModule>(context, listen: false).clearMisi();
            }
            Provider.of<HistoryModule>(context, listen: false).addPage();
          }
          Provider.of<HistoryModule>(context, listen: false).setMisi(tempData);

          if (Provider.of<HistoryModule>(context, listen: false).getMisiLength() >= misi['page']['totalElements']) {
            Provider.of<HistoryModule>(context, listen: false).setStopLoadHistory(true);
          }
        }
        else{
          Provider.of<HistoryModule>(context, listen: false).setLoadHistory(false);
          Provider.of<HistoryModule>(context, listen: false).setStopLoadHistory(true);
        }
      }
    } catch (e) {
      print(e.toString());
    }
  }

  onRefresh(BuildContext context) async {
    Provider.of<HistoryModule>(context, listen: false).clearMisi();
    Provider.of<HistoryModule>(context, listen: false).setPendingData([]);
    Provider.of<HistoryModule>(context, listen: false).setActiveForum([]);
    Provider.of<HistoryModule>(context, listen: false).setSelectedIndexes([]);
    Provider.of<HistoryModule>(context, listen: false).setMultiSelectMode(false);
    Provider.of<HistoryModule>(context, listen: false).setStopLoadHistory(false);
    Provider.of<HistoryModule>(context, listen: false).setPage(0);
    getActiveForum(context);
  }

  bool askForRate(list) {
    if (list['satisfactionRate'] == 0 && list['servantGroup'] != "#autoresponse") {
      return true;
    }
    return false;
  }

  bool isAutoResponse(list) {
    if (list['servantGroup'] == "#autoresponse") {
      return true;
    }
    return false;
  }

  selectedController(BuildContext context, i) {
    if (Provider.of<HistoryModule>(context, listen: false).selectedIndexes().contains(i)) {
      Provider.of<HistoryModule>(context, listen: false).removeSelectedIndexes(i);
    } else {
      Provider.of<HistoryModule>(context, listen: false).addSelectedIndexes(i);
    }
    Provider.of<HistoryModule>(context, listen: false).setMultiSelectMode(Provider.of<HistoryModule>(context, listen: false).selectedIndexes().length == 0 ? false : true);
  }

  deleteData(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext contextt) {
        return AlertDialog(
          title: Text("deleteHistory".tr(), style: TextStyle(fontSize: 18),
          ),
          content: Text("deleteHistoryConfirm".tr()),
          actions: <Widget>[
            TextButton(
              child: Text("buttonNo".tr()),
              onPressed: () {
                Navigator.of(contextt).pop();
              },
            ),
            TextButton(
                onPressed: () async {
                  Navigator.of(contextt).pop();
                  List<String> params = [];
                  Provider.of<HistoryModule>(context, listen: false).selectedIndexes().forEach((e) {
                    params.add(Provider.of<HistoryModule>(context, listen: false).dataMisi()[e]["ticketNo"]);
                  });
                  var res = await apiAuthProvider.postData("/api/requestHistories/deleteMyHistory", {"ticketNumbers": params}, null, context);
                  if (res != null) {
                    onRefresh(context);
                  }
                },
                child: Text("buttonYes".tr())),
          ],
        );
      },
    );
  }

  requestAgainAction(BuildContext context, int i) async{
    try {
      String tenant = '';
      String filter = '';

      if ((Provider.of<HistoryModule>(context, listen: false).dataMisi()[i]['requestGroupCode']).split(" ").length != 1) {
        tenant = ',{"f":["tenantCode","EQ","${(Provider.of<HistoryModule>(context, listen: false).dataMisi()[i]['requestGroupCode']).split(" ").first}"]}';
      }
      filter = '{"and":[{"f":["code","EQ","${Provider.of<HistoryModule>(context, listen: false).dataMisi()[i]['requestCode']}"]}$tenant]}';

      var res = await apiAuthProvider.getData('/api/requests/search/customFind', {'filter': filter}, context);
      if (res != null) {
        if (res.containsKey('_embedded')) {
          navigateTo(context, U.webView(context)?WebReqCreatePage(user: Provider.of<UserModule>(context, listen: false).user(), request: res['_embedded']['requests'][0]):MobReqCreatePage(user: Provider.of<UserModule>(context, listen: false).user(), request: res['_embedded']['requests'][0]));
        } else {
          showError(context, 'reqCodeNotFound'.tr());
        }
      }
    } catch (e) {
      showError(context, e.toString());
      print(e);
    }
  }
}