import 'dart:ui';

import 'package:cpt_form/router/page/form_page_router.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:domain/entity/form_content_entity.dart';
import 'package:domain/entity/form_list_entity.dart';
import 'package:domain/repository/form_repository.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:plugin_platform/engine/loading/loading_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/engine/notify/notify_engine.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:plugin_platform/platform_export.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:router/componentRouter/component_service_manager.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/picker/date_picker_util.dart';
import '../../form/form_page.dart';
import '../../form/form_types.dart';
import 'apply_state.dart';
import 'package:widgets/picker/option_pick_util.dart';

part 'apply_view_model.g.dart';

@riverpod
class ApplyViewModel extends _$ApplyViewModel with DioCancelableMixin {
  late final FormRepository _formRepository;

  @override
  ApplyState build() {
    _formRepository = ref.read(formRepositoryProvider);
    final state = ApplyState(formContentDetail: FormContentEntity());
    registerCancellation();
    return state;
  }

  //设置具体的表单类型
  void setFormType(String formType, String? estateFormId, FormListEntity? formItem, bool enableEdit, FormContentEntity? formContent) {
    //初始化 DetailPage 静态数据
    final detail = FormTypes.buildDetailPageMap(enableEdit)[formType];
    if (enableEdit) {
      state = state.copyWith(
        formType: formType,
        detailPage: detail,
        formItem: formItem,
        enableEdit: enableEdit,
        estateFormId: estateFormId ?? formItem?.id,
      );
    } else {
      state = state.copyWith(
        formType: formType,
        detailPage: detail,
        formItem: formItem,
        enableEdit: enableEdit,
        formContentDetail: formContent,
        estateFormId: estateFormId ?? formItem?.id,
      );
    }
  }

  //进入下一步页面
  void gotoNextPage() {
    Log.d("applyViewModelProvider - detailPageIndex:${state.detailPageIndex}");
    bool success = FormTypes.startDetailPageByType(state.detailPage?['detail_pages'], state.detailPageIndex);
    Log.d("applyViewModelProvider - gotoNextPage - success:$success");
    if (!success) {
      FormPage.startInstance();
    } else {
      state.detailPageIndex++;
    }
  }

  //返回的时候处理当前的索引
  void handlePopAction() {
    state.detailPageIndex--;
  }

  //选择一个选项
  void pickOption(bool isApplicationType) async {
    Log.d("当前的optionList：${state.formOption}");
    if (state.formOption == null) {
      //请求接口
      final result = await _formRepository.fetchFormOption(typeId: state.formType, cancelToken: cancelToken);

      if (result.isSuccess) {
        state = state.copyWith(formOption: result.data);
        _showPicker(isApplicationType);
      } else {
        ToastEngine.show(result.errorMsg ?? "UnKnow Error");
      }
    } else {
      _showPicker(isApplicationType);
    }
  }

  //展示分类的PickerView
  void _showPicker(bool isApplicationType) {
    List<String>? list;
    if (isApplicationType) {
      list = state.formOption?.typeOfApplication;
    } else {
      list = state.formOption?.ownershipStatus;
    }

    if (list == null || list.isEmpty) return;

    OptionPickerUtil.showCupertinoOptionPicker(
      items: list,
      initialSelectIndex: 0,
      onPickerChanged: (_, index) {
        final value = list![index];
        if (isApplicationType) {
          updateFormContentDetail((content) {
            content.typeOfApplication = value;
          });
        } else {
          updateFormContentDetail((content) {
            content.ownershipStatus = value;
          });
        }
      },
    );
  }

  //选择一个日期,并回调出去赋值
  void pickDate(DateTime? selectedDate, void Function(DateTime) dateCallback) {
    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: selectedDate ?? DateTime.now(),
      mode: CupertinoDatePickerMode.date,
      onDateTimeChanged: (date) {
        dateCallback.call(date);
      },
      title: S.current.choose_date,
    );
  }

  //选择一个时间 时分秒
  void pickTime(DateTime? selectedDate, void Function(DateTime) dateCallback) {
    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: selectedDate ?? DateTime.now(),
      mode: CupertinoDatePickerMode.time,
      onDateTimeChanged: (date) {
        dateCallback.call(date);
      },
      title: S.current.choose_date,
    );
  }

  /// 更新页面内容状态数据
  void updateFormContentDetail(void Function(FormContentEntity) update) {
    //先创建一个新对象
    final updatedDetail = state.formContentDetail.copyWith();
    //更新新对象的值
    update(updatedDetail);
    //更新State
    state = state.copyWith(formContentDetail: updatedDetail);
  }

  /// 提交Form表单 - 直接支付
  void submitForm() async {
    //支付流程 Loading 开始
    LoadingEngine.show();

    //调用接口生成订单
    final result = await _formRepository.submitForm(
      estateFormId: state.estateFormId,
      typeId: state.formType,
      content: state.formContentDetail,
      cancelToken: cancelToken,
    );

    LoadingEngine.dismiss();

    if (result.isSuccess) {
      String orderId = result.data?.order?.id ?? "";
      Log.d("当前Form生成的订单ID:$orderId");

      // 暂时直接进入线下支付页面
      gotoNextPage();

      // //调用支付服务
      // bool success = await ComponentServiceManager().paymentService.executePayment(orderId: orderId);
      //
      // //支付流程 Loading 结束
      // LoadingEngine.dismiss();
      //
      // //如果支付成功，走下一步流程
      // if (success) {
      //   gotoNextPage();
      // } else {
      //   //如果失败需要关闭到跟页面，并且跳转到详情的支付页面
      //   appRouter.pushAndPopUntil(
      //     FormDetailPageRoute(estateFormId: state.estateFormId ?? "", taskId: result.data?.id ?? "", type: state.formType ?? ""),
      //     predicate: (route) {
      //       return route.settings.name == 'FormPageRoute';
      //     },
      //   );
      // }

    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }
}
