import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../../common/api/index.dart';
import '../../../../common/models/index.dart';
import '../../../../common/values/index.dart';
import '../bbs_subject/index.dart';
import '../publish_subject/index.dart';
import 'index.dart';

class BbsSectionController extends GetxController {
  BbsSectionController();

  final state = BbsSectionState();
  int page = 1; //初始化页码
  String sectionId = ''; // 板块id
  bool _isLoading = false; // 是否正在加载
  final refreshController = RefreshController();
  SectionInfoList? sectionInfo; // 板块对象

 
  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    var map = Get.arguments;
    if (map != null && map is SectionInfoList) {
      sectionInfo = map;
      state.title = sectionInfo?.sectionName ?? '';
      sectionId = sectionInfo?.id ?? '';
      if (sectionId.isNotEmpty) {
        refreshData();  
        loadSectionPermission();
      }
    }
    super.onReady();
  } 

  /// 查询权限 是否能发帖
  loadSectionPermission() async {
    final permission = await BBSAssembleControlService.to.sectionPermission(sectionId);
    if (permission != null ) {
      state.subjectPublishAble = permission.subjectPublishAble ?? false;
    }
  }
  /// 板块对象
  loadSectionInfo() async {
    sectionInfo = await BBSAssembleControlService.to.getSectionInfo(sectionId);
  }
  /// 刷新主题帖子数据
  refreshData() async {
    if (_isLoading) return;
    _isLoading = true;
    page = 1;
    await loadSubjectList();
    refreshController.refreshCompleted();
  }
  /// 获取更多主题帖子数据
  loadMore() async {
    if (_isLoading) return;
    if (!state.hasMoreData) {
      refreshController.loadComplete();
      return;
    }
    _isLoading = true;
    page++;
    await loadSubjectList();
    refreshController.loadComplete();
  }

  Future<void> loadSubjectList() async {
    _isLoading = true;
    if (page == 1) {
      state.subjectList.clear();
    }
    var list =
        await BBSAssembleControlService.to.subjectListByPage(sectionId, page);
    if (list != null && list.isNotEmpty) {
      state.subjectList.addAll(list);
      state.hasMoreData = !(list.length < O2.o2DefaultPageSize);
    } else {
      state.hasMoreData = false;
    }
    _isLoading = false;
  }



  Future<void> clickSubject(SubjectInfo subject) async {
    await BbsSubjectPage.open(subject.id!, title: subject.title ?? '');
    refreshData();
  }
  /// 去发帖
  Future<void> clickGotoPublish() async {
    await PublishSubjectPage.toPublishSubject(sectionInfo!);
    refreshData();
  }
}
