import 'dart:io';

import 'package:electronic_assistant/base/base_controller.dart';
import 'package:electronic_assistant/resource/string.gen.dart';
import 'package:electronic_assistant/utils/audio_picker_utils.dart';
import 'package:electronic_assistant/utils/error_handler.dart';
import 'package:electronic_assistant/utils/file_upload_check_helper.dart';
import 'package:electronic_assistant/utils/toast_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:uuid/uuid.dart';

import '../../data/bean/talks.dart';
import '../../data/repositories/talk_repository.dart';
import '../../dialog/alert_dialog.dart';
import '../../resource/colors.gen.dart';
import '../talk/view.dart';

class AudioPickerController extends BaseController {
  final audioList = RxList<AssetEntity>();
  AssetPathEntity? currentPath;

  final _currentEntity = Rxn<AssetEntity?>();

  AssetEntity? get currentEntity => _currentEntity.value;
  final refreshController = RefreshController(initialRefresh: false);

  int limit = 20;

  int totalCount = 0;

  @override
  void onReady() async {
    super.onReady();
    bool isGrant = await checkFilePermission();
    if (!isGrant) {
      _onRecordPermissionDenied();
      return;
    }
    _initAudioPathList();
  }

  void _initAudioPathList() async {
    currentPath = await initPathEntity();
    totalCount = await currentPath?.assetCountAsync ?? 0;
    requestList(0, limit, isClearAll: true);
  }

  Future<bool> checkFilePermission({void Function()? requestPermission}) async {
    if (!await AudioPickerUtils.hasPermission()) {
      bool isAllow = await _showRequestPermissionDialog();
      if (isAllow) {
        bool permission = await AudioPickerUtils.requestPermissionExtend();
        if (!permission) {
          return false;
        } else {
          requestPermission?.call();
        }
      } else {
        return false;
      }
    }
    return true;
  }

  _onRecordPermissionDenied() {
    ToastUtil.showToast(StringName.authorizationFailed.tr);
  }

  Future<bool> _showRequestPermissionDialog() async {
    bool? isAllow = await EAAlertDialog.show(
        contentWidget: Container(
          margin: EdgeInsets.only(top: 16.h),
          child: Text(
            textAlign: TextAlign.center,
            '是否允许小听获取此设备的存储权限，为您提供转文字、智能总结服务？',
            style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 15.sp,
                color: ColorName.primaryTextColor),
          ),
        ),
        cancelText: '禁止',
        confirmText: '允许',
        cancelOnTap: () {
          EAAlertDialog.dismiss(result: false);
        },
        confirmOnTap: () {
          EAAlertDialog.dismiss(result: true);
        });
    return isAllow ?? false;
  }

  void requestList(int offset, int limit, {bool? isClearAll = false}) {
    if (currentPath == null) {
      return;
    }
    AudioPickerUtils.getAssetListRange(currentPath!, offset, limit)
        .then((list) {
      if (isClearAll == true) {
        audioList.clear();
      }
      audioList.addAll(list);
      if (audioList.length >= totalCount) {
        debugPrint("getAssetListRange-没有更多数据了");
        refreshController.loadNoData();
      } else {
        refreshController.loadComplete();
      }
      refreshController.refreshCompleted();
    }).catchError((error) {
      debugPrint("requestTalkData-catchError-$error");
      refreshController.loadFailed();
      refreshController.refreshFailed();
    });
  }

  Future<AssetPathEntity?> initPathEntity() async {
    List<AssetPathEntity> listEntity =
        await AudioPickerUtils.getAssetPathList();
    if (listEntity.isEmpty) {
      return null;
    }
    return listEntity.first;
  }

  void onItemClick(AssetEntity entity) {
    _currentEntity.value = entity;
  }

  void onImportClick() async {
    AssetEntity? entity = _currentEntity.value;
    if (entity == null) {
      ToastUtil.showToast(StringName.pleaseChoiceLocalAudioFile.tr);
      return;
    }
    File? file = await entity.file;
    if (file == null) {
      ToastUtil.showToast('文件不存在');
      return;
    }
    //文件格式是否允许
    if (!FileUploadCheckHelper.isAllowAudioFile(file.path)) {
      ToastUtil.showToast(StringName.audioNotSupportType.tr);
      return;
    }
    //文件大小不能超过500M
    if (file.lengthSync() > 500 * 1024 * 1024) {
      ToastUtil.showToast(StringName.fileChoiceSizeLimit.tr);
      return;
    }
    //录音时长不能超过5小时不能低于3s
    if (entity.duration < 3) {
      ToastUtil.showToast(StringName.recordingDurationCannotLessThan3s.tr);
      return;
    }
    if (entity.duration > 5 * 60 * 60) {
      ToastUtil.showToast(StringName.fileAudioDurationLimit.tr);
      return;
    }

    //上传文件
    try {
      TalkBean bean = await talkRepository.talkCreate(
          const Uuid().v4(), entity.duration,
          localAudioUrl:
              FileUploadCheckHelper.joinUploadServerAudioTag(entity.id),
          uploadType: FileUploadType.local);
      Get.back();
      TalkPage.start(bean);
    } catch (e) {
      ErrorHandler.toastError(e);
    }
  }

  void onLoadMoreData() {
    requestList(audioList.length, limit);
  }

  void pickSystemFile() async {
    bool isGrant = await checkFilePermission(requestPermission: () {
      _initAudioPathList();
    });
    if (!isGrant) {
      _onRecordPermissionDenied();
      return;
    }
    FileUploadCheckHelper.choicePlatformLocalFileAndCreateOrder(
        choiceSuccessCallback: () {
      Get.back();
    });
  }
}
