import 'dart:io';

import 'package:electronic_assistant/base/base_controller.dart';
import 'package:electronic_assistant/data/bean/talks.dart';
import 'package:electronic_assistant/data/consts/Constants.dart';
import 'package:electronic_assistant/data/consts/event_report_id.dart';
import 'package:electronic_assistant/data/repositories/agenda_repository.dart';
import 'package:electronic_assistant/data/repositories/config_repository.dart';
import 'package:electronic_assistant/data/repositories/talk_repository.dart';
import 'package:electronic_assistant/handler/event_handler.dart';
import 'package:electronic_assistant/module/login/view.dart';
import 'package:electronic_assistant/module/main/controller.dart';
import 'package:electronic_assistant/module/talk/view.dart';
import 'package:electronic_assistant/resource/string.gen.dart';
import 'package:electronic_assistant/router/app_pages.dart';
import 'package:electronic_assistant/utils/event_bus.dart';
import 'package:electronic_assistant/utils/file_upload_check_helper.dart';
import 'package:electronic_assistant/utils/mmkv_util.dart';
import 'package:electronic_assistant/widget/pull_to_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import '../../data/api/response/example_info_response.dart';
import '../../data/bean/agenda.dart';
import '../../data/repositories/account_repository.dart';
import '../../dialog/guide_dialog.dart';
import '../../resource/colors.gen.dart';
import '../../utils/error_handler.dart';
import '../../utils/toast_util.dart';
import '../agenda/detail/view.dart';
import '../audiopicker/view.dart';

class HomePageController extends BaseController {
  get isLogin => accountRepository.isLogin.value;

  get loginTxt => accountRepository.isLogin.value
      ? accountRepository.getUserSubName(accountRepository.phone)
      : StringName.homeGoLogin.tr;

  final refreshController = PullToRefreshController();

  BuildContext? todoTargetContext;

  RxList<TalkBean> get talkList => talkRepository.talkList;

  RxList<Agenda> get agendaList => agendaRepository.agendaList;

  final mainController = Get.find<MainController>();

  GlobalKey headGuideKey = GlobalKey();

  @override
  void onReady() {
    super.onReady();
    refreshController.requestRefresh();

    eventBus.on(EventUserLogin, (arg) {
      requestHomeData();
    });

    eventBus.on(EventUserLogout, (arg) {
      talkRepository.setTalkList([]);
      agendaRepository.setAgendaList([]);
      requestHomeData();
    });

    _checkMainGuide();
  }

  void _checkMainGuide() {
    if (!KVUtil.getBool(GuideConstants.mainGuide, true)) {
      return;
    }
    //新人引导
    mainGuide(headGuideKey, knowCallback: () {
      KVUtil.putBool(GuideConstants.mainGuide, false);
    });
  }

  @override
  void dispose() {
    super.dispose();
    eventBus.off(EventUserLogin);
    eventBus.off(EventUserLogout);
  }

  void requestHomeData() async {
    try {
      if (accountRepository.isLogin.value) {
        await Future.wait([
          talkRepository.refreshHomeTalkData(),
          agendaRepository.requestHomeAgendaData(),
        ]);
      } else {
        ExampleInfoResponse exampleInfo =
            await configRepository.getExampleInfo();
        talkRepository.setTalkList(
            exampleInfo.talkInfoList != null ? exampleInfo.talkInfoList! : []);
        agendaRepository.setAgendaList(
            exampleInfo.agendaList != null ? exampleInfo.agendaList! : []);
      }
    } catch (e) {
      refreshController.refreshCompleted();
      // Handle errors if necessary
    } finally {
      refreshController.refreshCompleted();
    }
  }

  void requestName(String? newName, TalkBean bean) {
    talkRepository.talkRename(bean.id, newName).then((data) {
      bean.title.value = newName;
      ToastUtil.showToast(StringName.talkRenameSuccess.tr);
    }).catchError((error) {
      ErrorHandler.toastError(error, message: StringName.talkRenameFail.tr);
    });
  }

  void goTalkRecordPage() {
    mainController.updateIndexByPageName(StringName.mainTabFile);
  }

  void showLoginDrawer() {
    mainController.openDrawer();
  }

  void requestDelete(TalkBean item) {
    talkRepository.talkDelete(item.id).then((data) {
      requestHomeData();
    }).catchError((error) {
      ErrorHandler.toastError(error, message: StringName.talkDeleteFail.tr);
    });
  }

  void agendaComplete(Agenda item) {
    agendaRepository.agendaFinish(item.id, true).then((data) {
      agendaRepository.requestHomeAgendaData();
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

  void onPickerAudioFile() async {
    EventHandler.report(EventId.event_100030);
    if (!accountRepository.isLogin.value) {
      Get.toNamed(RoutePath.login);
      ToastUtil.showToast(StringName.errorCodeNoLogin.tr);
      return;
    }
    if (Platform.isAndroid) {
      _showAndroidFilePicker();
    } else {
      FileUploadCheckHelper.choicePlatformLocalFileAndCreateOrder();
    }
  }

  void onGoAgendaList() {
    if (!accountRepository.isLogin.value) {
      Get.toNamed(RoutePath.login);
      ToastUtil.showToast(StringName.errorCodeNoLogin.tr);
      return;
    }
    Get.toNamed(RoutePath.task);
  }

  void onTalkItemClick(TalkBean item) {
    if (item.isExample == true) {
      EventHandler.report(EventId.event_100001);
    }
    TalkPage.start(item);
  }

  void onRecordClick() {
    Get.toNamed(RoutePath.record);
  }

  void onLoginClick() {
    LoginPage.start(fromType: LoginFromType.mainLogin);
  }

  void _showAndroidFilePicker() {
    Get.bottomSheet(const AudioPickerPage(),
        isScrollControlled: true,
        barrierColor: ColorName.black55,
        backgroundColor: ColorName.transparent);
  }

  void onAgendaItemClick(Agenda item) {
    AgendaDetailPage.start(item);
  }
}
