part of user_edit_note;

class UserEditNoteController extends GetxController {

  final NoteModel model;
  final String bookId;
  late TextEditingController contentInput;
  UserEditNoteController(this.model,this.bookId){
    _setDuration();
    contentInput = TextEditingController(text: model.noteContent?.text?.content);
  }

  // 录音
  final FlutterSoundRecorder _mRecorder = FlutterSoundRecorder();
  just_audio.AudioPlayer audioPlayer = just_audio.AudioPlayer();
  // 录音开始
  bool startRecording = false;
  // 笔记是否公开
  bool isPublic = false;

  bool initRecorder = false;

  String currentDuration = '';

  late MediaModel currentPlayMediaModel = MediaModel();

  @override
  void onInit() {
    isPublic = model.isOpen ==1?true:false;
    super.onInit();
  }

  @override
  void onClose() {
    contentInput.dispose();
    audioPlayer.dispose();
    Tools.unfocus();
    super.onClose();
  }

  // 设置笔记是否公开
  void setIsPublic(){
    isPublic = !isPublic;
    update();
  }
  // 配置音频时长
  void _setDuration() async {
    for(MediaModel mediaModel in model.noteContent!.audio!){
      Duration? duration = await just_audio.AudioPlayer().setUrl(mediaModel.content??'');

      mediaModel.duration = Tools.formatDuration(duration!);
    }
    update();
  }

  // 删除图片
  void delImage(MediaModel mediaModel){
     model.noteContent!.image!.remove(mediaModel);
     update();
  }
  // 删除音频
  void delAudio(MediaModel mediaModel){
    model.noteContent!.audio!.remove(mediaModel);
    // 新加的录音 如果删除要删除源文件
    if(mediaModel.id == 0){

    }
    update();
  }

  // 添加音频
  void addAudio(String path,String duration){
    MediaModel mediaModel = MediaModel(path: path,id: 0,duration: duration);
    model.noteContent!.audio!.add(mediaModel);
    update();
  }
  // 添加图片
  void addImage(String path){
    MediaModel mediaModel = MediaModel(path: path,id: 0);
    model.noteContent!.image!.add(mediaModel);
    update();
  }

  // 初始化录音组件
  Future<void> openTheRecorder() async {
    if(!initRecorder){
      // 获取权限
      if(await Access.microphone()){
        await _mRecorder.openRecorder();
        final session = await AudioSession.instance;
        await session.configure(AudioSessionConfiguration(
          avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,
          avAudioSessionCategoryOptions:
          AVAudioSessionCategoryOptions.allowBluetooth |
          AVAudioSessionCategoryOptions.defaultToSpeaker,
          avAudioSessionMode: AVAudioSessionMode.spokenAudio,
          avAudioSessionRouteSharingPolicy:
          AVAudioSessionRouteSharingPolicy.defaultPolicy,
          avAudioSessionSetActiveOptions: AVAudioSessionSetActiveOptions.none,
          androidAudioAttributes: const AndroidAudioAttributes(
            contentType: AndroidAudioContentType.speech,
            flags: AndroidAudioFlags.none,
            usage: AndroidAudioUsage.voiceCommunication,
          ),
          androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
          androidWillPauseWhenDucked: true,
        ));
      }
      // 没有权限
      else {

      }
    }
    initRecorder = true;
  }

  // 开启录音
  void record() async {
    openTheRecorder();
    update();
    startRecording = true;
    String filePath = await Tools.getDirectory();
    String fileName = Tools.generateVoiceFileName();

    _mRecorder.startRecorder(
      toFile: '$filePath/$fileName',
      audioSource: sound_recorder_platform.AudioSource.microphone,
      codec: Codec.aacMP4,

    );
  }
  // 停止录音
  void stopRecorder() async{

    startRecording = false;
    final path = await _mRecorder.stopRecorder();
    var duration = await audioPlayer.setFilePath(path!);
    print('-----duration---------------------$duration------');

    // 添加到数组
    addAudio(path, Tools.formatDuration(duration!));
  }

  // 播放音频
  void playAudio(MediaModel mediaModel){
    if(audioPlayer.playerState.playing){
      audioPlayer.stop();
      mediaModel.currentDuration = '0:00:00';
      // if(currentPlayMediaModel.id == mediaModel.id){
      //   return;
      // }
    }
    // 本地音频
    if (mediaModel.id == 0){
      audioPlayer.setFilePath(mediaModel.path);
    }
    // 远程音频
    else {
      audioPlayer.setUrl(mediaModel.content??'');
    }
    audioPlayer.play();
    StreamSubscription? positionSubscription;
    positionSubscription =audioPlayer.positionStream.listen((position) {
      String temp =  Tools.formatDuration(position);
      Console.log('播放时间---------------------$temp------id-------------${mediaModel.id}');
      mediaModel.currentDuration = temp;
      if(position >= audioPlayer.duration!){
        Console.log('---------播放结束-----------');
        positionSubscription?.cancel();
      }
      update();
    });
    // currentPlayMediaModel = mediaModel;
  }

  // 上传文件
  Future<String> upload({
    required String path
  }) async {
    // String result  = await CommonAPI.upload(path:path,fileTypes: 'comment');
    // return result;
    OssTool tool = OssTool('zxts-comment-file');
    final response = await tool.putObjectFile(path);
    print('------response--------------------------${response.realUri}');
    return response.realUri.toString();
  }

  // 提交
  Future<bool> submit() async {
    CustomToast.loading();
    // 循环上传图片获取地址
    for(MediaModel mediaModel in model.noteContent!.image!){
      if (mediaModel.id == 0){
        final url = await upload(path: mediaModel.path);
        mediaModel.content = url;
      }
    }

    // 循环上传音频获取地址
    for(MediaModel mediaModel in model.noteContent!.audio!){
      if (mediaModel.id == 0){
        final url = await upload(path: mediaModel.path);
        mediaModel.content = url;
      }
    }
    CustomToast.dismiss();

    // 组织图片
    List<Map> images = [];
    for(MediaModel mediaModel in model.noteContent!.image!){
     images.add( mediaModel.toJson());
    }

    // 组织音频
    List<Map> audios = [];
    for(MediaModel mediaModel in model.noteContent!.audio!){
      audios.add( mediaModel.toJson());
    }

    model.noteContent!.text!.content = contentInput.text;
    Map<String,dynamic> contentMap = {
      'text':model.noteContent!.text!.toJson(),
      'audio':audios,
      'image':images
    };

    String isOpen = '0';
    if(isPublic){
      isOpen = '1';
    }

    final result = MineAPI.editNotes(
        content: model.content??'',
        notesId: model.notesId.toString(),
        bookId: bookId,
        noteContent: jsonEncode(contentMap),
        isOpen: isOpen
    );
    return result;
  }


}