/*
 * @Author: WuWei
 * @Date: 2020-05-14 14:58:35
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2022-10-19 16:53:12
 * @Description:
 */

import 'package:app_package/app_package.dart';
import 'package:get/get.dart';
import 'package:flutter/widgets.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import '../../src/service/impl/notice_service_impl.dart';
import '../../src/service/notice_service.dart';
import '../../src/models/notice_model.dart';

class NoticeListStore extends GetxController {
  Map? args;
  final scrollViewKey = GlobalKey<WisScrollViewState>();

  final NoticeService _noticeService = NoticeServiceImpl();
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

  ///从储存中取出的当前小区 拿出来可能是空
  CommunityModel? get currentCommunity => communityGlobalStore.data;

  ///去选择小区
  toCommunityPick() async {
    await Get.toNamed('community');
    // Get.back();
  }

  Map<String, dynamic> params = {
    'pageNum': 1,
    'pageSize': 20,
  }.obs;

  var list = <NoticeModel>[].obs;
  // List<NoticeModel> list = [];

  var name = ''.obs;

  String title = '';
  onSearch(String t) {
    title = t;
    params['pageNum'] = 1;
    list.value = [];
    list.refresh();
    scrollViewKey.currentState?.initTrigger();
  }

  Future getList({bool isLoad = true}) async {
    if (!isLoad) params['pageNum'] = 1;
    var res = await _noticeService.getNoticeList({
      ...params,
      'communityId': currentCommunity?.id,
      'title': title,
    });
    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      scrollViewKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      scrollViewKey.currentState?.isLast();
    } else {
      params['pageNum']++;
    }
    isLoad ? list.addAll(_list) : list.value = _list;
    list.refresh();
    name.value = 'getx';
  }

  Future<void> onInitPage() async {
    if (currentCommunity?.id != null) {
      await getList();
    } else {
      toCommunityPick();
    }
  }

  routeToDetail(NoticeModel item) {
    Get.toNamed('notice/detail', arguments: item.toJson());
  }

  routeToAdd() {
    Get.toNamed('notice/add')!.then((value) {
      //插入新发布的通知
      if (value is NoticeModel) {
        list.insert(0, value);
      }
    });
  }
}
