import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:get/get.dart';
import 'package:o2oa_all_platform/common/index.dart';
import 'package:path_provider/path_provider.dart';

import '../index.dart';


class ImVoiceRecordToolView extends StatefulWidget {
  const ImVoiceRecordToolView({Key? key}) : super(key: key);

  @override
  _ImVoiceRecordToolViewState createState() => _ImVoiceRecordToolViewState();
}

class _ImVoiceRecordToolViewState extends State<ImVoiceRecordToolView>  {
  /// 录音
  FlutterSoundRecorder? _myRecorder = FlutterSoundRecorder();
  bool _mRecorderIsInited = false;
  String _mPath = "";
  final _maxLength = 60;// 最长录音时间60秒
  int _recordSecond = 0;
  StreamSubscription? _mRecordingDataSubscription;

  ImChatController imChatController = Get.find();

  /// ui
  String title = 'im_chat_tools_voice'.tr;

  @override
  void initState() {
    initTheRecorder();
    super.initState();
  }
  @override
  void dispose() {
    _myRecorder?.closeRecorder();
    _myRecorder = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.all(10),
        child: Column(
          children: [
            Text(title, style: Theme.of(context).textTheme.bodyMedium),
            const SizedBox(height: 10),
            GestureDetector(
              onTapDown: (x) =>_startRecorder(),
              onTapUp: (x) =>_stopRecorder(),
              onTapCancel: ()=>_stopRecorder(),
              child: Container(
                decoration: BoxDecoration(
                    border: Border.all(color: Theme.of(context).colorScheme.onBackground),
                    borderRadius: const BorderRadius.all(Radius.circular(100))),
                width: 95,
                height: 95,
                child: const Center(
                  child: Icon(Icons.mic, size: 36)
                  
                  // AssetsImageView(
                  //   'chat_iicon_yuyin.png',
                  //   width: 36,
                  //   height: 36,
                  // ),
                ))
            ),

            
          ],
        ));
  }

  /// 
  Future<void> initTheRecorder() async {
    // 检查录音权限
    var isPermission = await O2Utils.microphonePermission();
    if (!isPermission) {
      OLogger.e('没有权限，无法录音');
      Loading.showError('im_chat_error_need_record_permission'.tr);
      return;
    }
    // 开启录音工具
    await _myRecorder?.openRecorder();
    //设置订阅计时器
    await _myRecorder?.setSubscriptionDuration(const Duration(milliseconds: 10));
    // 初始化录音路径
    var tempDir = await getTemporaryDirectory();
    _mPath = '${tempDir.path}/o2_record_voice.aac';
    setState(() {
      _mRecorderIsInited = true;
    });
  }
 

  Future<void> _startRecorder() async {
    if (!_mRecorderIsInited) {
      Loading.showError('im_chat_error_record_not_init'.tr);
      return;
    }
    // 初始化数字
    _recordSecond = 0;
    // 初始化文件
    var outputFile = File(_mPath);
    if (outputFile.existsSync()) {
      await outputFile.delete();
    }

    _myRecorder?.startRecorder(
      toFile: _mPath,
      codec: Codec.aacADTS,
    );
     /// 监听录音
    _mRecordingDataSubscription = _myRecorder?.onProgress?.listen((e) {
        var date = DateTime.fromMillisecondsSinceEpoch(
            e.duration.inMilliseconds,
            isUtc: true);
        OLogger.d("$date");
        var txt = date.hms();
        _recordSecond = date.second;//
        //设置了最大录音时长
        if (date.second >= _maxLength) {
          _stopRecorder();
          return;
        }
        setState(() {
          //更新录音时长
          title = txt;
        });
      });
      
      /// 正在录音

  }

  Future<void> _stopRecorder() async {
    await _myRecorder!.stopRecorder().then((value) {
     _cancelRecorderSubscriptions();
    });
    OLogger.d("record time $_recordSecond");
    if (_recordSecond < 1) {
      Loading.showError('im_chat_error_record_time_too_short'.tr);
    } else {
      _sendMsg();
    }
    setState(() {
      //更新录音时长
      title = 'im_chat_tools_voice'.tr;
    });
  }

  ///
  /// 发送消息
  /// 
  Future<void> _sendMsg() async {
    imChatController.uploadAndSendVoiceMsg(_mPath, _recordSecond);
  }

/// 取消录音监听
void _cancelRecorderSubscriptions() {
  if (_mRecordingDataSubscription != null) {
    _mRecordingDataSubscription?.cancel();
    _mRecordingDataSubscription = null;
  }
}
   
}

/// 
/// 语音消息发送工具
/// 
class ImVoiceRecordToolWidget extends GetView<ImChatController> {
  const ImVoiceRecordToolWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.all(10),
        child: Column(
          children: [
            Text('im_chat_tools_voice'.tr, style: Theme.of(context).textTheme.bodyMedium),
            const SizedBox(height: 10),
            Container(
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.white),
                    borderRadius: const BorderRadius.all(Radius.circular(100))),
                width: 95,
                height: 95,
                child: const Center(
                  child: Icon(Icons.mic, size: 36)
                ))
          ],
        ));
  }
}
