import 'package:ffmpeg_kit_flutter_audio/ffmpeg_kit.dart';
import 'package:ffmpeg_kit_flutter_audio/ffmpeg_session.dart';
import 'package:ffmpeg_kit_flutter_audio/return_code.dart';
import 'package:get/get.dart';
import 'package:tone_snap/ads/interstitial_ad_manager.dart';
import 'package:tone_snap/components/base_easyloading.dart';
import 'package:tone_snap/data/models/voice_model.dart';
import 'package:tone_snap/data/storage/my_voice_box.dart';
import 'package:tone_snap/generated/assets.dart';
import 'package:tone_snap/modules/sidea/controllers/player_controller.dart';
import 'package:tone_snap/modules/sidea/initial/initial_controller.dart';
import 'package:tone_snap/routes/app_routes.dart';
import 'package:tone_snap/utils/date_util.dart';
import 'package:tone_snap/utils/file_util.dart';
import 'package:tone_snap/utils/local_path_util.dart';
import 'package:tone_snap/utils/log_util.dart';
import 'package:tone_snap/utils/obj_util.dart';

class ChangeVoiceController extends GetxController {
  var timberList = [
    // Timber('Child', Assets.coverChild, 1.3, 1.1),
    // Timber('Boy', Assets.coverBoy, 1.2, 1.1),
    // Timber('Man', Assets.coverMan, 0.9, 1.1),
    // Timber('Elder', Assets.coverElder, 0.75, 1.333),
    // Timber('Robot', Assets.coverRobot, 1.0, 1.5),
    // Timber('Girl', Assets.coverGirl, 1.5, 0.6667),
    // Timber('Sexy', Assets.coverSexy, 1.25, 0.8),
    // Timber('Woman', Assets.coverWoman, 1.25, 0.8),
    // Timber('Monsters', Assets.coverMonsters, 0.7, 1.1),

    Timber('Original', Assets.coverOriginal, 1.0, 1.0, check: true),
    Timber('Fast', Assets.coverFast, 1.0, 1.5),
    Timber('Slow', Assets.coverSlow, 1.0, 0.5),
    Timber('Flash', Assets.coverFlash, 1.0, 2.0),
    Timber('Baby', Assets.coverChild, 1.3, 0.76),
    Timber('Robot', Assets.coverRobot, 1.0, 1.25),
    Timber('Monsters', Assets.coverMonsters, 0.60, 1.1),
    Timber('DIY', Assets.coverDIY, 1.0, 1.0),
  ].obs;
  var currentIndex = 0.obs;
  final playerController = PlayerController.to;
  var toneValue = 1.0.obs;
  var soundSpeedValue = 1.0.obs;
  late String filePath;

  @override
  void onInit() {
    super.onInit();
    InterstitialAdManager().loadAd();

    filePath = Get.arguments;
    // playerController.setFilePath(filePath);
  }

  @override
  void onClose() async {
    // if (Platform.isAndroid) await playerController.setPitch(1.0);
    // await playerController.setSpeed(1.0);
    // playerController.stopPlay();
    super.onClose();
  }

  void onTapItem(Timber item, int index) {
    for (var e in timberList) {
      // e == item ? item.check = !item.check : e.check = false;
      e.check = false;
    }
    item.check = true;
    currentIndex.value = index;
    toneValue.value = item.check ? item.tone : 1.0;
    soundSpeedValue.value = item.check ? item.soundSpeed : 1.0;
    // if (Platform.isAndroid) playerController.setPitch(toneValue.value);
    // playerController.setSpeed(soundSpeedValue.value);
    timberList.refresh();
  }

  /// 开始/暂停播放
  Future<void> togglePlayback() async {
    if (playerController.isPlaying.value) {
      await playerController.pausePlay();
    } else {
      await playerController.startPlay();
    }
  }

  void onChanged(double value, int type) {
    // var item = timberList.firstWhereOrNull((e) => e.check);
    if (type == 0) {
      toneValue.value = value;
      // if (Platform.isAndroid) playerController.setPitch(toneValue.value);
      // if (item?.tone.toString() != NumUtil.formatNum(value)) {
      //   item?.check = false;
      //   timberList.refresh();
      // }
    } else {
      soundSpeedValue.value = value;
      // playerController.setSpeed(soundSpeedValue.value);
      // if (item?.soundSpeed.toString() != NumUtil.formatNum(value)) {
      //   item?.check = false;
      //   timberList.refresh();
      // }
    }
  }

  /// 保存
  Future<void> save() async {
    // 显示插页广告
    InterstitialAdManager().showAdIfAvailable(
      onTap: () async {
        // 停止播放
        if (playerController.isPlaying.value) playerController.stopPlay();
        BaseEasyLoading.loading();

        try {
          // 若是assets路径，转换为文件路径
          if (filePath.contains('assets')) {
            filePath = await FileUtil.getAssetsToFilePath(filePath);
          }

          // 输出目录
          final outputDir = await LocalPathUtil.getVoiceChangeOutputDir();
          String fileName = '${DateUtil.getNowTimeStr().replaceAll(' ', '_')}_output.mp3';
          String outputPath = '${outputDir.path}/$fileName';

          var filter = "";
          // var timber = timberList.firstWhereOrNull((e) => e.check);
          // if (timber != null) {
          //   int index = timberList.indexOf(timber);
          //   if (index == 5) filter = ",afftdn=nf=-30";
          // }

          if (currentIndex.value == 5) filter = ",afftdn=nf=-30,aecho=0.8:0.88:60:0.4";

          // 获取原始采样率
          String sampleRate = await _getSampleRate() ?? '24000';

          // 构建 FFmpeg 命令
          final String command = '-i $filePath -af "asetrate=$sampleRate*${toneValue.value},atempo=${soundSpeedValue.value}$filter" $outputPath';

          // 执行 FFmpeg 命令
          FFmpegSession session = await FFmpegKit.execute(command);

          // 获取执行结果
          final returnCode = await session.getReturnCode();
          if (ReturnCode.isSuccess(returnCode)) {
            LogUtil.d('Audio processing successful');
            try {
              await MyVoiceBox().addData(VoiceModel(name: fileName, path: outputPath));
              BaseEasyLoading.toast('Save successful');

              // 回到首页-我的页面
              Get.until((route) => route.settings.name == AppRoutes.initialA);
              InitialController.to.onBottomAppBarItemChanged(2);
            } catch (e) {
              BaseEasyLoading.toast('Save failed');
            }
          } else {
            LogUtil.d('Audio processing failed');
            BaseEasyLoading.toast('Audio processing failed');
          }
        } catch (e) {
          BaseEasyLoading.toast('Audio processing failed');
        }
      },
    );
  }

  /// 获取音频的采样率
  Future<String?> _getSampleRate() async {
    String? sampleRate;
    String ffmpegCommand = '-i $filePath';
    FFmpegSession session = await FFmpegKit.execute(ffmpegCommand);
    final output = await session.getOutput();
    if (ObjUtil.isNotEmpty(output)) {
      // 使用正则表达式提取采样率
      final regex = RegExp(r'(\d+) Hz');
      final match = regex.firstMatch(output!);
      if (match != null) {
        sampleRate = match.group(1);
        LogUtil.d('采样率: $sampleRate Hz');
      } else {
        LogUtil.e('未找到采样率');
      }
    } else {
      LogUtil.e('获取采样率失败');
    }
    return sampleRate;
  }
}

class Timber {
  late final String name;
  late final String cover;
  late final double tone;
  late final double soundSpeed;
  bool check;

  Timber(this.name, this.cover, this.tone, this.soundSpeed, {this.check = false});
}