import 'dart:io';

import 'package:electronic_assistant/data/api/atmob_api.dart';
import 'package:electronic_assistant/data/api/atmob_file_api.dart';
import 'package:electronic_assistant/data/api/request/talk_create_request.dart';
import 'package:electronic_assistant/data/api/request/talk_delete_request.dart';
import 'package:electronic_assistant/data/api/request/talk_file_request.dart';
import 'package:get/get.dart';
import '../../utils/http_handler.dart';
import '../api/request/talk_generate_request.dart';
import '../api/request/talk_paginate_request.dart';
import '../api/request/talk_rename_request.dart';
import '../api/request/talk_request.dart';
import '../api/response/talk_check_electric_response.dart';
import '../api/response/talk_info_response.dart';
import '../api/response/talk_paginate_response.dart';
import '../bean/talk_original.dart';
import '../bean/talks.dart';
import 'account_repository.dart';

class TalkRepository {
  TalkRepository._();

  final Set<String> _uploadingTalkIds = {};

  final _talkList = RxList<TalkBean>();

  RxList<TalkBean> get talkList => _talkList;

  bool isUploadingTalk(String talkId) {
    return _uploadingTalkIds.contains(talkId);
  }

  void renovateTalkData(TalkBean talkInfo) {
    for (int i = 0; i < _talkList.length; i++) {
      if (_talkList[i].id == talkInfo.id) {
        _talkList[i].updateBean(talkInfo);
        break;
      }
    }
  }

  void setTalkList(List<TalkBean> list) {
    _talkList.assignAll(list);
  }

  void addNewTalkData(TalkBean talkInfo) {
    _talkList.insert(0, talkInfo);
  }

  clearTalkList() {
    _talkList.clear();
  }

  Future<TalkPaginateResponse> requestHomeTalkData(
      {int pageSize = 10, int? sortType = 1}) {
    return requestTalkPagePaginate(1, pageSize, sortType: sortType);
  }

  Future<TalkPaginateResponse> requestTalkPagePaginate(int page, int pageSize,
      {String? searchKeyword, int? sortType = 1}) {
    return talkPagePaginate(page, pageSize,
            searchKeyword: searchKeyword, sortType: sortType)
        .then((response) {
      if (page == 1) {
        _talkList.clear();
      }
      if (response.list != null) {
        _talkList.addAll(response.list!);
      }
      return response;
    });
  }

  ///sortType 1：按创建时间倒序 2：按更新时间倒序
  Future<TalkPaginateResponse> talkPagePaginate(int page, int pageSize,
      {String? searchKeyword, int? sortType = 1}) {
    return atmobApi
        .talkPagePaginate(TalkPaginateRequest(page, pageSize,
            searchKeyword: searchKeyword, sortType: sortType))
        .then(HttpHandler.handle(false));
  }

  Future<List<TalkOriginal>> talkOriginal(String? talkId) {
    return atmobApi
        .talkOriginal(
            TalkRequest(talkId, isExample: !accountRepository.isLogin.value))
        .then(HttpHandler.handle(false))
        .then((data) {
      if (data.list != null) {
        return data.list!;
      } else {
        return [];
      }
    });
  }

  // duration 音频时长，单位为秒
  Future<TalkCheckElectricResponse> checkElectric(double duration) {
    return atmobApi
        .checkElectric(TalkGenerateRequest(duration))
        .then(HttpHandler.handle(false));
  }

  Future<TalkInfoResponse> talkInfo(String id) {
    return atmobApi
        .talkInfo(TalkRequest(id, isExample: !accountRepository.isLogin.value))
        .then(HttpHandler.handle(true));
  }

  Future<void> talkRename(String? id, String? title) {
    return atmobApi
        .talkRename(TalkRenameRequest(id, title))
        .then(HttpHandler.handle(true));
  }

  Future<void> talkDelete(String? id) {
    return atmobApi
        .talkDelete(TalkDeleteRequest(id))
        .then(HttpHandler.handle(true));
  }

  Future<TalkBean> talkCreate(String requestId, int duration) {
    return atmobApi
        .talkCreate(TalkCreateRequest(duration, requestId))
        .then(HttpHandler.handle(true));
  }

  Future<String> uploadTalkFile(String talkId, double duration, File file) {
    _uploadingTalkIds.add(talkId);
    return atmobFileApi
        .uploadTalkFile(TalkFileRequest(talkId, duration, file: file).toJson())
        .then(HttpHandler.handle(true))
        .then((response) {
      _uploadingTalkIds.remove(talkId);
      return response.taskId;
    }).catchError((error) {
      _uploadingTalkIds.remove(talkId);
      throw error;
    });
  }
}

final talkRepository = TalkRepository._();
