/*
 * @Author: XianKaiQun
 * @Date: 2020-09-03 11:23:15
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-05-24 16:30:47
 * @Description: 
 */
import 'dart:async';

import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import '../service/impl/face_audit_impl.dart';
import '../models/face_audit_list_model.dart';
import '../models/device_detail.dart';

class PrivateIndexStore with ChangeNotifier {
  final BuildContext context;

  late Map<String, dynamic> routingArgs;

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

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

  /// 顶部tab 当前位置
  int tabIndex = 0;
  onSetTabIndex(index) {
    FocusScope.of(context).requestFocus(FocusNode());
    tabIndex = index;
    notifyListeners();
  }

  refresh() {
    final refresh = WisStorageUtil.get(key: 'face-list-refresh');
    if (refresh) {
      scorllViewListKey.currentState?.initTrigger();
    }
  }

  // 通行证管理-----------------------------------------------------
  final scorllViewListKey = GlobalKey<WisScrollViewState>();

  ///去详情
  Future<void> route2detail(String? id) async {
    await Navigator.pushNamed(context, 'face/detail', arguments: {'id': id});
    refresh();
  }

  ///去添加
  Future<void> route2add() async {
    Object? refresh = await Navigator.pushNamed(context, 'face/add');
    if (refresh == true) {
      faceList = [];
      notifyListeners();
      scorllViewListKey.currentState?.initTrigger();
    }
  }

  Map<String, dynamic> params = {
    'pageNum': 1,
    'pageSize': 20,
  };

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

  /// 设备状态
  final deviceStatusMap = {
    0: '离线',
    1: '在线',
  };

  SinglePickerEntity status = SinglePickerEntity(name: '全部', unique: 0);
  onStatusChange(SinglePickerEntity value) {
    if (value != status) {
      status = value;
      faceList = [];
      notifyListeners();
      scorllViewListKey.currentState?.initTrigger();
    }
  }

  String searchKey = '';
  onSearch(String t) {
    searchKey = t;
    faceList = [];
    notifyListeners();
    FocusScope.of(context).requestFocus(FocusNode());
    scorllViewListKey.currentState?.initTrigger();
  }

  ///人脸审核列表
  List<FaceAuditRecordModel> faceList = [];
  final FaceAuditServiceImpl _faceService = FaceAuditServiceImpl();

  Future getFaceList({bool isLoad = true}) async {
    if (!isLoad) params['pageNum'] = 1;
    if (currentCommunity?.id == null) {
      WToastUtil.show('小区不能为空！');
      return;
    }
    params['communityId'] = currentCommunity?.id;
    final regExp = RegExp(r"1[3456789]\d{9}$");
    final boolean = regExp.hasMatch(searchKey);
    String? mobile;
    String? fuzzyHouseName;
    if (boolean) {
      mobile = searchKey;
    } else {
      fuzzyHouseName = searchKey;
    }
    var res = await _faceService.getAppAdminFaceAuditRecordList({
      ...params,
      'fuzzyHouseName': fuzzyHouseName,
      'mobile': mobile,
      'status': status.unique == 0 ? null : status.unique,
    });
    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      scorllViewListKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      scorllViewListKey.currentState?.isLast();
    } else {
      params['pageNum']++;
    }
    isLoad ? faceList.addAll(_list) : faceList = _list;
    notifyListeners();
  }

  // 门禁设备-------------------------------------------------
  List<DeviceDetailModel> deviceList = [];
  List<DeviceDetailModel> originDeviceList = [];
  bool deviceSearchIng = true;
  final deviceScorllViewListKey = GlobalKey<WisScrollViewState>();

  onDeviceSearch(String keyWord) {
    deviceSearchIng = true;
    if (keyWord.isNotEmpty) {
      deviceList = originDeviceList
          .where((item) => item.name!.contains(keyWord))
          .toList();
    } else {
      deviceList = originDeviceList;
    }
    deviceSearchIng = false;
    notifyListeners();
    FocusScope.of(context).requestFocus(FocusNode());
  }

  Future getDoorDeviceList() async {
    deviceSearchIng = true;
    var res = await _faceService.getDoorDeviceList({
      'communityId': currentCommunity?.id,
    });
    final _list = res.data ?? [];
    if (_list.length == 0) {
      deviceScorllViewListKey.currentState?.isEmpty();
    }
    deviceList = _list;
    originDeviceList = _list;
    deviceSearchIng = false;
    notifyListeners();
  }

  // 门禁设备-远程开门
  Future<void> openDoorByRemote(data) async {
    bool? res = await FaceAuditServiceImpl().postDoorOpen(data.id);
    if (res == true) {
      WToastUtil.show('开门成功');
    } else {
      WToastUtil.show('开门失败');
    }
  }
}
