/*
 * @Author: ChenYaJin
 * @Date: 2021-11-09 14:42:04
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2023-03-31 09:37:52
 * @Description: 
 */
import 'package:app_package/app_package.dart';
import 'package:collection/collection.dart' show IterableExtension;
import 'package:flutter/widgets.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import '../service/report_service.dart';
import '../service/impl/report_service_impl.dart';
import '../models/cascade_house.dart';
import '../models/service_project.dart';
import '../models/service_fee_detail.dart';
import '../models/report_detail.dart';
import '../api/api.dart';

class FeeIndexStore with ChangeNotifier {
  final BuildContext context;
  Map? args;
  FeeIndexStore(this.context) {
    args =
        ModalRoute.of(context)!.settings.arguments as Map<dynamic, dynamic>? ??
            {};
    checkboxs = [];
    entCode = WisStorageUtil.get(key: 'storage-loginInfo')['entCode'];
  }

  ReportDetailModel? reportDetail;
  ServiceFeeDetailModel? serviceFeeDetail;
  List<FeeDetail>? list = [];
  String? entCode = '';

  ///当前小区
  String get currentCommunityId => reportDetail!.communityId ?? '';
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();
  final ReportService _reportService = ReportServiceImpl();
  final feeDetailKey = GlobalKey<WisScrollViewState>();

  // 获取费用详情
  Future getFeeDetail() async {
    if (args!['serviceFeeId'] != null) {
      var res = await _reportService
          .getServiceFeeDetaill({'id': args!['serviceFeeId']});
      serviceFeeDetail = res.data;
      list = serviceFeeDetail?.serviceFeeDetails ?? [];
      notifyListeners();
    } else {
      serviceFeeDetail = null;
      list = [];
      notifyListeners();
    }
  }

  bool get isPaied =>
      (serviceFeeDetail?.receivedFee ?? 0).toDouble() > 0 ||
      (serviceFeeDetail?.discountFee ?? 0).toDouble() > 0;

  bool get ableManage =>
      serviceFeeDetail?.paymentStatus != null &&
      serviceFeeDetail?.paymentStatus == 'unCleared';

  bool get hasServiceFee => args!['serviceFeeId'] != null;

  /// 跳转服务费用添加
  route2AddFee() async {
    final res =
        await Navigator.pushNamed(context, 'report/fee/add', arguments: args);
    // 添加后刷新
    if (res != null) {
      args = res as Map<dynamic, dynamic>?;
      getFeeDetail();
    }
  }

  /// 返回服务费用详情
  route2FeeDetailNotRefresh() {
    Navigator.pop(context);
  }

  route2FeeDetail() {
    Navigator.pop(context, args);
  }

  /// 跳转服务费用管理
  route2ManageFee() async {
    final res = await Navigator.pushNamed(context, 'report/fee/manage',
        arguments: args);
    // 删除后刷新
    if (res != null) {
      args = res as Map<dynamic, dynamic>?;
      getFeeDetail();
    }
  }

  /// 获取报修详情  首次添加费用时的房屋数据需要
  initAddData() async {
    if (args!['serviceFeeId'] == null || args!['serviceFeeId'] == '') {
      var res = await _reportService.getReportDetail({'id': args!['id']});
      reportDetail = res.data;
      notifyListeners();
    } else {
      getFeeDetail();
    }
  }

  final formKey = GlobalKey<WFormState>();
  Map<String, dynamic>? formValue = {
    'house': null,
    'payServiceProject': null,
    'quantity': '',
    'fee': '',
  };
  dynamic price = 0.0;
  dynamic quantity = 0.0;
  bool isHasPriceAndUnit = false;
  String fee = '¥--';

  formChange() {
    formValue = formKey.currentState?.values;
    notifyListeners();
  }

  selectProject(ServiceProject project) {
    isHasPriceAndUnit = formValue!['payServiceProject']?.price != null &&
        formValue!['payServiceProject']?.price != '';
    if (formValue!['payServiceProject'] != null) {
      formValue!['price'] = formValue!['payServiceProject'].price;
      formValue!['unit'] = formValue!['payServiceProject'].unit;
      formValue!['quantity'] = '';
      formValue!['fee'] = '';
      price = 0.0;
      quantity = 0.0;
      setFee();
    }
    notifyListeners();
  }

  changeQuantity(String value) {
    formValue!['quantity'] = value;
    setFee();
  }

  setFee() {
    price = double.parse(formValue!['price'] is num
        ? formValue!['price'].toString()
        : formValue!['price']);
    quantity = double.parse(
        formValue!['quantity'] != null && formValue!['quantity'] != ''
            ? formValue!['quantity']
            : '0');
    fee = quantity > 0 ? '¥' + (price * quantity).toStringAsFixed(2) : '¥--';
    notifyListeners();
  }

  String get priceAndUnit => isHasPriceAndUnit
      ? '${formValue!['payServiceProject']?.price}元/${formValue!['payServiceProject']?.unit}'
      : '--';

  bool get hasSelectProject => formValue!['payServiceProject'] != null;

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

    final build = list.firstWhereOrNull((e) => e.status == 'build');
    final unit = list.firstWhereOrNull((e) => e.status == 'unit');
    final floor = list.firstWhereOrNull((e) => e.status == 'floor');
    final last = list.lastWhereOrNull((e) => true);

    switch (last?.status) {
      case 'build':
        final res = await RequestApi().getUnitInfo({
          'communityId': currentCommunityId,
          'buildId': build!.id,
        });
        back = res.data;
        break;
      case 'unit':
        final res = await RequestApi().getFloorInfo({
          'communityId': currentCommunityId,
          'buildId': build!.id,
          'unitId': unit!.id,
        });
        back = res.data;
        break;
      case 'floor':
        final res = await RequestApi().getHouseInfo({
          'communityId': currentCommunityId,
          'buildId': build!.id,
          'unitId': unit!.id,
          'houseFloor': floor!.id,
        });
        back = res.data;
        break;

      default:
        final res = await RequestApi().getBuildInfo({
          'communityId': currentCommunityId,
        });
        back = res.data;
    }
    return back ?? [];
  }

  // 项目列表
  List<ServiceProject> projectList = [];
  Future<List<ServiceProject>> getProjectList() async {
    if (projectList.isNotEmpty && projectList.length > 1) {
      return setDisabled();
    } else {
      var res = await _reportService
          .getServiceProjectList({'communityId': currentCommunityId});
      projectList = res.data ?? [];
      return setDisabled();
    }
  }

  List<ServiceProject> setDisabled() {
    projectList = projectList
        .map((item) => ServiceProject(
            id: item.id,
            name: item.name,
            unit: item.unit,
            price: item.price,
            disabled: list!.any(
                (e) => e.payServiceProjectId.toString() == item.id.toString())))
        .toList();
    return projectList;
  }

  // 添加费用校验
  Future toCreateFee() async {
    final Map<String, dynamic> values = formKey.currentState!.values!;
    final houseData = (reportDetail?.houseId?.isNotEmpty ?? false)
        ? reportDetail!.houseId
        : (serviceFeeDetail?.houseId?.isNotEmpty ?? false)
            ? serviceFeeDetail!.houseId
            : values['house'];
    final hasHouse = houseData != '' && houseData != null;
    final hasProject = values['payServiceProject'] != null;
    final hasFee = isHasPriceAndUnit
        ? quantity > 0
        : formValue!['fee'] != '' && (double.parse(formValue!['fee'])) > 0;
    if (!hasHouse || !hasProject || !hasFee) {
      final message = !hasHouse
          ? '请选择房屋！'
          : !hasProject
              ? '请选择项目！'
              : '请填写${isHasPriceAndUnit ? '数量' : '金额'}！';
      WToastUtil.show(message);
      return;
    }
    args!['serviceFeeId'] == null || args!['serviceFeeId'] == ''
        ? postAddFee()
        : putAddFee();
  }

  // 首次新增费用
  Future postAddFee() async {
    final Map<String, dynamic> values = formKey.currentState!.values!;
    CascadeHouseModel? house = values['house']?.firstWhere(
      (e) => e.status == 'house',
    );
    var res = await _reportService.postServiceFee({
      'communityId': serviceFeeDetail?.communityId ?? currentCommunityId,
      'serviceType': 'report',
      'relationId': args!['id'],
      'houseId': reportDetail!.houseId != '' && reportDetail!.houseId != null
          ? reportDetail!.houseId
          : house?.id,
      'payServiceProjectId': values['payServiceProject'].id,
      'quantity': isHasPriceAndUnit ? values['quantity'] : '',
      'fee': isHasPriceAndUnit
          ? quantity * price
          : double.parse(formValue!['fee']),
    });

    if (res is String) {
      WToastUtil.show('费用添加成功！');
      args!['serviceFeeId'] = res;
      route2FeeDetail();
      setBackLstRefresh();
    } else {
      WToastUtil.show('费用添加失败！');
    }
  }

  List<FeeDetail> checkboxs = [];
  onCheckboxchange(FeeDetail item, bool check) {
    int index = checkboxs.indexWhere((e) => e.id == item.id);
    item.check = check;
    if (check) {
      checkboxs.add(item);
    } else {
      checkboxs.removeAt(index);
    }
    notifyListeners();
  }

  // 删除数据处理
  toDeleteFee() async {
    if (checkboxs.isEmpty) {
      return;
    }
    var deleteFee = 0.00;
    checkboxs.forEach((item) {
          deleteFee += (item.fee is num
              ? item.fee!
              : double.parse(item.fee as String? ?? '0'));
        });
    final ids = checkboxs.map((item) => item.id).toList();
    deleteAddFee(ids, deleteFee);
  }

  // 批量删除费用
  Future deleteAddFee(deletesids, deleteFee) async {
    var totalFee = 0.00;
    list!.forEach((item) {
          totalFee += (item.fee is num
              ? item.fee!
              : double.parse(item.fee as String? ?? '0'));
        });
    var res = await _reportService.putServiceFee(args!['serviceFeeId'], {
      'serviceFee': (totalFee - deleteFee).toStringAsFixed(2),
      'deleteDetailIds': deletesids,
    });

    if (res is int) {
      WToastUtil.show('费用删除成功！');
      if (deletesids.length == list!.length) {
        args!['serviceFeeId'] = null;
        setBackLstRefresh();
        route2FeeDetail();
      } else {
        route2FeeDetail();
      }
    } else {
      WToastUtil.show('费用删除失败！');
    }
  }

  // 已有基础上新增费用
  Future putAddFee() async {
    final Map<String, dynamic> values = formKey.currentState!.values!;
    var serviceFee = 0.00;
    list!.forEach((item) {
          serviceFee +=
              (item.fee is num ? item.fee! : double.parse(item.fee.toString()));
        });
    final dealFee = isHasPriceAndUnit
        ? price * quantity
        : (formValue!['fee'] is num
            ? formValue!['fee']
            : double.parse(formValue!['fee'].toString()));
    serviceFee += dealFee;
    var res = await _reportService.putServiceFee(args!['serviceFeeId'], {
      'payServiceProjectId': values['payServiceProject'].id,
      'quantity': values['quantity'],
      'fee': isHasPriceAndUnit
          ? price * quantity
          : (formValue!['fee'] is num
              ? formValue!['fee']
              : double.parse(formValue!['fee'].toString())),
      'serviceFee': serviceFee.toStringAsFixed(2),
    });

    if (res is int) {
      WToastUtil.show('费用添加成功！');
      setBackLstRefresh();
      route2FeeDetail();
    } else {
      WToastUtil.show('费用添加失败！');
    }
  }

  setBackLstRefresh() {
    WisStorageUtil.set(key: 'report_list_refresh', data: true);
  }
}
