import 'dart:async';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:peasmartcare/models/additional_service_model.dart';
import 'package:peasmartcare/models/result_data_model.dart';
import 'package:peasmartcare/models/user_model.dart';
import 'package:peasmartcare/services/additional_service.dart';
import 'package:peasmartcare/utils/clear_count_notification_util.dart';
import 'package:peasmartcare/utils/share_data_util.dart';

part 'additional_service_detail_event.dart';
part 'additional_service_detail_state.dart';

class AdditionalServiceDetailBloc extends Bloc<AdditionalServiceDetailEvent, AdditionalServiceDetailState> {
  AdditionalImpService service = AdditionalImpService();

  ResultData resultData;
  String id;

  AdditionalServiceDetailBloc() : super(AdditionalServiceDetailInitial());

  @override
  Stream<AdditionalServiceDetailState> mapEventToState(AdditionalServiceDetailEvent event) async* {
    try {
      if (event is AdditionalServiceDetailGetData) {
        yield AdditionalServiceDetailLoading();

        await ClearCountNotificationUtil.additionalService();

        resultData = await service.getDetail(
          id: id,
          authenKey: ShareDataUtil.getAuthenKey(),
        );

        if (resultData.statusCode == 401) {
          yield AdditionalServiceDetailErrorUnauthorized();
        } else {
          yield AdditionalServiceDetailLoaded(
            result: resultData.result,
            saveSuccess: null,
          );
        }
      } else if (event is AdditionalServiceDetailOnSave) {
        yield AdditionalServiceDetailLoading();
        UserModel user = ShareDataUtil.getUserInfo();

        String id = event.id;
        String caNumber = ShareDataUtil.getCaNumber();
        String statusId = "1";
        String createBy = user.firstname;
        String descreption = "ขอใช้บริการเสริม";

        ResultData saveResult = await service.save(
          id: id,
          caNumber: caNumber,
          statusId: statusId,
          createBy: createBy,
          descreption: descreption,
          customerId: ShareDataUtil.getCustomerId(),
          customerName: ShareDataUtil.getCustomerName(),
          fullname: ShareDataUtil.getFullname(),
          authenKey: ShareDataUtil.getAuthenKey(),
        );

        if (resultData.statusCode == 401) {
          yield AdditionalServiceDetailErrorUnauthorized();
        } else {
          yield AdditionalServiceDetailLoaded(
            result: resultData.result,
            saveSuccess: saveResult.result,
          );
        }
      } else if (event is AdditionalServiceDetailAddId) {
        id = event.id;
      }
    } catch (e) {
      print(e);
      yield AdditionalServiceDetailError(message: "Error");
    }
  }
}
