/*
 * @Author       : WuWei
 * @LastEditors: wuwei
 * @Date         : 2023-10-25 10:03:46
 * @LastEditTime: 2023-11-30 18:01:32
 * @Description  : Do not edit
 */
import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

import '../api/asset_bill.dart';
import '../models/asset_list.dart';
import '../models/fee_type.dart';
import '../models/identification.dart';

class OweFilterStore extends GetxController {
  final scrollViewKey = GlobalKey<WisScrollViewState>();
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

  CommunityModel? get community => communityGlobalStore.data;
  var assetList = [
    AssetsOfAssetListModel(
      name: '全部',
      code: '',
    ),
  ].obs;
  var feeTypeList = [
    FeeTypeModel(
      feeType: '全部',
      feeTypeId: '',
    )
  ].obs;

  var identificationList = [
    IdentificationModel(
      feeName: '全部',
      identification: '',
    )
  ].obs;

  /// 资产
  var assetId = ''.obs;

  String argAssetId = '';

  String assetType = '';

  String assetFullName = '';

  var assetItem = AssetsOfAssetListModel(
    name: '全部',
    code: '',
  ).obs;

  var feeTypeItem = FeeTypeModel(
    feeType: '全部',
    feeTypeId: '',
  ).obs;

  var identificationItem = IdentificationModel(
    feeName: '全部',
    identification: '',
  ).obs;

  /// 类型
  var feeTypeId = ''.obs;

  /// 服务分类
  var identification = ''.obs;

  bool get isFilterStatus => true;

  onInitData() async {
    argAssetId = Get.arguments['assetId'];
    assetType = Get.arguments['assetType'];
    assetFullName = Get.arguments['assetFullName'];
    await onGetFeeTypeList();
    await getAssetList();
    if (Get.arguments!['chargeYearMonthStart'] != null) {
      chargeYearMonthStart.value = Get.arguments['chargeYearMonthStart'];
    }
    if (Get.arguments['chargeYearMonthEnd'] != null) {
      chargeYearMonthEnd.value = Get.arguments['chargeYearMonthEnd'];
    }
    if (Get.arguments['assetItem'] != null) {
      assetItem.value = Get.arguments['assetItem'];
    }
    if (Get.arguments['feeTypeItem'] != null) {
      feeTypeItem.value = Get.arguments['feeTypeItem'];
      await findIdentification(feeTypeItem.value);
    }
    if (Get.arguments['identificationItem'] != null) {
      identificationItem.value = Get.arguments['identificationItem'];
    }
  }

  /// 按资产id获取全部关联资产
  Future getAssetList() async {
    var res = await AssetBillApi.getAssetListByAssetId({
      'assetId': argAssetId,
      'treeSelection': Get.arguments['assetType'],
      // 'treeSelection': 'house',
    });
    List<AssetsOfAssetListModel> _list = [];
    _list.add(AssetsOfAssetListModel(
      code: argAssetId,
      name: assetFullName,
      type: assetType,
    ));
    res.data?.forEach((item) {
          // if ((item.type == 'owner' || ||
          // item.type == 'waterMeter' ||
          // item.type == 'electricMeter'
          if ((item.type == 'house' ||
                  item.type == 'car' ||
                  item.type == 'parkingSpace') &&
              item.assets != null &&
              item.assets!.length > 0)
            {
              item.assets?.forEach((asset) {
                asset.type = item.type;
                _list.add(asset);
              });
            };
        });
    assetList.value = [...assetList, ..._list];
    assetList.refresh();
  }

  List allFeeTypeList = [];

  /// 获取费用类型列表
  Future onGetFeeTypeList() async {
    var res = await AssetBillApi.getChargeItemList({
      'communityId': community?.id,
    });
    allFeeTypeList = res.data ?? [];
    var _list = [];
    var _feetypeIdList = [];
    res.data?.forEach((element) {
      if (_feetypeIdList.contains(element.feeTypeId) != true) {
        _feetypeIdList.add(element.feeTypeId);
        _list.add(element);
      }
    });
    feeTypeList.value = [...feeTypeList, ..._list];
    feeTypeList.refresh();
  }

  /// 账单筛选开始时间
  var chargeYearMonthStart = DateTime(1900).obs;

  /// 账单筛选结束时间
  var chargeYearMonthEnd = DateTime.now().obs;

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

  /// 选择账单缴费结束时间
  onPickBillEndDate(date) {
    chargeYearMonthEnd.value = date;
  }

  /// 账期开始选择
  chooseStartMonth() async {
    var res = await WPickerUtil.month(
      Get.context!,
      title: WisText('选择日期'),
      firstDate: DateTime(1980),
      lastDate: chargeYearMonthEnd.value,
      initialDate: chargeYearMonthStart.value.year == 1900
          ? null
          : chargeYearMonthStart.value,
    );
    if (res != null) {
      chargeYearMonthStart.value = res;
    }
  }

  /// 账期结束选择
  chooseLastMonth() async {
    var res = await WPickerUtil.month(
      Get.context!,
      title: WisText('选择日期'),
      firstDate: chargeYearMonthStart.value, //DateTime(2010)
      lastDate: DateTime(2050),
      initialDate: chargeYearMonthEnd.value,
    );
    if (res != null) {
      chargeYearMonthEnd.value = res;
    }
  }

  /// 选择费用类型
  chooseFeeType() async {
    var res = await WPickerUtil.single<FeeTypeModel>(
      Get.context!,
      title: WisText('选择费用类型'),
      getData: () async => await feeTypeList,
      initialValue: feeTypeItem.value,
    );
    if (res != null) {
      feeTypeItem.value = res;
      identificationItem.value = IdentificationModel(
        feeName: '全部',
        identification: '',
      );
      findIdentification(res);
    }
  }

  /// 选择收费项目
  chooseIdentification() async {
    var res = await WPickerUtil.single<IdentificationModel>(
      Get.context!,
      title: WisText('选择收费项目'),
      getData: () async => await identificationList,
      initialValue: identificationItem.value,
    );
    if (res != null) {
      identificationItem.value = res;
    }
  }

  /// 查找所属收费项目
  findIdentification(item) {
    var _list = [];
    allFeeTypeList.forEach((element) {
      if (element.feeTypeId == item.feeTypeId) {
        _list.add(IdentificationModel(
          feeName: element.feeName,
          identification: element.identification,
        ));
      }
    });
    identificationList.value = [
      IdentificationModel(
        feeName: '全部',
        identification: '',
      )
    ];
    identificationList.value = [...identificationList, ..._list];
    identification.refresh();
  }

  /// 选择资产范围
  chooseAsset(asset) {
    assetItem.value = asset;
    assetId.value = asset.code;
  }

  back() {
    final params = {
      'isRefresh': false,
      'assetId': argAssetId,
      'assetType': assetType,
      'assetFullName': assetFullName,
    };
    backByParams(params);
  }

  backByParams(data) {
    Get.back(result: data);
  }

  onResetInner() {
    // chooseFeeType('');
    // chooseIdentification('');
    final params = {
      'feeTypeItem': FeeTypeModel(
        feeType: '全部',
        feeTypeId: '',
      ),
      'identificationItem': IdentificationModel(
        feeName: '全部',
        identification: '',
      ),
      'assetItem': AssetsOfAssetListModel(
        name: '全部',
        code: '',
      ),
      'chargeYearMonthEnd': DateTime.now(),
      'chargeYearMonthStart': DateTime(1900),
      'isRefresh': true,
    };
    backByParams(params);
  }

  submit() {
    final params = {
      'feeTypeItem': feeTypeItem.value,
      'identificationItem': identificationItem.value,
      'assetItem': assetItem.value,
      'chargeYearMonthEnd': chargeYearMonthEnd.value,
      'chargeYearMonthStart': chargeYearMonthStart.value,
      'isRefresh': true,
    };
    backByParams(params);
  }
}
