/*
 * @Author: WuWei
 * @Date: 2020-08-07 11:29:42
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2023-09-25 16:24:42
 * @Description:
 */

import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:app_package/src/api/employee.dart';
import 'package:get/get.dart';
import 'package:app_package/src/models/community_picker.dart';
import '../models/pay_list.dart';
import '../service/impl/pay_index_impl.dart';
import '../models/pay_summary.dart';
import '../models/pay_detail.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>? ??
        {};
    if (routingArgs['isFilterPage'] == true) {
      payWay = routingArgs['payWay'];
      payBillAtStart = routingArgs['payBillAtStart'];
      payBillAtEnd = routingArgs['payBillAtEnd'];
      communityId = routingArgs['communityId'];
      communityIName = routingArgs['communityIName'];
      communityINameBySubmit = routingArgs['communityIName'];
      communityList = CommunityPickerModel(
        id: routingArgs['communityId'],
      );
    }
    notifyListeners();
    initTab();
  }
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

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

  final indexScorllViewKey0 = GlobalKey<WisScrollViewState>();
  final indexScorllViewKey1 = GlobalKey<WisScrollViewState>();
  final indexScorllViewKey2 = GlobalKey<WisScrollViewState>();
  final indexScorllViewKey3 = GlobalKey<WisScrollViewState>();
  late Map<String, dynamic> params = {
    'pageNum': 1,
    'pageSize': 20,
  };

  late Map<String, dynamic> params1 = {
    'pageNum': 1,
    'pageSize': 20,
  };
  late Map<String, dynamic> params2 = {
    'pageNum': 1,
    'pageSize': 20,
  };
  late Map<String, dynamic> params3 = {
    'pageNum': 1,
    'pageSize': 20,
  };
  ScrollController viewController0 = new ScrollController();
  ScrollController viewController1 = new ScrollController();
  ScrollController viewController2 = new ScrollController();
  ScrollController viewController3 = new ScrollController();
  List<PayListModel> paylist = [];
  List<PayListModel> paylist1 = [];
  List<PayListModel> paylist2 = [];
  PaySummaryModel? summary;
  PayDetail? payDetail;
  int tabNum = 0;

  int? get argtab => routingArgs['billType'] == 'billPay'
      ? 0
      : routingArgs['billType'] == 'prePayPay'
          ? 1
          : routingArgs['billType'] == 'depositePay'
              ? 2
              : 0;

  Future setTab(index) async {
    tabNum = index;
    notifyListeners();
    onhandleFilter();
  }

  Future<void> initTab() async {
    if (routingArgs['billType'] != null && argtab != null) {
      setTab(argtab);
    }
  }

  /// 账单缴费列表
  Future getList({bool isLoad = true}) async {
    if (communityId == null && currentCommunity?.id == null) {
      WToastUtil.show(
        '小区id不存在',
      );
      return;
    }
    if (!isLoad) params['pageNum'] = 1;
    var res = await PayIndexServiceImpl().getPayList({
      ...params,
      "communityId": communityId ?? currentCommunity?.id,
      "assetId": communityId ?? currentCommunity?.id,
      "billBehavior": 'billPay',
      "assetType": "communitys",
      "payStart": payBillAtStart,
      "payEnd": payBillAtEnd,
      "payWay": payWay,
    });
    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      indexScorllViewKey0.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      indexScorllViewKey0.currentState?.isLast();
    } else {
      params['pageNum']++;
    }
    isLoad ? paylist.addAll(_list) : paylist = _list;
    paylist = paylist;
    notifyListeners();
  }

  ///预存款缴费列表
  Future getPreList({bool isLoad = true}) async {
    if (communityId == null && currentCommunity?.id == null) {
      WToastUtil.show(
        '小区id不存在',
      );
      return;
    }
    if (!isLoad) params1['pageNum'] = 1;
    var res = await PayIndexServiceImpl().getPayList({
      ...params1,
      "communityId": communityId ?? currentCommunity?.id,
      "assetId": communityId ?? currentCommunity?.id,
      "billBehavior": 'prePayPay',
      "assetType": "communitys",
      "payStart": payBillAtEnd,
      "payEnd": payBillAtStart,
      "payWay": payWay,
    });

    final _data = res.data;
    final _list = _data?.list ?? [];

    if ((_data?.total ?? 0) == 0) {
      indexScorllViewKey1.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      indexScorllViewKey1.currentState?.isLast();
    } else {
      params1['pageNum']++;
    }
    isLoad ? paylist1.addAll(_list) : paylist1 = _list;
    notifyListeners();
  }

  ///押金缴费列表
  Future getDepositeList({bool isLoad = true}) async {
    if (communityId == null && currentCommunity?.id == null) {
      WToastUtil.show(
        '小区id不存在',
      );
      return;
    }
    if (!isLoad) params2['pageNum'] = 1;
    var res = await PayIndexServiceImpl().getPayList({
      ...params2,
      "communityId": communityId ?? currentCommunity?.id,
      "assetId": communityId ?? currentCommunity?.id,
      "billBehavior": 'depositePay',
      "assetType": "communitys",
      "payStart": payBillAtStart,
      "payEnd": payBillAtEnd,
      "payWay": payWay,
    });
    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      indexScorllViewKey2.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      indexScorllViewKey2.currentState?.isLast();
    } else {
      params2['pageNum']++;
    }
    isLoad ? paylist2.addAll(_list) : paylist2 = _list;
    notifyListeners();
  }

  List? billList;
  List? preList;
  List? depositeList;

  bool isShowList = false;

  /// 缴费统计
  Future getSummary() async {
    if (communityId == null && currentCommunity?.id == null) {
      WToastUtil.show(
        '小区id不存在',
      );
      return;
    }
    WLoadingUtil.show();
    var res = await PayIndexServiceImpl().getPaySummary({
      "communityId": communityId ?? currentCommunity?.id,
      "payAtStart": payAtStart,
      "payAtEnd": payAtEnd,
    });
    if (res.data != null) {
      isShowList = true;
      summary = res.data;
      billList = res.data?.bill;
      preList = res.data?.prePay;
      depositeList = res.data?.deposite;
      WLoadingUtil.hide();
      notifyListeners();
    }
  }

  /// 跳转详情
  void routeToDetail(item) {
    Navigator.pushNamed(context, 'paylist/detail', arguments: item.toJson());
  }

  List feeTypes = [];

  /// 缴费详情
  Future getDetail() async {
    var res = await PayIndexServiceImpl().getPayDetail(routingArgs['id'], {
      "billType": routingArgs['billType']['code'],
    });
    payDetail = res.data;
    res.data?.list?.forEach((element) {
      if (feeTypes.contains(element.feeType) != true) {
        feeTypes.add(element.feeType);
      }
    });
    feeTypes = feeTypes;
    notifyListeners();
  }

  String? payAtStart;
  String? payAtEnd;

  String? payAtStartDate;
  String? payAtEndDate;

  /// 选择起始时间
  onPickStartDate(date) {
    payAtStart = date;
    chooseButton = null;
    if (date == null && payAtEnd == null) {
      isShowList = false;
    }
    notifyListeners();
  }

  /// 选择结束时间
  onPickEndDate(date) {
    payAtEnd = date;
    chooseButton = null;
    if (date == null && payAtStart == null) {
      isShowList = false;
    }
    notifyListeners();
  }

  String? chooseButton;

  void onChooseDateButton(date) {
    chooseButton = date;
    notifyListeners();
    switch (date) {
      case 'today':
        payAtStart = DateTime.now().toFormat(WisDateTimeFormat.date);
        payAtEnd = DateTime.now().toFormat(WisDateTimeFormat.date);
        notifyListeners();
        break;
      case 'yesterday':
        var preDay = DateTime.now().add(Duration(days: -1));
        payAtStart = preDay.toFormat(WisDateTimeFormat.date);
        payAtEnd = preDay.toFormat(WisDateTimeFormat.date);
        notifyListeners();
        break;
      case 'week':
        var preDay = DateTime.now().add(Duration(days: -6));
        payAtStart = preDay.toFormat(WisDateTimeFormat.date);
        payAtEnd = DateTime.now().toFormat(WisDateTimeFormat.date);
        notifyListeners();
        break;
      case 'thismonth':
        var preDay =
            DateTime.now().add(Duration(days: -(DateTime.now().day) + 1));
        payAtStart = preDay.toFormat(WisDateTimeFormat.date);
        payAtEnd = DateTime.now().toFormat(WisDateTimeFormat.date);
        notifyListeners();
        break;
      case 'lastmonth':
        var preEndDay =
            DateTime.now().add(Duration(days: -(DateTime.now().day)));
        var preDay = preEndDay.add(Duration(days: -(preEndDay.day) + 1));

        payAtStart = preDay.toFormat(WisDateTimeFormat.date);
        payAtEnd = preEndDay.toFormat(WisDateTimeFormat.date);
        notifyListeners();
        break;
    }
    onFilterSummary();
  }

  /// 筛选收款统计
  onFilterSummary() {
    if (payAtStart == null || payAtEnd == null) {
      WToastUtil.show('请先选择起始时间跟结束时间~');
      return;
    }
    communityINameBySubmit = communityIName;
    payAtStartDate = payAtStart;
    payAtEndDate = payAtEnd;
    notifyListeners();
    getSummary();
  }

  /// 账单筛选开始时间
  String? payBillAtStart;

  /// 账单筛选结束时间
  String? payBillAtEnd;

  /// 选择筛选账单缴费起始时间
  onPickBillStartDate(date) {
    payBillAtStart = date;
    notifyListeners();
  }

  /// 选择账单缴费结束时间
  onPickBillEndDate(date) {
    payBillAtEnd = date;
    notifyListeners();
  }

  bool filterShow = false;

  /// 跳转筛选
  onSetFilterShow() async {
    await Get.toNamed('paylist/filter', arguments: {
      'payWay': payWay,
      'payBillAtStart': payBillAtStart,
      'payBillAtEnd': payBillAtEnd,
      'communityId': communityId,
      'communityIName': communityIName,
      'isFilterPage': true,
    })!
        .then((res) {
      if (res != null) {
        payWay = res['payWay'];
        payBillAtStart = res['payBillAtStart'];
        payBillAtEnd = res['payBillAtEnd'];
        communityId = res['communityId'];
        communityIName = res['communityIName'];
        notifyListeners();
        onhandleFilter();
      }
    });
  }

  /// 筛选条件
  onhandleFilter() {
    switch (tabNum) {

      /// 筛选账单缴费
      case 0:
        params["pageNum"] = 1;
        billList = [];
        indexScorllViewKey0.currentState?.initTrigger();
        break;

      /// 筛选预存款缴费
      case 1:
        params1["pageNum"] = 1;
        preList = [];
        indexScorllViewKey1.currentState?.initTrigger();
        break;

      /// 筛选押金缴费
      case 2:
        params2["pageNum"] = 1;
        depositeList = [];
        indexScorllViewKey2.currentState?.initTrigger();
        break;
      default:
        break;
    }
  }

  /// 支付方式
  int? payWay;

  ///支付方式列表
  List payWayList = [
    {'code': null, 'name': '全部'},
    {'code': 0, 'name': '线下'},
    {'code': 1, 'name': '线上'}
  ];

  /// 筛选支付方式 0：线下 1：线上
  onChoosePayWay(data) async {
    payWay = data;
    notifyListeners();
  }

  /// 所选小区对象
  CommunityPickerModel? communityList;

  /// 所选小区名称
  String communityIName = '';

  /// 确定之后显示的所选小区名称
  String communityINameBySubmit = '';

  /// 获取小区列表
  Future<List<CommunityPickerModel>> getAsyncCommunityList() async {
    var res = await EmployeeApi.getDomainCommunityListToPicker();
    return res.data ?? [];
  }

  /// 选择小区
  onChooseCommunity(CommunityPickerModel res) {
    communityId = res.id ?? '';
    communityList = res;
    communityIName = res.name ?? '';
    notifyListeners();
  }

  /// 筛选重置
  onResetInner() {
    Get.back(result: {
      'payWay': null,
      'payBillAtStart': null,
      'payBillAtEnd': null,
      'communityId': null,
      'communityIName': null,
      'communityList': null,
    });
  }

  back() {
    Get.back();
  }

  /// 确认筛选
  submit() {
    Get.back(result: {
      'payWay': payWay,
      'payBillAtStart': payBillAtStart,
      'payBillAtEnd': payBillAtEnd,
      'communityId': communityId,
      'communityIName': communityIName,
    });
  }
}
