/*
 * @Author: XianKaiQun
 * @Date: 2020-09-04 09:52:46
 * @LastEditors: wuwei
 * @LastEditTime: 2024-01-16 16:06:30
 * @Description: 
 */
import 'dart:async';

import 'package:app_package/app_package.dart';
import 'package:face_package/src/models/cascade.dart';
import 'package:face_package/src/models/door_group.dart';
import 'package:face_package/src/models/face_detail.dart';
import 'package:face_package/src/models/pass_card.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 PrivateDetailStore with ChangeNotifier {
  final BuildContext context, providerContext;
  late Map<String, dynamic> routingArgs;
  PrivateDetailStore(this.context, this.providerContext) {
    routingArgs = (ModalRoute.of(context)?.settings.arguments ??
            new Map<String, dynamic>()) as Map<String, dynamic>? ??
        {};
    WisStorageUtil.set(key: 'face-list-refresh', data: false);
  }
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

  String? get id => routingArgs['id'];
  String? get communityId => communityGlobalStore.data.id;

  ///审核状态筛选
  final statusMap = {
    0: '全部',
    1: '待审核',
    2: '待下发',
    3: '审核通过',
    4: '禁止通行',
    5: '被拒绝',
    6: '已失效',
  };

  ///与申请人关系
  final relationMap = {
    1: '本人',
    2: '父亲',
    3: '母亲',
    4: '儿子',
    5: '女儿',
    6: '公公',
    7: '婆婆',
    8: '岳父',
    9: '岳母',
    10: '兄弟',
    11: '姐妹',
    12: '其他',
  };

  ///当前是否在编辑状态
  bool isEdit = false;
  isEditChange() {
    isEdit = !isEdit;
    notifyListeners();
  }

  ///数据初始化
  FaceDetailModel? data;
  Future initData() async {
    await Future.wait([getData(), getPassCardList()]);
  }

  Future<void> getData() async {
    final res = await FaceAuditServiceImpl().getFaceDetail(id);
    data = res.data ?? FaceDetailModel();
    imageId = data?.photo;
    if (data?.expirationTime != null && data!.expirationTime!.isNotEmpty) {
      modifyForm!['expirationTime'] = DateTime.parse(data!.expirationTime!);
    }
    if (data?.doorGroups != null && data!.doorGroups!.isNotEmpty) {
      modifyForm!['doorGroups'] = data!.doorGroups!
          .map((e) => DoorGroupModel(
              doorGroupId: e.doorGroupId, doorGroupName: e.doorGroupName))
          .toList();
    }
    notifyListeners();
  }

  Map<String, Object> auditData = {};
  final auditFormkey = GlobalKey<WFormState>();

  ///关联住户
  ///房屋列表只选择申请人已有房屋
  ///
  Future<List<EnumModel>> getOwnerData() async {
    final res = await FaceAuditServiceImpl().getOwnerByParams({
      'mobile': data!.mobile,
      'name': data!.residentName,
      'communityId': communityId,
    });

    /// 列表为空
    if (res.data!.isEmpty == true) {
      WToastUtil.show('未匹配到同姓名同手机号住户，请先添加住户');
    }
    return res.data ?? [];
  }

  ///门禁组列表
  Future<List<DoorGroupModel>> getAuditList() async {
    final communityId = communityGlobalStore.data.id;
    final res = await FaceAuditServiceImpl().getdoorGroupList(communityId);
    return res.data ?? [];
  }

  final formKey = GlobalKey<WFormState>();
  String? imageId;

  ///编辑表单
  Map<String, Object?>? modifyForm = {
    'doorGroups': null, //门禁组   List
    'expirationTime': null, //失效日期
    'resident': null, //租户相关  EnumModel
  };
  formChange() {
    modifyForm = formKey.currentState?.values;
  }

  /// 人脸选择
  void facePicker() async {
    ///记录从哪选择的照片（相机或相册）
    WImageSource? source;
    var res = await WAssetPickerUtil.image(
      maxCount: 1,
      sourceCallBack: (s) => source = s,
    );
    if (res.length == 0) return;

    final imageId = await WNavUtil.instance!.pushNamed(
      'face/edit',
      arguments: {
        'path': res[0].file!.path,
        'source': source,
      },
    );
    if (imageId != null) {
      this.imageId = imageId as String?;
      notifyListeners();
    }
  }

  ///拒绝
  Future<void> onRefuse(String? str) async {
    if (str == null) {
      WToastUtil.show('请输入拒绝理由');
      return;
    }
    final res = await FaceAuditServiceImpl().putFaceAuditRefuse({
      'id': data!.id,
      'remark': str,
    });
    if (res == 1) {
      WToastUtil.show('拒绝成功');
      await initData();
      WNavUtil.instance!.popUntil(
        (route) => route.settings.name == 'face/detail',
      );
      backListRefresh();
    } else {
      WToastUtil.show('拒绝失败');
    }
  }

  ///允许通行
  Future<void> onPassed() async {
    final Map<String, dynamic> form = formKey.currentState!.values!;
    final List<DoorGroupModel>? doorGroups = form['doorGroups'];
    if (doorGroups == null) {
      WToastUtil.show('通行门禁组不可为空');
      return;
    }

    final EnumModel? resident = form['resident'];

    // 2024.01.16 取消住户校验
    // print(resident);
    // if ((data!.residentId?.isEmpty == true) || resident == null) {
    //   WToastUtil.show('关联住户不可为空');
    //   return;
    // }

    List<String?> doorGroupIds = doorGroups.map((e) => e.doorGroupId).toList();

    final residentId = resident?.code ?? data!.residentId;

    final expirationTime = form['expirationTime'] != null
        ? (form['expirationTime'] as DateTime).toFormat()
        : null;
    final res = await FaceAuditServiceImpl().putFaceAuditAllow({
      'id': data!.id,
      'residentId': residentId,
      'doorGroupIds': doorGroupIds,
      'expirationTime': expirationTime,
    });
    if (res == 1) {
      await initData();
      backListRefresh();
    }
  }

  ///提交修改
  Future<void> onModify() async {
    final Map<String, dynamic> form = formKey.currentState!.values!;

    final List<DoorGroupModel>? doorGroups = form['doorGroups'];
    if (imageId == null && data!.openDoorWay != 'scanCard') {
      WToastUtil.show('人脸图片不可为空');
      return;
    }
    if (doorGroups == null) {
      WToastUtil.show('通行门禁组不可为空');
      return;
    }

    final EnumModel? resident = form['resident'];
     // 2024.01.16 取消住户校验
    // if ((data!.residentId?.isEmpty == true) || resident == null) {
    //   WToastUtil.show('关联住户不可为空');
    //   return;
    // }

    List<String?> doorGroupIds = doorGroups.map((e) => e.doorGroupId).toList();
    final residentId = data!.residentId ?? resident?.code;

    final expirationTime = form['expirationTime'] != null
        ? (form['expirationTime'] as DateTime).toFormat()
        : null;
    final res = await FaceAuditServiceImpl().postFaceModify({
      'id': data!.id,
      'photo': imageId,
      'residentId': residentId,
      'doorGroupIds': doorGroupIds,
      'expirationTime': expirationTime,
      'doorCard': data?.doorCards?.join(',') ?? '',
    });
    if (res == 1) {
      isEditChange();
      await initData();
      backListRefresh();
    }
  }

  // 通行证列表
  List<PassCardDetailModel> passCardList = [];
  bool isAbleDeleteAllPass = false; // 允许删除全部通行证
  bool isAbleOperation = false; // 允许操作
  bool isAbleModify = false; // 允许修改、重新下发、
  Future<void> getPassCardList() async {
    var res = await FaceAuditServiceImpl().getPassCardList(id);
    passCardList = res.data ?? [];
    notifyListeners();
  }

  bool isOverDate() {
    if (data?.expirationTime != null && data!.expirationTime!.isNotEmpty) {
      var preDay = DateTime.now().add(Duration(days: -1));
      var expirationTime = DateTime.parse(data!.expirationTime!);
      return expirationTime.isBefore(preDay);
    } else {
      return false;
    }
  }

  // 1: '待下发',2: '未通过',3: '已通过',4: '待设备删除'
  bool isAllStatus(status) {
    return passCardList.isNotEmpty == true &&
        passCardList.every((item) => item.status == status);
  }

  bool isSomeStatus(status) {
    return passCardList.isNotEmpty == true &&
        passCardList.any((item) => item.status == status);
  }

  ///设置返回刷新
  backListRefresh() {
    WisStorageUtil.set(key: 'face-list-refresh', data: true);
  }

// 审核记录status  1：待审核  3：审核通过  5：被拒绝
//  按钮控制：
//  待审核：通过，拒绝
//  被拒绝：修改，删除
//  审核通过：1，通行证列表为空时: (已失效) => 修改，拒绝通行，（未失效）=> 重新下发,修改，拒绝通行
//  2，通行证全部通过时：删除全部通行证
//  3，通行证全部未通过：重新下发，删除全部通行证，
//  4，部分通行证通过，部分未通过时：重新下发未通过，删除全部通行证

  Future<void> onDeleteRecord() async {
    bool? confirm = await WModalUtil.showSync('确定删除审核记录吗?');
    if (confirm!) {
      var res = await FaceAuditServiceImpl().deleteRecord(data?.id);
      if (res == 1) {
        WToastUtil.show('删除成功');
        backListRefresh();
        Navigator.pop(context);
      } else {
        WToastUtil.show('删除失败');
      }
    }
  }

  Future<void> onDeleteAllPassCard() async {
    bool? confirm = await WModalUtil.showSync('确定删除全部通行证吗?');
    if (confirm == true) {
      var res = await FaceAuditServiceImpl().deleteAllPassCard(data?.id);
      if (res == true) {
        getPassCardList();
        WToastUtil.show('删除成功');
        backListRefresh();
      } else {
        WToastUtil.show('删除失败');
      }
    }
  }

  Future<void> rePushAllPassCard() async {
    var res = await FaceAuditServiceImpl().putPassCardRePush(data?.id);
    if (res == true) {
      getPassCardList();
      WToastUtil.show('下发成功');
      // backListRefresh();
    } else {
      WToastUtil.show('下发失败');
    }
  }
}
