import 'package:cs_resources/generated/l10n.dart';
import 'package:domain/repository/main_repository.dart';
import 'package:flutter/material.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/picker/option_pick_util.dart';

import '../../main/main_page.dart';
import '../create_success/feedback_create_success_page.dart';
import 'feedback_create_state.dart';

part 'feedback_create_view_model.g.dart';

@riverpod
class FeedbackCreateViewModel extends _$FeedbackCreateViewModel with DioCancelableMixin {
  late final MainRepository _mainRepository;

  @override
  FeedbackCreateState build() {
    _mainRepository = ref.read(mainRepositoryProvider);
    final state = FeedbackCreateState(imgList: []);

    registerCancellation();

    return state;
  }

  //选择选项
  void pickCategory() async {
    _dismissKeyboard();
    Log.d("当前的optionList：${state.optionList}");
    if (state.optionList == null || state.optionList!.isEmpty) {
      //请求接口
      final result = await _mainRepository.fetchFeedbackCategory(cancelToken: cancelToken);

      if (result.isSuccess) {
        state.optionList = result.list;
        showCategoryPicker();
      } else {
        ToastEngine.show(result.errorMsg ?? "UnKnow Error");
      }
    } else {
      showCategoryPicker();
    }
  }

  //展示分类的PickerView
  void showCategoryPicker() {
    if (state.optionList == null) return;

    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.optionList!.map((e) => e.name).whereType<String>().toList(),
      initialSelectIndex: 0,
      onPickerChanged: (_, index) {
        state = state.copyWith(selectedOption: state.optionList![index]);
      },
    );
  }

  void _dismissKeyboard() {
    final FocusNode titleFocusNode = state.formData['title']!['focusNode'];
    final FocusNode descFocusNode = state.formData['desc']!['focusNode'];
    titleFocusNode.unfocus();
    descFocusNode.unfocus();
  }

  ///提交反馈
  void submitFeedback() async {
    _dismissKeyboard();

    final TextEditingController titleController = state.formData['title']!['controller'];
    final TextEditingController descController = state.formData['desc']!['controller'];

    final title = titleController.text;
    final desc = descController.text;

    Log.d('当前待提交的 option:${state.selectedOption} title:$title desc:$desc imgList:${state.imgList}');

    if (state.selectedOption == null) {
      ToastEngine.show(S.current.choose_category);
      return;
    }

    if (Utils.isEmpty(title)) {
      ToastEngine.show("Title cannot be empty!");
      return;
    }

    if (Utils.isEmpty(desc)) {
      ToastEngine.show("Enter Your FeedBack Description");
      return;
    }
    //执行请求
    final result = await _mainRepository.postFeedback(
      categoryId: state.selectedOption?.id,
      title: title,
      content: desc,
      paths: state.imgList,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      //去成功页面
      FeedbackCreateSuccessPage.startInstance();
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }

  //选中图片
  void setImgList(List<String> list) {
    _dismissKeyboard();
    state = state.copyWith(imgList: list);
  }
}
