/*
 * @Author: XianKaiQun
 * @Date: 2020-04-21 08:47:59
 * @LastEditors: wuwei
 * @LastEditTime: 2024-02-02 15:35:50
 * @Descripttion: 
 */
part of 'index.dart';

class _Store with ChangeNotifier {
  final BuildContext context;
  late Map args;
  _Store(this.context) {
    args =
        ModalRoute.of(context)!.settings.arguments as Map<dynamic, dynamic>? ??
            {};
  }
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

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

  /// 展开标识
  bool? expand;

  onSetExpand(bool flag) {
    expand = flag;
    FocusScope.of(context).requestFocus(FocusNode());
    notifyListeners();
  }

  /// 卡片统计数据
  var feeStatistics;

  /// 当月标识
  var billStatisticIsThisMonth = true;

  /// 统计文案
  var statisticText = '';

  /// 欠费文案
  var arrearsFeeText = '';

  /// 初始化更新统计月份数据
  getBillStatisticThisMonth() {
    var isCurrent = WisStorageUtil.get(key: 'bill_statistic_is_this_month');
    if (isCurrent == null) {
      WisStorageUtil.set(key: 'bill_statistic_is_this_month', data: true);
    }
    billStatisticIsThisMonth =
        WisStorageUtil.get(key: 'bill_statistic_is_this_month');
    getCurrentStatisticRangeText();
    notifyListeners();
  }

  /// 设置统计月份
  setBillStatisticThisMonth() {
    billStatisticIsThisMonth = !billStatisticIsThisMonth;
    WisStorageUtil.set(
        key: 'bill_statistic_is_this_month', data: billStatisticIsThisMonth);
    getCurrentStatisticRangeText();
    getFee();
  }

  /// 统计文案
  getCurrentStatisticRangeText() {
    var current = DateFormat('yyyy-MM').format(DateTime.now());
    var last = DateFormat("yyyy-MM")
        .format(DateTime(DateTime.now().year, DateTime.now().month - 1));
    statisticText = billStatisticIsThisMonth == true
        ? '本期（${current}账期统计数据）'
        : '上期（${last}账期统计数据）';
    arrearsFeeText = billStatisticIsThisMonth == true
        ? '（本期\\截止至${current}账期）'
        : '（上期\\截止至${last}账期）';
  }

  /// 获取收费卡片数据(应收、欠费、实收、今日已收、收费率)
  Future<void> getFee() async {
    feeStatistics = null;
    notifyListeners();
    var current = DateFormat('yyyy-MM').format(DateTime.now());
    var last = DateFormat("yyyy-MM")
        .format(DateTime(DateTime.now().year, DateTime.now().month - 1));
    var res = await AssetBillApi.getFeeStatistics({
      'communityId': args['communityId'] ?? currentCommunity!.id,
      'chargeYearMonth': billStatisticIsThisMonth == true ? current : last
    });
    feeStatistics = res.data;
    notifyListeners();
  }

  var treeSelectionList = [
    {'name': '房屋搜索', 'icon': 'lib/assets/fangwu.png', 'code': 'house'},
    {'name': '车位搜索', 'icon': 'lib/assets/chewei.png', 'code': 'parkingSpace'},
    {'name': '车辆搜索', 'icon': 'lib/assets/cheliang.png', 'code': 'car'},
    {'name': '住户搜索', 'icon': 'lib/assets/zhuhu.png', 'code': 'resident'},
  ];

  var currentTreeSelection = 'house';

  onTreeSelectionChange(code) {
    currentTreeSelection = code;
    notifyListeners();
  }

  Future onInit() async {
    if (await communityGlobalStore.intent == false) {
      return Navigator.pop(context);
    }
    getBillStatisticThisMonth();
    getFee();
  }

  route2list(ArrearsFeeModel item) {
    Navigator.pushNamed(context, 'bill/list', arguments: {
      'communityId': args['communityId'] ?? currentCommunity!.id,
      ...item.toJson(),
    });
  }

  ///房屋搜索---------------------------
  final houseScrollViewKey = GlobalKey<WisScrollViewState>();
  Map<String, dynamic> houseParams = {
    'pageNum': 1,
    'pageSize': 20,
  };
  List<CascadeModel> houseList = [];

  String houseSearchWord = '';

  List<CascadeModel> currentHouseFilterData = [];

  CascadeModel? currentItem;

  Future onHouseSearchTrigger(String v) async {
    houseSearchWord = v;
    FocusScope.of(context).requestFocus(FocusNode());
    notifyListeners();

    if (v == '') {
      getHouseData();
    } else {
      getHouseList();
    }
  }

  onClearFilterData() {
    currentItem = null;
    currentHouseFilterData = [];
    notifyListeners();
    getHouseData();
  }

  onClickFilterItem(item) async {
    WLoadingUtil.show(color: Colors.black26);
    int index =
        currentHouseFilterData.indexWhere((element) => item.id == element.id);
    notifyListeners();
    List<CascadeModel>? back = [];
    switch (item?.status) {
      case 'build':
        currentHouseFilterData.removeRange(
            index, currentHouseFilterData.length);
        final res = await AssetBillApi().getBuildInfo({
          'communityId': args['communityId'] ?? currentCommunity?.id,
        });
        back = res.data;

        break;
      case 'unit':
        currentHouseFilterData.removeRange(
            index, currentHouseFilterData.length);
        final res = await AssetBillApi().getUnitInfo({
          'communityId': args['communityId'] ?? currentCommunity?.id,
          'buildId':
              currentHouseFilterData.firstWhere((e) => e.status == 'build').id,
        });
        back = res.data;

        break;
      case 'floor':
        currentHouseFilterData.removeRange(
            index, currentHouseFilterData.length);
        final res = await AssetBillApi().getFloorInfo({
          'communityId': args['communityId'] ?? currentCommunity?.id,
          'buildId':
              currentHouseFilterData.firstWhere((e) => e.status == 'build').id,
          'unitId':
              currentHouseFilterData.firstWhere((e) => e.status == 'unit').id,
        });
        back = res.data;
        break;
    }
    WLoadingUtil.hide();
    houseList = back ?? [];
    notifyListeners();
  }

  Map assetTypeNameList = {
    'build': '楼栋',
    'unit': '单元',
    'floor': '楼层',
    'house': '房屋',
  };

  onClickHouseItem(item) {
    if (item.status == 'house') {
      late Map params = {
        'assetId': item.id,
        'assetType': 'house',
        'assetFullName':
            currentHouseFilterData.map((e) => e.name).toList().join('/') +
                '${currentHouseFilterData.length > 0 ? '/' : ''}'
                    '${item.name}',
      };
      Navigator.pushNamed(context, 'receipt/detail', arguments: params);
      return;
    }
    WLoadingUtil.show(color: Colors.black26);
    switch (item.status) {
      case 'build':
        if (currentHouseFilterData.length == 1) {
          currentHouseFilterData[0] = item;
        } else {
          currentHouseFilterData.add(item);
        }
        break;
      case 'unit':
        if (currentHouseFilterData.length == 2) {
          currentHouseFilterData[1] = item;
        } else {
          currentHouseFilterData.add(item);
        }
        break;
      case 'floor':
        if (currentHouseFilterData.length == 3) {
          currentHouseFilterData[2] = item;
        } else {
          currentHouseFilterData.add(item);
        }
        break;
    }

    notifyListeners();
    getHouseData();
  }

  ///房号级联选择
  Future getHouseData() async {
    List<CascadeModel>? back = [];

    final last = currentHouseFilterData.length == 0
        ? null
        : currentHouseFilterData.lastWhere((e) => true);
    switch (last?.status) {
      case 'build':
        final res = await AssetBillApi().getUnitInfo({
          'communityId': args['communityId'] ?? currentCommunity?.id,
          'buildId':
              currentHouseFilterData.firstWhere((e) => e.status == 'build').id,
        });
        back = res.data;
        break;
      case 'unit':
        final res = await AssetBillApi().getFloorInfo({
          'communityId': args['communityId'] ?? currentCommunity?.id,
          'buildId':
              currentHouseFilterData.firstWhere((e) => e.status == 'build').id,
          'unitId':
              currentHouseFilterData.firstWhere((e) => e.status == 'unit').id,
        });
        back = res.data;
        break;
      case 'floor':
        final res = await AssetBillApi().getHouseInfo({
          'communityId': args['communityId'] ?? currentCommunity?.id,
          'buildId':
              currentHouseFilterData.firstWhere((e) => e.status == 'build').id,
          'unitId':
              currentHouseFilterData.firstWhere((e) => e.status == 'unit').id,
          'houseFloor':
              currentHouseFilterData.firstWhere((e) => e.status == 'floor').id,
        });
        back = res.data;
        break;

      default:
        final res = await AssetBillApi().getBuildInfo({
          'communityId': args['communityId'] ?? currentCommunity?.id,
        });
        back = res.data;
    }
    WLoadingUtil.hide();
    houseList = back ?? [];
    notifyListeners();
  }

  Future getHouseList({bool isLoad = true}) async {
    if (houseSearchWord == '') {
      houseList = [];
      notifyListeners();
      return;
    }
    final res = await AssetBillApi().getHouseInfo({
      'communityId': args['communityId'] ?? currentCommunity?.id,
      'buildId': currentHouseFilterData.length == 1
          ? currentHouseFilterData.firstWhere((e) => e.status == 'build').id
          : '',
      'unitId': currentHouseFilterData.length == 2
          ? currentHouseFilterData.firstWhere((e) => e.status == 'unit').id
          : '',
      'houseFloor': currentHouseFilterData.length == 3
          ? currentHouseFilterData.firstWhere((e) => e.status == 'floor').id
          : '',
      'roomNo': houseSearchWord
    });
    houseList = res.data ?? [];
    // isLoad ? houseList.addAll(_list) : houseList = _list;
    notifyListeners();
  }

  ///车辆---------------------------
  final carScrollViewKey = GlobalKey<WisScrollViewState>();
  Map<String, dynamic> carParams = {
    'pageNum': 1,
    'pageSize': 20,
  };
  List<SearchItemModel> carList = [];

  String carSearchWord = '';
  Future onCarSearchTrigger(String v) async {
    carSearchWord = v;
    carList = [];
    FocusScope.of(context).requestFocus(FocusNode());
    notifyListeners();
    carScrollViewKey.currentState?.initTrigger();
  }

  Future getCarList({bool isLoad = true}) async {
    if (carSearchWord == '') {
      carList = [];
      return;
    }
    if (!isLoad) carParams['pageNum'] = 1;
    var res = await AssetBillApi.getCarSearchList({
      'communityId': args['communityId'] ?? currentCommunity!.id,
      'fuzzyCarNo': carSearchWord,
      ...carParams,
    });
    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      carScrollViewKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      carScrollViewKey.currentState?.isLast();
    } else {
      carParams['pageNum']++;
    }
    isLoad ? carList.addAll(_list) : carList = _list;
    notifyListeners();
  }

  ///车位搜索
  final parkScrollViewKey = GlobalKey<WisScrollViewState>();
  Map<String, dynamic> parkParams = {
    'pageNum': 1,
    'pageSize': 20,
  };
  List<SearchItemModel> parkList = [];

  String parkSearchWord = '';

  Future onParkSearchTrigger(String v) async {
    parkSearchWord = v;
    parkList = [];
    notifyListeners();
    FocusScope.of(context).requestFocus(FocusNode());
    parkScrollViewKey.currentState?.initTrigger();
  }

  Future getParkList({bool isLoad = true}) async {
    if (parkSearchWord == '') {
      parkList = [];
      return;
    }
    if (!isLoad) parkParams['pageNum'] = 1;
    var res = await AssetBillApi.getParkSearchList({
      'communityId': args['communityId'] ?? currentCommunity!.id,
      'fuzzyCode': parkSearchWord,
      ...parkParams,
    });
    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      parkScrollViewKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      parkScrollViewKey.currentState?.isLast();
    } else {
      parkParams['pageNum']++;
    }
    isLoad ? parkList.addAll(_list) : parkList = _list;
    notifyListeners();
  }

  /// 住户搜索
  final residentScrollViewKey = GlobalKey<WisScrollViewState>();
  Map<String, dynamic> residentParams = {
    'pageNum': 1,
    'pageSize': 20,
  };
  List<ResidentItemModel> residentList = [];

  Future onResidentSearchTrigger(String v) async {
    residentSearchWord = v;
    residentList = [];
    notifyListeners();
    FocusScope.of(context).requestFocus(FocusNode());
    residentScrollViewKey.currentState?.initTrigger();
  }

  String residentSearchWord = '';

  Future getResidentList({bool isLoad = true}) async {
    if (residentSearchWord == '') {
      residentList = [];
      return;
    }
    if (!isLoad) residentParams['pageNum'] = 1;
    var res = await AssetBillApi.getResidentSearchList({
      'communityId': args['communityId'] ?? currentCommunity!.id,
      'keyWord': residentSearchWord,
      ...residentParams,
    });
    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      residentScrollViewKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      residentScrollViewKey.currentState?.isLast();
    } else {
      residentParams['pageNum']++;
    }
    isLoad ? residentList.addAll(_list) : residentList = _list;
    notifyListeners();
  }

  /// 手机收单详情页
  route2ReceiptDetail(item) {
    late Map params = {
      'assetId': item.assetId,
      'assetType': item.assetType,
      'assetFullName': item?.assetName ?? '${item.name}/${item.mobile}',
    };
    Navigator.pushNamed(context, 'receipt/detail', arguments: params);
  }

  toRecord() {
    Navigator.pushNamed(context, 'pay_record/index',
        arguments: {'appBarTitle': '收支记录'});
  }
}
