import 'dart:convert';
import 'dart:io';

import 'package:domain/repository/auth_repository.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:plugin_platform/engine/directory/directory_util.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:shared/utils/log_utils.dart';

import 'verify_code_state.dart';

class VerifyCodeViewModel extends AutoDisposeNotifier<verifyCodeState> with DioCancelableMixin {
  late final AuthRepository authRepository;

  @override
  verifyCodeState build() {
    authRepository = ref.read(authRepositoryProvider);

    final state = verifyCodeState();

    registerCancellation(callback: () {
      _clearCachedImage();
    });
    return state;
  }

  ///获取验证码
  void fetchCode() async {
    final result = await authRepository.fetchCaptchaImage(cancelToken: cancelToken);

    // 获取 Base64 字符串并去掉前缀
    String base64String = result.data?.img ?? '';
    String fileExtension = ''; // 用于保存文件扩展名

    // 检查图像类型并去掉正确的前缀
    if (base64String.startsWith('data:image/jpeg;base64,')) {
      base64String = base64String.replaceFirst('data:image/jpeg;base64,', '');
      fileExtension = '.jpg'; // 设置文件扩展名为 .jpg
    } else if (base64String.startsWith('data:image/png;base64,')) {
      base64String = base64String.replaceFirst('data:image/png;base64,', '');
      fileExtension = '.png'; // 设置文件扩展名为 .png
    } else {
      // 如果图像格式不支持，可以显示错误信息
      ToastEngine.show("Unsupported image format");
      return;
    }

    try {
      // Base64 转为本地图片缓存
      final bytes = base64.decode(base64String);
      final tempDir = DirectoryUtil.getTempPath();
      final file = File('$tempDir/verify${DateTime.now().millisecondsSinceEpoch}$fileExtension'); // 使用正确的文件扩展名
      await file.writeAsBytes(bytes);
      Log.d('存入的File路径为：${file.path}');

      if (result.isSuccess) {
        state = state.copyWith(key: result.data?.key, imgFilePath: file.path);
      } else {
        ToastEngine.show(result.errorMsg ?? "Unknown Error");
      }
    } catch (e) {
      Log.e('Error decoding Base64 image: $e');
      ToastEngine.show("Error decoding image");
    }
  }

  // 清除缓存的verify验证图形码的缓存文件
  Future<void> _clearCachedImage() async {
    final cacheDir = await DirectoryUtil.initTempDir();
    if (cacheDir != null) {
      if (await cacheDir.exists()) {
        //遍历删除 Cache 目录下面的全部文件或文件夹
        for (final entity in cacheDir.listSync()) {
          // 如果是指定的文件直接删除
          if (entity is File && entity.path.split('/').last.startsWith("verify")) {
            await entity.delete();
          }
        }
      }
    }
  }
}

final verifyCodeProvider = NotifierProvider.autoDispose<VerifyCodeViewModel, verifyCodeState>(VerifyCodeViewModel.new);
