import 'package:cpt_main/modules/main/main_page.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:domain/repository/main_repository.dart';
import 'package:flutter/cupertino.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:riverpod_annotation/riverpod_annotation.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/date_time_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/picker/date_picker_util.dart';

import 'visitor_register_state.dart';

part 'visitor_register_view_model.g.dart';

@riverpod
class VisitorRegisterViewModel extends _$VisitorRegisterViewModel with DioCancelableMixin {
  late final MainRepository _mainRepository;

  @override
  VisitorRegisterState build() {
    _mainRepository = ref.read(mainRepositoryProvider);
    final state = VisitorRegisterState();
    initListener(state);
    registerCancellation(callback: () {
      onDispose(state);
    });
    return state;
  }

  //提交表单
  void submitVisitorRegister() async {
    state = state.copyWith(
      fullNameErrorText: null,
      phoneErrorText: null,
      nricErrorText: null,
    );

    final FocusNode fullNameFocusNode = state.formData['full_name']!['focusNode'];
    final FocusNode phoneFocusNode = state.formData['phone']!['focusNode'];
    final FocusNode nricFocusNode = state.formData['nric']!['focusNode'];
    final FocusNode plateNumberFocusNode = state.formData['plate_number']!['focusNode'];
    final FocusNode noteFocusNode = state.formData['note']!['focusNode'];

    fullNameFocusNode.unfocus();
    phoneFocusNode.unfocus();
    nricFocusNode.unfocus();
    plateNumberFocusNode.unfocus();
    noteFocusNode.unfocus();

    final TextEditingController fullNameController = state.formData['full_name']!['controller'];
    final TextEditingController phoneController = state.formData['phone']!['controller'];
    final TextEditingController nricController = state.formData['nric']!['controller'];
    final TextEditingController plateNumberController = state.formData['plate_number']!['controller'];
    final TextEditingController noteController = state.formData['note']!['controller'];

    final fullName = fullNameController.text;
    final phone = phoneController.text;
    final nric = nricController.text;
    final plateNumber = plateNumberController.text;
    final note = noteController.text;
    final accessDate = state.accessDate == null ? null : DateTimeUtils.formatDate(state.accessDate!, format: 'yyyy-MM-dd');

    Log.d('当前待提交的 fullName:$fullName phone:$phone nric:$nric plateNumber:$plateNumber note:$note accessDate:$accessDate');

    if (Utils.isEmpty(fullName)) {
      state = state.copyWith(fullNameErrorText: "Full Name cannot be empty!");
      return;
    }

    if (Utils.isEmpty(phone)) {
      state = state.copyWith(phoneErrorText: "Mobile Number cannot be empty!");
      return;
    }

    if (Utils.isEmpty(nric)) {
      state = state.copyWith(nricErrorText: "NRIC/FIN cannot be empty!");
      return;
    }

    if (Utils.isEmpty(accessDate)) {
      ToastEngine.show("Select Access Date");
      return;
    }

    //执行请求
    final result = await _mainRepository.createVisitor(
      name: fullName,
      phone: phone,
      nric: nric,
      vehicleNumber: plateNumber,
      accessDate: accessDate,
      note: note,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      NotifyEngine.showSuccess(S.current.successful);
      //去首页
      appRouter.maybePop();
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }

  //选择通行时间
  void pickAccessDate() {
    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: state.accessDate ?? DateTime.now(),
      mode: CupertinoDatePickerMode.date,
      onDateTimeChanged: (date) {
        state = state.copyWith(accessDate: date);
      },
      title: S.current.access_date,
    );
  }

  //初始化监听
  void initListener(VisitorRegisterState initState) {
    final FocusNode fullNameFocusNode = initState.formData['full_name']!['focusNode'];
    final FocusNode phoneFocusNode = initState.formData['phone']!['focusNode'];
    final FocusNode nricFocusNode = initState.formData['nric']!['focusNode'];

    fullNameFocusNode.addListener(() {
      // 获取焦点的时候清空错误文本
      if (fullNameFocusNode.hasFocus) {
        state = state.copyWith(fullNameErrorText: null);
      }
    });

    phoneFocusNode.addListener(() {
      // 获取焦点的时候清空错误文本
      if (phoneFocusNode.hasFocus) {
        state = state.copyWith(phoneErrorText: null);
      }
    });

    nricFocusNode.addListener(() {
      // 获取焦点的时候清空错误文本
      if (nricFocusNode.hasFocus) {
        state = state.copyWith(nricErrorText: null);
      }
    });
  }

  //销毁资源
  void onDispose(VisitorRegisterState initState) {
    final FocusNode fullNameFocusNode = initState.formData['full_name']!['focusNode'];
    final FocusNode phoneFocusNode = initState.formData['phone']!['focusNode'];
    final FocusNode nricFocusNode = initState.formData['nric']!['focusNode'];
    fullNameFocusNode.dispose();
    phoneFocusNode.dispose();
    nricFocusNode.dispose();

    Log.d("VisitorRegisterViewModel 销毁 onDispose");
  }
}
