/*
 * @Author: WuWei
 * @Date: 2020-08-07 11:29:42
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2023-11-03 10:34:27
 * @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';
import '../models/pay_type.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['assetId'] != null) {
      assetId = routingArgs['assetId'];
    }

    if (routingArgs['assetType'] != null) {
      assetType = routingArgs['assetType'];
    }
    notifyListeners();
    initTab();
  }

  String? assetId;
  String? assetType;
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

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

  final indexScrollViewKey0 = GlobalKey<WisScrollViewState>();
  final indexScrollViewKey1 = GlobalKey<WisScrollViewState>();
  final indexScrollViewKey2 = GlobalKey<WisScrollViewState>();
  final indexScrollViewKey3 = 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,
  };
  String billSearchWord = '';
  String depositSearchWord = '';
  String preSearchWord = '';
  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;

  get getMoneyFlowName => getMoneyFlowNameFun(payDetail);
  getMoneyFlowNameFun(detail) {
    if (detail?.invalid == true) {
      return '作废';
    } else if (detail?.moneyFlow == 'in') {
      return '收入';
    } else if (detail?.moneyFlow == 'out') {
      return '支出';
    } else {
      return '--';
    }
  }

  get getMoneyFlowColor => getMoneyFlowColorFun(payDetail);
  getMoneyFlowColorFun(detail) {
    if (detail?.invalid == true) {
      return Color(0xff9FA5B7);
    } else if (detail?.moneyFlow == 'in') {
      return Color(0xff00C78C);
    } else if (detail?.moneyFlow == 'out') {
      return Color(0xffFF495E);
    } else {
      return Color(0xff00C78C);
    }
  }

// 支付方式 tag主色
  getPayWayColorFun(payWay) {
    if (payWay == '线下') {
      return Color(0xff0F67F8);
    } else if (payWay == '线上') {
      return Color(0xffFF495E);
    } else {
      return Color(0xffF99B1A);
    }
  }

  /// 发票、收据类型
  final InvoiceTypes = {
    'invoice': '发票',
    'receipt': '收据',
    'onlineReceipt': '线上收据',
    'electronic': '普通电子发票',
    'redSpecial': '红字专用发票',
    'vatSpecial': '增值税专用发票',
    'general': '普通发票',
    'special': '专用发票',
  };

  /// 缴费类型1
  final billTypeName = {
    'assetBill': '账单',
    'prePay': '预存款',
    'deposit': '押金',
    'tempPay': '临时账单',
  };

  /// 缴费类型2
  final inOutName = {
    'in': '缴费',
    'out': '退费',
  };

  /// inOutType = in / out
  getBillTypeText(detail) {
    return '${billTypeName[routingArgs['billType']['code']]}${inOutName[detail?.moneyFlow] ?? '--'}';
  }

  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) {
      if (routingArgs['payWayCodesFirst'] != null) {
        payWayCodesFirst = routingArgs['payWayCodesFirst'];
        notifyListeners();
      }
      setTab(argtab);
    }
  }

  getNonessentialParams() {
    var params = {};
    params['moneyFlow'] =
        ['in', 'out'].contains(currentBehaviorType) ? currentBehaviorType : '';
    params['invalid'] = currentBehaviorType == behaviorMenu['CANCEL'];
    return params;
  }

  toBillSearchList(word) {
    billSearchWord = word;
    indexScrollViewKey0.currentState?.initTrigger();
  }

  toPreSearchList(word) {
    preSearchWord = word;
    indexScrollViewKey1.currentState?.initTrigger();
  }

  toDepositSearchList(word) {
    depositSearchWord = word;
    indexScrollViewKey3.currentState?.initTrigger();
  }

  /// 账单缴费列表
  Future getList({bool isLoad = true}) async {
    if (communityId == null && currentCommunity?.id == null) {
      WToastUtil.show(
        '小区id不存在',
      );
      return;
    }
    if (!isLoad) params['pageNum'] = 1;
    final nonessentialParams = getNonessentialParams();
    var res = await PayIndexServiceImpl().getPayList({
      ...params,
      "communityId": communityId ?? currentCommunity?.id,
      "assetId": assetId ?? communityId ?? currentCommunity?.id,
      "billBehavior": 'billPay',
      "assetType": assetType != null
          ? assetType == 'owner'
              ? 'owner'
              : '${assetType}s'
          : "communitys",
      "payStart": payBillAtStart,
      "payEnd": payBillAtEnd,
      "payWays": payWays,
      "payTypes": getPayTypes,
      'fuzzyAssetName': billSearchWord,
      ...nonessentialParams,
    });
    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      indexScrollViewKey0.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      indexScrollViewKey0.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;
    final nonessentialParams = getNonessentialParams();
    var res = await PayIndexServiceImpl().getPayList({
      ...params1,
      "communityId": communityId ?? currentCommunity?.id,
      "assetId": assetId ?? communityId ?? currentCommunity?.id,
      "billBehavior": 'prePayPay',
      "assetType": assetType != null
          ? assetType == 'owner'
              ? 'owner'
              : '${assetType}s'
          : "communitys",
      "payStart": payBillAtStart,
      "payEnd": payBillAtEnd,
      "payWays": payWays,
      "payTypes": getPayTypes,
      'fuzzyAssetName': preSearchWord,
      ...nonessentialParams,
    });

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

    if ((_data?.total ?? 0) == 0) {
      indexScrollViewKey1.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      indexScrollViewKey1.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;
    final nonessentialParams = getNonessentialParams();
    var res = await PayIndexServiceImpl().getPayList({
      ...params2,
      "communityId": communityId ?? currentCommunity?.id,
      "assetId": assetId ?? communityId ?? currentCommunity?.id,
      "billBehavior": 'depositePay',
      "assetType": assetType != null
          ? assetType == 'owner'
              ? 'owner'
              : '${assetType}s'
          : "communitys",
      "payStart": payBillAtStart,
      "payEnd": payBillAtEnd,
      "payWays": payWays,
      "payTypes": getPayTypes,
      'fuzzyAssetName': depositSearchWord,
      ...nonessentialParams,
    });
    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      indexScrollViewKey2.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      indexScrollViewKey2.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, 'pay_record/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;
    payDetail?.id = routingArgs['id'];
    notifyListeners();
  }

  PayDetail? refundDetail;
  bool showDetail = false;

  /// 缴费详情
  Future getRefundDetail() async {
    var res = await PayIndexServiceImpl().getPayDetail(payDetail?.originalId, {
      "billType": routingArgs['billType']['code'],
    });
    refundDetail = res.data;
    refundDetail?.id = payDetail?.originalId;
    notifyListeners();
  }

  onSetShowDetail(flag) {
    showDetail = flag;
    notifyListeners();
    if (showDetail && refundDetail?.id == null) {
      getRefundDetail();
    }
  }

  get getAccountStatusName => getAccountStatusNameFun();

  getAccountStatusNameFun() {
    var name = '';
    switch (payDetail?.accountStatus) {
      case 'notAccount':
        name = '普通录单';
        break;
      case 'inAccount':
        name = '挂帐中';
        break;
      case 'account':
        name = '挂帐录单';
        break;
      default:
        name = '普通录单';
        break;
    }
    return name;
  }

  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('pay_record/filter', arguments: {
      'currentBehaviorType': currentBehaviorType,
      'payBillAtStart': payBillAtStart,
      'payBillAtEnd': payBillAtEnd,
      'communityId': communityId ?? currentCommunity?.id,
      'communityIName': communityIName,
      'payWayCodesFirst': payWayCodesFirst,
      'payWayCodesSecond': payWayCodesSecond,
    })!
        .then((res) {
      if (res != null) {
        currentBehaviorType = res['currentBehaviorType'];
        payBillAtStart = res['payBillAtStart'];
        payBillAtEnd = res['payBillAtEnd'];
        communityId = res['communityId'];
        communityIName = res['communityIName'];
        payWayCodesFirst = res['payWayCodesFirst'];
        payWayCodesSecond = res['payWayCodesSecond'];
        notifyListeners();
        onhandleFilter();
      }
    });
  }

  toSummaryPage() async {
    await Get.toNamed('pay_record/summary');
  }

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

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

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

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

  /// 业务行为 全部/收入/支出/作废
  final Map<String, String> behaviorMenu = {
    'ALL': 'all',
    'IN': 'in',
    'OUT': 'out',
    'CANCEL': 'cancel',
  };

  String currentBehaviorType = 'all';

  /// 支付方式
  get payWays => payWaysFun();

  payWaysFun() {
    if (payWayCodesFirst.contains('all')) {
      return '';
    } else {
      return payWayCodesFirst.join("','");
    }
  }

  get getPayTypes => getPayTypesFun();

  getPayTypesFun() {
    if (payWayCodesFirst.contains('all')) {
      return '';
    } else {
      return payWayCodesSecond.join("','");
    }
  }

  List<dynamic> payWayCodesFirst = [];
  List<dynamic> payWayCodesSecond = [];

  var payTypeList = [];
  PayTypeModel? payTypeAllList = null;

  /// 所选小区对象
  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();
  }
}
