import 'package:absenkuv3/Repository/Model/mReimbursement.dart';
import 'package:absenkuv3/Repository/Model/mSplashScreen.dart';
import 'package:absenkuv3/Repository/Service/reimbursementApi.dart';
import 'package:absenkuv3/Repository/Service/serviceInfo.dart';
import 'package:collection/collection.dart' show IterableExtension;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:sn_progress_dialog/sn_progress_dialog.dart';
import '../CustomFunction.dart';

abstract class ReimbursementDetailEvent {
  BuildContext? context;
  GlobalKey<ScaffoldState>? scaffoldKey;
}

class GetDetailReimbursementEvent extends ReimbursementDetailEvent {
  String? idPengajuan;
  GetDetailReimbursementEvent(BuildContext? _context, this.idPengajuan) {
    context = _context;
  }
}

class ApprovalReimbursementEvent extends ReimbursementDetailEvent {
  ApprovalReimbursementModel approvalReimbursementModel;
  ApprovalReimbursementEvent(this.approvalReimbursementModel);
}

class RevisiReimbursementItemEvent extends ReimbursementDetailEvent {
  DataItem dataItem;
  RevisiReimbursementItemEvent(this.dataItem);
}

class SubmitApprovalReimbursementEvent extends ReimbursementDetailEvent {
  SubmitApprovalReimbursementEvent(
      BuildContext _context, GlobalKey<ScaffoldState> _scaffoldKey) {
    context = _context;
    scaffoldKey = _scaffoldKey;
  }
}

class SubmitRevisiReimbursementEvent extends ReimbursementDetailEvent {
  SubmitRevisiReimbursementEvent(
      BuildContext _context, GlobalKey<ScaffoldState> _scaffoldKey) {
    context = _context;
    scaffoldKey = _scaffoldKey;
  }
}

abstract class ReimbursementDetailState {
  DataReimbursement? dataReimbursement;
}

class GetListReimbursementSuccessState extends ReimbursementDetailState {
  bool aksiFooterLocal;
  GetListReimbursementSuccessState(
      ReimbursementDetailEvent _event, DataReimbursement? _data,
      {this.aksiFooterLocal = false}) {
    dataReimbursement = _data;
  }
}

class ReimbursementProgressState extends ReimbursementDetailState {}

class ReimbursementErrorState extends ReimbursementDetailState {}

class ReimbursementDetailBloc
    extends Bloc<ReimbursementDetailEvent, ReimbursementDetailState> {
  final dateFormat = new DateFormat('yyyy-MM');
  ReimbursementDetailState? initialState;
  DataReimbursement? dataReimbursement;
  String? idPengajuan;
  int offset = 0;
  int limit = ServerInfo.limit;
  int? jumlah = 0;
  List<ApprovalReimbursementModel> listApprovalReimbursementModel =
      <ApprovalReimbursementModel>[];
  List<DataItem> listRevisiReimbursementItemModel = <DataItem>[];

  ReimbursementDetailBloc(ReimbursementDetailState initialState)
      : super(initialState);

  @override
  Stream<ReimbursementDetailState> mapEventToState(
      ReimbursementDetailEvent event) async* {
    if (event is GetDetailReimbursementEvent) {
      offset = 0;
      yield ReimbursementProgressState();
      ReimbursementRespon reimbursementRespon = await ReimbursementApi()
          .getDataReimbursementDetail(event.idPengajuan);
      if (reimbursementRespon.success!) {
        idPengajuan = event.idPengajuan;
        dataReimbursement = reimbursementRespon.data![0];
        jumlah = dataReimbursement!.listItemPengajuan!.jumlah;
        yield GetListReimbursementSuccessState(event, dataReimbursement);
      } else
        yield ReimbursementErrorState();
    } else if (event is ApprovalReimbursementEvent) {
      final item = dataReimbursement!.listItemPengajuan!.dataItem!
          .firstWhereOrNull(
              (item) => item.idItem == event.approvalReimbursementModel.id);
      if (item != null) {
        // print('nominal : ${event.approvalReimbursementModel.nominal}');
        item.nominalDisetujui = int.parse(
            event.approvalReimbursementModel.nominal != '' &&
                    event.approvalReimbursementModel.nominal != null
                ? event.approvalReimbursementModel.nominal!
                : '0');
        int totalPengajuanDisetujuiTemp = 0;
        for (int i = 0;
            i < dataReimbursement!.listItemPengajuan!.dataItem!.length;
            i++) {
          totalPengajuanDisetujuiTemp = totalPengajuanDisetujuiTemp +
              dataReimbursement!
                  .listItemPengajuan!.dataItem![i].nominalDisetujui!;
        }
        dataReimbursement!.totalPengajuanDisetujui =
            totalPengajuanDisetujuiTemp.toString();
      }

      if (listApprovalReimbursementModel.length > 0) {
        final item = listApprovalReimbursementModel.firstWhereOrNull(
            (item) => item.id == event.approvalReimbursementModel.id);
        if (item != null) {
          item.id = event.approvalReimbursementModel.id;
          item.status = event.approvalReimbursementModel.status;
          item.keterangan = event.approvalReimbursementModel.keterangan;
          item.nominal = event.approvalReimbursementModel.nominal;
        } else
          listApprovalReimbursementModel.add(event.approvalReimbursementModel);
      } else
        listApprovalReimbursementModel.add(event.approvalReimbursementModel);
      // print("LIST APPROVAL LENGHT ${listApprovalReimbursementModel.length}");
      if (dataReimbursement!.listItemPengajuan!.jumlah ==
          listApprovalReimbursementModel.length)
        yield GetListReimbursementSuccessState(event, dataReimbursement,
            aksiFooterLocal: true);
      else
        yield GetListReimbursementSuccessState(event, dataReimbursement,
            aksiFooterLocal: false);
    } else if (event is RevisiReimbursementItemEvent) {
      final item = dataReimbursement!.listItemPengajuan!.dataItem!
          .firstWhereOrNull((item) => item.idItem == event.dataItem.idItem);
      if (item != null) {
        item.idItem = event.dataItem.idItem;
        item.idJenis = event.dataItem.idJenis;
        item.nominal = event.dataItem.nominal;
        item.tglNota = event.dataItem.tglNota;
        item.keterangan = event.dataItem.keterangan;
        item.file = event.dataItem.file ?? item.file;
        item.editedPhotoPath = event.dataItem.editedPhotoPath;
        int totalPengajuanTemp = 0;
        for (int i = 0;
            i < dataReimbursement!.listItemPengajuan!.dataItem!.length;
            i++) {
          totalPengajuanTemp = totalPengajuanTemp +
              dataReimbursement!.listItemPengajuan!.dataItem![i].nominal!;
        }
        dataReimbursement!.totalPengajuan = totalPengajuanTemp.toString();
      }

      if (listRevisiReimbursementItemModel.length > 0) {
        final item = listRevisiReimbursementItemModel
            .firstWhereOrNull((item) => item.idItem == event.dataItem.idItem);
        if (item != null) {
          item.idItem = event.dataItem.idItem;
          item.idJenis = event.dataItem.idJenis;
          item.nominal = event.dataItem.nominal;
          item.tglNota = event.dataItem.tglNota;
          item.keterangan = event.dataItem.keterangan;
          item.file = event.dataItem.file;
        } else
          listRevisiReimbursementItemModel.add(event.dataItem);
      } else
        listRevisiReimbursementItemModel.add(event.dataItem);
      // print("LIST REVISI LENGHT ${listRevisiReimbursementItemModel.length}");
      if (dataReimbursement!.listItemPengajuan!.jumlah ==
          listRevisiReimbursementItemModel.length)
        yield GetListReimbursementSuccessState(event, dataReimbursement,
            aksiFooterLocal: true);
      else
        yield GetListReimbursementSuccessState(event, dataReimbursement,
            aksiFooterLocal: false);
    } else if (event is SubmitApprovalReimbursementEvent) {
      ProgressDialog pd = ProgressDialog(context: event.context);
      ProgressDialogDelayed.show(pd, isDismissible: false);
      BasicRespon basicRespon = await ReimbursementApi()
          .submitApprovalReimbursement(
              listApprovalReimbursementModel, idPengajuan);
      ProgressDialogDelayed.hide(pd);
      showSnackBarDelayed(
          event.scaffoldKey, basicRespon.message, event.context);
      if (basicRespon.success!)
        BlocProvider.of<ReimbursementDetailBloc>(event.context!)
            .add(GetDetailReimbursementEvent(event.context, idPengajuan));
      // print("LIST APPROVAL LENGHT ${listApprovalReimbursementModel.length}");
    } else if (event is SubmitRevisiReimbursementEvent) {
      ProgressDialog pd = ProgressDialog(context: event.context);
      ProgressDialogDelayed.show(pd, isDismissible: false);
      BasicRespon basicRespon = await ReimbursementApi()
          .submitRevisiReimbursement(
              listRevisiReimbursementItemModel, idPengajuan);
      ProgressDialogDelayed.hide(pd);
      showSnackBarDelayed(
          event.scaffoldKey, basicRespon.message, event.context);
      if (basicRespon.success!)
        BlocProvider.of<ReimbursementDetailBloc>(event.context!)
            .add(GetDetailReimbursementEvent(event.context, idPengajuan));
      // print("LIST APPROVAL LENGHT ${listApprovalReimbursementModel.length}");
    }
  }
}
