/*
 * @Author: XianKaiQun
 * @Date: 2020-09-11 08:55:40
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-11-07 15:17:31
 * @Description: 
 */
import 'package:app_package/app_package.dart';
import 'package:dynamic_package/src/api/api.dart';
import 'package:dynamic_package/src/models/dynamic_item.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:get/get.dart';

class PrivateIndexStore with ChangeNotifier {
  final BuildContext context, providerContext;
  late Map<String, dynamic> routingArgs;
  PrivateIndexStore(this.context, this.providerContext) {
    routingArgs = (ModalRoute.of(context)?.settings.arguments ??
            new Map<String, dynamic>()) as Map<String, dynamic>? ??
        {};
    onGetClassList();
  }
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

  int index = 0;

  ///去草稿箱
  // route2draft() async {
  //   await WNavUtil.instance!.pushNamed('dynamic/draft');
  //   scrollViewKey.currentState?.initTrigger();
  // }

  ///去新增
  route2add() async {
    var res = await WNavUtil.instance!.pushNamed('dynamic/edit');
    if (res == true) {
      onSetTabIndex(1);
    }
    if (res == false) {
      onSetTabIndex(0);
    }
  }

  ///删除动态
  Future<void> onDelete(String? id) async {
    var res = await DynamicServiceImpl().deleteDynamic(id);
    if (res.data == 1) {
      WToastUtil.show('该服务动态删除成功！');
      if (index == 0) {
        list.removeWhere((element) => element.id == id);
      } else {
        draftlist.removeWhere((element) => element.id == id);
      }
      notifyListeners();
    }
  }

  /// 撤回动态
  Future<void> onUndo(item) async {
    var res = await DynamicServiceImpl().undoDynamic(item.id);
    if (res.data == 1) {
      WToastUtil.show(
        item.type == 'serviceBulletin' ? '撤回成功！重新发布需要到草稿箱进行~' : '撤回成功！',
        duration: Duration(seconds: 2),
      );
      list.removeWhere((element) => element.id == item.id);
      notifyListeners();
    }
  }

  List classList = [];

  /// 获取类型列表
  Future onGetClassList() async {
    var res = await DynamicServiceImpl().getClassIdList();
    classList = res.data ?? [];
  }

  /// 切换tab 0：已发布 1：草稿箱
  onSetTabIndex(data) {
    index = data;
    notifyListeners();
    onRefresh();
  }

  /// 初始化刷新列表
  onRefresh() {
    if (index == 0) {
      list = [];
      params['pageNum'] = 1;
      notifyListeners();
      scrollViewKey.currentState?.initTrigger();
    } else {
      draftlist = [];
      draftParams['pageNum'] = 1;
      notifyListeners();
      scrollViewKey1.currentState?.initTrigger();
    }
  }

  /// 类型
  String classId = '';

  /// 服务分类
  String type = '';

  String title = '';
  String titleDraft = '';
  onSearch(String t) {
    title = t;
    notifyListeners();
    onRefresh();
  }

  onSearchDraft(String t) {
    titleDraft = t;
    notifyListeners();
    onRefresh();
  }

  final tabKey = GlobalKey();
  final searchKey = GlobalKey();
  final searchKey1 = GlobalKey();
  final scrollViewKey = GlobalKey<WisScrollViewState>();
  final scrollViewKey1 = GlobalKey<WisScrollViewState>();
  late Map<String, dynamic> params = {
    'pageNum': 1,
    'pageSize': 20,
  };
  List<DynamicItemModel> list = [];
  Future getList({bool isLoad = true}) async {
    if (!isLoad) params['pageNum'] = 1;
    var res = await DynamicServiceImpl().getDynamicList({
      'communityId': communityGlobalStore.data.id,
      ...params,
      'title': title,
      'classId': classId,
      'type': type,
    });
    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 = _list;
    notifyListeners();
  }

  /// 跳转详情
  toDetail(item) {
    Get.toNamed('dynamic/detail', arguments: {
      'id': item.id,
      'item': item,
    });
  }

  ///跳转筛选
  toFilter() {
    Get.toNamed('dynamic/filter', arguments: {
      'classId': classId,
      'type': type,
    })!
        .then((res) => {
              if (res != null && res['isRefresh'] == true)
                {
                  type = res['type'],
                  classId = res['classId'],
                  notifyListeners(),
                  onRefresh(),
                }
            });
  }

  Future<void> onEdit(item) async {
    final res = await WNavUtil.instance!.pushNamed('dynamic/edit', arguments: {
      'id': item.id,
      'content': item.title,
      'photos': (item.url ?? '') == '' ? <String>[] : item.url!.split(','),
      'classId': item.classId,
      'item': item
    });
    if (res == true) {
      onSetTabIndex(1);
    }
    if (res == false) {
      onSetTabIndex(0);
    }
  }

  late Map<String, dynamic> draftParams = {
    'pageNum': 1,
    'pageSize': 20,
  };

  // String title = '';
  // onSearch(String t) {
  //   title = t;
  //   list = [];
  //   notifyListeners();
  //   scrollViewKey.currentState?.initTrigger();
  // }

  List<DynamicItemModel> draftlist = [];
  Future getDraftList({bool isLoad = true}) async {
    if (!isLoad) draftParams['pageNum'] = 1;
    var res = await DynamicServiceImpl().getDynamicDraftList({
      'communityId': communityGlobalStore.data.id,
      ...draftParams,
      'title': titleDraft,
      'classId': classId,
      'type': type,
    });
    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      scrollViewKey1.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      scrollViewKey1.currentState?.isLast();
    } else {
      draftParams['pageNum']++;
    }
    isLoad ? draftlist.addAll(_list) : draftlist = _list;
    notifyListeners();
  }
}
