import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../../../common/api/index.dart';
import '../../../../../../common/models/index.dart';
import '../../../../../../common/utils/index.dart';
import '../../../../../../common/values/index.dart';
import '../../../cms_document/index.dart';

class CmsCategoryController extends GetxController {
  CmsCategoryController(this.categoryData);

  CmsCategoryData categoryData;
  

  // obs
  RxList<DocumentData> docList = <DocumentData>[].obs;
  Rx<bool> hasMore = true.obs;
  
  final ScrollController scrollController = ScrollController();

  int page = 1;
  bool _isLoading = false;

  _initData() {
    scrollController.addListener(() {
       if (scrollController.position.pixels >=
          scrollController.position.maxScrollExtent) {
        if (_isLoading) return;
        if (!hasMore.value) return;
        _isLoading = true;
        loadMoreDocList();
      }
    });
    update(["cms_category_${categoryData.id!}"]);
  }

  @override
  void onReady() {
    _initData();
    loadDocList();
    super.onReady();
  }

 
  Future<void> loadDocList() async {
    page = 1;
    _isLoading = true;
    Loading.show();
    Map<String, dynamic> body = {};
    body['statusList'] = <String>['published'];
    body['categoryIdList'] = <String>[categoryData.id!];
    OLogger.d('loadDocList body：$body');
    var list = await CmsAssembleControlService.to.getCmsDocumentListByPage(page, body: body);
    if (list != null && list.isNotEmpty) {
      docList.clear();
      docList.addAll(list);
      hasMore.value = !(list.length < O2.o2DefaultPageSize);
    } else {
      hasMore.value = false;
    }
    update(["cms_category_${categoryData.id!}"]);
    _isLoading = false;
    Loading.dismiss();
  }

  Future<void> loadMoreDocList() async {
     _isLoading = true;
    page++;
    Loading.show();
    Map<String, dynamic> body = {};
    body['statusList'] = <String>['published'];
    body['categoryIdList'] = <String>[categoryData.id!];
    var list = await CmsAssembleControlService.to.getCmsDocumentListByPage(page, body: body);
    if (list != null && list.isNotEmpty) {
      docList.addAll(list);
      hasMore.value = !(list.length < O2.o2DefaultPageSize);
    } else {
      hasMore.value = false;
    }
    update(["cms_category_${categoryData.id!}"]);
    _isLoading = false;
    Loading.dismiss();
  }

  Future<void> clickDoc(int index) async {
    final doc = docList[index];
    await CmsDocumentPage.open(doc.id!, title: doc.title ?? '');
    loadDocList();
  }

  Future<void> clickEditDoc(int index) async {
    final doc = docList[index];
    await CmsDocumentPage.open(doc.id!, title: doc.title ?? '', options: {"readonly": false});
    loadDocList();
  }
}
