/*
 * @Author: XianKaiQun
 * @Date: 2020-04-22 15:43:49
 * @LastEditors: wuwei
 * @LastEditTime: 2024-02-06 14:30:31
 * @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 appGlobalStore = GetIt.I.get<AppGlobalStore>();
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

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

  final scorllViewKey = GlobalKey<WisScrollViewState>();
  final scorllViewKey1 = GlobalKey<WisScrollViewState>();

  ///详情
  OweFeeInfoModel? detail;
  OweFeeInfoModel? detailAll;
  Future getDetail(type) async {
    await getOweFeeMonthList();
    await getFeeTotalCount();
    await getTotalCount();
  }

  // List oweMonth = [];

  // getOweFeeMonthList() async {
  //   var params = {
  //     'communityId': currentCommunity?.id,
  //   };
  //   if (args['assetType'] != 'owner') {
  //     params['assetType'] = args['assetType'];
  //     params['assetId'] = args['assetId'];
  //   } else {
  //     params['ownerId'] = args['assetId'];
  //   }
  //   var res = await AssetBillApi.getOweFeeMonthList(params);
  //   oweMonth = res.data ?? [];
  //   if (res.data?.isNotEmpty == true) {
  //     chooseMonth = res.data![0];
  //     chooseYear = int.parse(res.data![0].split('-')[0]);
  //   }
  //   notifyListeners();
  //   getBillDetailList();
  // }

  List<OweFeeMonthListModel> oweFeeListByMonth = [];
  List<OweFeeMonthListModel> oweFeeListByAll = [];

  getOweFeeMonthList() async {
    var res = await AssetBillApi.getOweFeeListByMonth({
      'assetType': args['assetType'],
      'assetId': args['assetId'],
      'queryFor': "arrears",
    });

    oweFeeListByMonth = res.data ?? [];
    if (oweFeeListByMonth.length == 0) {
      scorllViewKey.currentState?.isEmpty();
    }
    notifyListeners();
    if (res.data?.isNotEmpty == true) {
      chooseMonth = res.data![0].chargeYearMonth;
      chooseYear = int.parse(chooseMonth!.split('-')[0]);
    }
    notifyListeners();
    getBillDetailList('month');
  }

  int year =
      DateTime.now().month > 6 ? DateTime.now().year : DateTime.now().year - 1;
  int endYear = DateTime.now().year;
  int count = 1;

  reloadAllList() async {
    oweFeeListByAll = [];
    year = DateTime.now().month > 6
        ? DateTime.now().year
        : DateTime.now().year - 1;
    endYear = DateTime.now().year;
    count = 1;
    getOweFeeMonthListByAll(isLoad: false);
  }

  Future getOweFeeMonthListByAll({bool isLoad = true}) async {
    var res = await AssetBillApi.getOweFeeListByMonth({
      'queryFor': "all",
      'assetType': args['assetType'],
      'assetId': args['assetId'],
      'chargeYearMonthStart': '${year}-01',
      'chargeYearMonthEnd': endYear == DateTime.now().year
          ? count == 1
              ? null
              : DateTime.now().toFormat(WisDateTimeFormat.yearAndMonth)
          : '${endYear - 1}-12',
    });

    final _list = res.data ?? [];

    isLoad ? oweFeeListByAll.addAll(_list) : oweFeeListByAll = _list;
    if (oweFeeListByAll.length == 0 && year < 1990) {
      scorllViewKey1.currentState?.isEmpty();
    } else if (year < 1990 && oweFeeListByAll.length != 0) {
      scorllViewKey1.currentState?.isLast();
    } else {
      year--;
      endYear--;
      count++;
    }
    notifyListeners();
    if (oweFeeListByAll.length < 12 && year >= 1990) {
      getOweFeeMonthListByAll(isLoad: true);
    }
  }

  TotalCountModel? totalCount;
  getFeeTotalCount() async {
    var res = await AssetBillApi.getFeeTotalCount({
      'assetId': args['assetId'],
      'assetType': args['assetType'],
      'communityId': currentCommunity?.id,
    });
    totalCount = res.data ?? TotalCountModel();
    notifyListeners();
  }

  OweFeeCountModel? oweCount;

  /// 获取账单总计-------------------------------------------
  Future<void> getTotalCount() async {
    Map<String, dynamic> params = {
      'assetId': args['assetId'],
      'treeSelection': args['assetType'],
      'identification': null,
      'feeTypeId': null,
      'communityId': currentCommunity?.id,
      'chargeYearMonthEnd': DateFormat('yyyy-MM').format(DateTime.now()),
    };

    var res = await AssetBillApi.getOweFeeCount(params);
    oweCount = res.data ?? OweFeeCountModel();
    notifyListeners();
  }

  /// 账单明细
  Future getBillDetailList(type) async {
    var res = await AssetBillApi.getFeeListByMonth({
      'assetId': args['assetId'],
      'assetType': args['assetType'],
      'chargeYearMonth': type == 'all' ? chooseMonthAll : chooseMonth,
    });
    if (type == 'all') {
      detailAll = res.data ?? OweFeeInfoModel();
      notifyListeners();
    } else {
      detail = res.data ?? OweFeeInfoModel();
      notifyListeners();
    }

    notifyListeners();
  }

  LiquidatedDamagesModel info = LiquidatedDamagesModel();

  /// 获取违约金明细
  getLiquidatedDetails(item) async {
    if (item.isBreach) {
      var res = await AssetBillApi.getLiquidatedDamages(item.id);
      if (res.data?.receivableFee != null && res.data!.receivableFee! > 0) {
        info = res.data ?? LiquidatedDamagesModel();
      } else {
        info.discountFee = item.breachDiscountFee;
        info.arrearsFee = (item.breachReceivableFee - item.breachDiscountFee);
        info.receivableFee = item.breachReceivableFee;
        info.receivedFee = 0;
        info.liquidatedDamagesStartAt = item.liquidatedDamagesStartAt;
        info.quantity = item.breachQuantity;
        info.coefficient = item.coefficient;
      }
    }
    notifyListeners();
  }

  DateTime startMonth = DateTime.now();
  DateTime? lastMonth;

  int? chooseYear;

  chooseDialogYear(value) {
    chooseYear = value;
    notifyListeners();
  }

  // 选择账期
  String? chooseMonth = DateFormat('yyyy-MM').format(DateTime.now());
  chooseMonthByArrears(item) {
    chooseMonth = item.chargeYearMonth;
    notifyListeners();
    getBillDetailList('month');
  }

  clearChooseMonth() {
    chooseMonth = null;
    notifyListeners();
  }

  String? chooseMonthAll = DateFormat('yyyy-MM').format(DateTime.now());
  chooseMonthByAllList(item) {
    chooseMonthAll = item.chargeYearMonth;
    notifyListeners();
    getBillDetailList('all');
  }

  clearChooseMonthAll() {
    chooseMonthAll = null;
    notifyListeners();
  }

  /// 账期结束选择
  chooseLastMonth() async {
    var res = await WPickerUtil.month(
      context,
      title: WisText('选择账期'),
      firstDate: startMonth, //DateTime(2010)
      lastDate: DateTime(2050),
      initialDate: lastMonth ?? DateTime.now().add((Duration(minutes: 10))),
    );
    if (res != null) {
      lastMonth = res;
      notifyListeners();
      scorllViewKey.currentState?.refreshTrigger();
    }
  }

  /// 收支记录
  toFeeRecord() {
    Get.toNamed(
      'pay_record/index',
      arguments: {
        'appBarTitle': '收支记录',
        'assetId': args['assetId'],
        'assetType': args['assetType'],
      },
    );
  }

  /// 跳转筛选页
  toFilter() {
    Get.toNamed('bill/detal/filter');
  }
}
