/*
 * @Author: XianKaiQun
 * @Date: 2020-09-09 16:54:44
 * @LastEditors: wuwei
 * @LastEditTime: 2024-01-16 14:49:33
 * @Description: 
 */
import 'package:app_package/app_package.dart';
import 'package:collection/collection.dart' show IterableExtension;
import 'package:face_package/src/models/cascade.dart';
import 'package:face_package/src/models/door_group.dart';
import 'package:face_package/src/service/impl/face_audit_impl.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

class PrivateAddStore with ChangeNotifier {
  final BuildContext context, providerContext;
  Map<String, dynamic>? routingArgs;
  PrivateAddStore(this.context, this.providerContext) {
    routingArgs = (ModalRoute.of(context)?.settings.arguments ??
            new Map<String, dynamic>()) as Map<String, dynamic>? ??
        {};
  }
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

  String? get communityId => communityGlobalStore.data.id;

  ///表单
  final formKey = GlobalKey<WFormState>();
  Map<String, Object?> formData = {
    'doorGroups': null, //门禁组
    'resident': null, //关联住户
    'expirationTime': null, //失效日期
  };

  ///门禁组
  ///
  ///
  ///
  ///
  List<DoorGroupModel>? _doorGroupList; //缓存
  Future<List<DoorGroupModel>> getDoorGroupList() async {
    if (_doorGroupList == null) {
      final res = await FaceAuditServiceImpl().getdoorGroupList(communityId);
      _doorGroupList = res.data ?? _doorGroupList;
    }
    return _doorGroupList ?? [];
  }

  ///关联住户
  ///
  ///
  ///
  Future<List<CascadeModel>> getOwnerData(List<CascadeModel> list) async {
    List<CascadeModel>? 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 house = list.firstWhereOrNull((e) => e.status == 'house');
    final last = list.lastWhereOrNull((e) => true);

    switch (last?.status) {
      case 'build':
        final res = await FaceAuditServiceImpl().getUnitInfo({
          'communityId': communityId,
          'buildId': build!.id,
        });
        back = res.data;
        break;
      case 'unit':
        final res = await FaceAuditServiceImpl().getFloorInfo({
          'communityId': communityId,
          'buildId': build!.id,
          'unitId': unit!.id,
        });
        back = res.data;
        break;
      case 'floor':
        final res = await FaceAuditServiceImpl().getHouseInfo({
          'communityId': communityId,
          'buildId': build!.id,
          'unitId': unit!.id,
          'houseFloor': floor!.id,
        });
        back = res.data;
        break;
      case 'house':
        final res = await FaceAuditServiceImpl().getOwner({
          'houseId': house!.id,
        });
        back = res.data;
        break;
      default:
        final res = await FaceAuditServiceImpl().getBuildInfo({
          'communityId': communityGlobalStore.data.id,
        });
        back = res.data;
    }
    return back ?? [];
  }

  String? imageId;

  /// 人脸选择
  void facePicker() async {
    ///记录从哪选择的照片（相机或相册）
    WImageSource? source;
    var res = await WAssetPickerUtil.image(
      maxCount: 1,
      sourceCallBack: (s) => source = s,
    );
    if (res.length == 0) return;
    final id = await WNavUtil.instance!.pushNamed(
      'face/edit',
      arguments: {
        'path': res[0].file!.path,
        'source': source,
      },
    );
    if (id != null) {
      imageId = id as String?;
      notifyListeners();
    }
  }

  ///提交表单
  Future<void> submit() async {
    final Map<String, dynamic> formData = formKey.currentState!.values!;
    List<DoorGroupModel>? doorGroups = formData['doorGroups'];
    if (doorGroups == null || doorGroups.length == 0) {
      WToastUtil.show('通行门禁组不可为空');
      return;
    }
    final doorGroupIds = doorGroups.map((e) => e.doorGroupId).toList();

    List<CascadeModel>? residents = formData['resident'];
    if (residents == null || residents.length == 0) {
      return WToastUtil.show('关联住户不可为空');
    }
    final residentId =
        residents.firstWhere((element) => element.status == 'owner').id;

    if (imageId == null) {
      return WToastUtil.show('人脸照片不可为空');
    }
    final expirationTime =
        (formData['expirationTime'] as DateTime?)?.toFormat();

    final res = await FaceAuditServiceImpl().postFaceAdd({
      'doorGroupIds': doorGroupIds,
      'residentId': residentId,
      'communityId': communityId,
      'photo': imageId,
      'expirationTime': expirationTime,
    });
    if (res != null) {
      await WModalUtil.showSync('人脸添加成功', canCancel: false);
      Navigator.pop(context, true);
      // WNavUtil.instance.pop(true);
    }
  }
}
