import 'dart:typed_data';

import 'package:domain/entity/feedback_detail_entity.dart';
import 'package:domain/entity/form_option_entity.dart';
import 'package:plugin_platform/platform_export.dart';
import 'package:plugin_platform/http/dio_engine.dart';
import 'package:plugin_platform/http/http_result.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';

import '../constants/api_constants.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:plugin_basic/provider/http_provider/http_provider.dart';
import '../entity/form_content_entity.dart';
import '../entity/form_detail_entity.dart';
import '../entity/form_list_entity.dart';
import '../entity/form_order_entity.dart';
import '../entity/form_submitted_page_entity.dart';
import '../entity/id_name_entity.dart';

part 'form_repository.g.dart';

@Riverpod(keepAlive: true)
FormRepository formRepository(Ref ref) {
  final dioEngine = ref.watch(dioEngineProvider);
  return FormRepository(dioEngine: dioEngine);
}

/*
 * 表单的数据仓库
 */
class FormRepository {
  DioEngine dioEngine;

  FormRepository({required this.dioEngine});

  /// 获取表单的可申请列表
  Future<HttpResult<FormListEntity>> fetchFormApplyList({
    CancelToken? cancelToken,
  }) async {
    final result = await dioEngine.requestNetResult(
      ApiConstants.apiFormList,
      method: HttpMethod.GET,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final jsonList = result.getListJson();

      //获取List数据 需要转换一次
      var list = jsonList
          ?.map((value) {
            if (value is Map<String, dynamic>) {
              return FormListEntity.fromJson(value);
            } else {
              return null;
            }
          })
          .where((item) => item != null)
          .cast<FormListEntity>()
          .toList();

      return result.convert<FormListEntity>(list: list);
    }
    return result.convert<FormListEntity>();
  }

  /// 已发布的表单列表
  Future<HttpResult<FormSubmittedPageEntity>> fetchFormSubmitList({
    required int curPage,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['page'] = curPage.toString();
    params['limit'] = "10";

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiFormSubmittedList,
      params: params,
      method: HttpMethod.GET,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = FormSubmittedPageEntity.fromJson(json!);
      return result.convert<FormSubmittedPageEntity>(data: data);
    }
    return result.convert();
  }

  /// 已批准的表单列表
  Future<HttpResult<FormSubmittedPageEntity>> fetchFormApproveList({
    required int curPage,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['page'] = curPage.toString();
    params['limit'] = "10";

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiFormApprovedList,
      params: params,
      method: HttpMethod.GET,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = FormSubmittedPageEntity.fromJson(json!);
      return result.convert<FormSubmittedPageEntity>(data: data);
    }
    return result.convert();
  }

  /// 已拒绝的表单列表
  Future<HttpResult<FormSubmittedPageEntity>> fetchFormRejectList({
    required int curPage,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['page'] = curPage.toString();
    params['limit'] = "10";

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiFormRejectedList,
      params: params,
      method: HttpMethod.GET,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = FormSubmittedPageEntity.fromJson(json!);
      return result.convert<FormSubmittedPageEntity>(data: data);
    }
    return result.convert();
  }

  /// 获取表单的选项
  Future<HttpResult<FormOptionEntity>> fetchFormOption({
    required String? typeId,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['type_id'] = typeId ?? "";

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiFormOption,
      params: params,
      method: HttpMethod.GET,
      isShowLoadingDialog: true,
      networkDebounce: true,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = FormOptionEntity.fromJson(json!);
      return result.convert<FormOptionEntity>(data: data);
    }
    return result.convert();
  }

  /// 上传表单
  Future<HttpResult<FormOrderEntity>> submitForm({
    required String? estateFormId,
    required String? typeId,
    required FormContentEntity content,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    Map<String, String> paths = {};
    params['estate_online_form_id'] = estateFormId ?? "";

    //选择参数添加
    if (Utils.isNotEmpty(content.typeOfApplication)) {
      params["type_of_application"] = content.typeOfApplication!;
    }

    if (Utils.isNotEmpty(content.notesToRecipient)) {
      params["notes_to_recipient"] = content.notesToRecipient!;
    }

    if (Utils.isNotEmpty(content.notesToManagement)) {
      params["notes_to_management"] = content.notesToManagement!;
    }

    if (Utils.isNotEmpty(content.ownershipStatus)) {
      params["ownership_status"] = content.ownershipStatus!;
    }

    if (Utils.isNotEmpty(content.vehicleNumber)) {
      params["vehicle_number"] = content.vehicleNumber!;
    }

    if (Utils.isNotEmpty(content.iuNumber)) {
      params["iu_number"] = content.iuNumber!;
    }

    if (Utils.isNotEmpty(content.vehicleMakeModelColour)) {
      params["vehicle_make_model_colour"] = content.vehicleMakeModelColour!;
    }

    if (Utils.isNotEmpty(content.startDate)) {
      params["start_date"] = content.startDate!;
    }

    if (Utils.isNotEmpty(content.endDate)) {
      params["end_date"] = content.endDate!;
    }

    if (Utils.isNotEmpty(content.timeOrArrival)) {
      params["time_or_arrival"] = "${content.timeOrArrival!}:00";
    }

    if (Utils.isNotEmpty(content.movingCompany)) {
      params["moving_company"] = content.movingCompany!;
    }

    if (Utils.isNotEmpty(content.personInCharge)) {
      params["person_in_charge"] = content.personInCharge!;
    }

    if (Utils.isNotEmpty(content.mobileNumber)) {
      params["mobile_number"] = content.mobileNumber!;
    }

    if (Utils.isNotEmpty(content.companyAddress)) {
      params["company_address"] = content.companyAddress!;
    }

    if (Utils.isNotEmpty(content.dateOfEntry)) {
      params["date_of_entry"] = content.dateOfEntry!;
    }

    if (Utils.isNotEmpty(content.guestName)) {
      params["guest_name"] = content.guestName!;
    }

    if (Utils.isNotEmpty(content.guestMobileNumber)) {
      params["guest_mobile_number"] = content.guestMobileNumber!;
    }

    if (Utils.isNotEmpty(content.renovationStartDate)) {
      params["renovation_start_date"] = content.renovationStartDate!;
    }

    if (Utils.isNotEmpty(content.renovationEndDate)) {
      params["renovation_end_date"] = content.renovationEndDate!;
    }

    if (Utils.isNotEmpty(content.hackingStartDate)) {
      params["hacking_start_date"] = content.hackingStartDate!;
    }

    if (Utils.isNotEmpty(content.hackingEndDate)) {
      params["hacking_end_date"] = content.hackingEndDate!;
    }

    if (Utils.isNotEmpty(content.renovationCompany)) {
      params["renovation_company"] = content.renovationCompany!;
    }

    if (Utils.isNotEmpty(content.listOfRenovationWorks)) {
      params["list_of_renovation_works"] = content.listOfRenovationWorks!;
    }

    //attachments 添加
    if (content.attachments != null && content.attachments!.isNotEmpty) {
      content.attachments!.asMap().forEach((index, path) {
        paths["attachments[$index]"] = path;
      });
    }

    //signature 添加使用 ByteData 数据
    Map<String, Uint8List> streams = {};
    if (content.signatureByteData != null && content.signatureByteData is ByteData) {
      streams["signature"] = (content.signatureByteData as ByteData).buffer.asUint8List();
    }

    final result = await dioEngine.requestNetResult(
      "${ApiConstants.apiFormSubmit}$typeId",
      params: params,
      paths: paths,
      pathStreams: streams,
      method: HttpMethod.POST,
      networkDebounce: true,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = FormOrderEntity.fromJson(json!);
      return result.convert<FormOrderEntity>(data: data);
    }
    return result.convert();
  }

  /// 获取表单的详情数据
  Future<HttpResult<FormDetailEntity>> fetchFormDetail({
    required String? estateFormId,
    required String? taskId,
    CancelToken? cancelToken,
  }) async {
    Map<String, String> params = {};
    params['estate_online_form_id'] = estateFormId ?? "";
    params['id'] = taskId ?? "";

    final result = await dioEngine.requestNetResult(
      ApiConstants.apiFormDetail,
      params: params,
      method: HttpMethod.GET,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      final json = result.getDataJson();
      var data = FormDetailEntity.fromJson(json!);
      return result.convert<FormDetailEntity>(data: data);
    }
    return result.convert();
  }

}
