/*
 * @Author: WuWei
 * @Date: 2020-05-27 09:20:33
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2023-04-06 10:50:46
 * @Description:
 */
import 'package:app_package/app_package.dart';
import 'package:flutter/widgets.dart';
import 'package:search_package/src/impl/searchindex_service_impl.dart';
import 'package:search_package/src/models/search_house_list.dart';
import 'package:search_package/src/models/search_resident_list.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import '../models/search_car_list.dart';
import '../models/search_park_list.dart';

class SearchIndexStore with ChangeNotifier {
  final BuildContext context;
  late Map args;
  SearchIndexStore(this.context) {
    args =
        ModalRoute.of(context)!.settings.arguments as Map<dynamic, dynamic>? ??
            {};
  }

  final scorllViewKey1 = GlobalKey<WisScrollViewState>();
  final scorllViewKey2 = GlobalKey<WisScrollViewState>();
  final scorllViewKey3 = GlobalKey<WisScrollViewState>();
  final scorllViewKey4 = GlobalKey<WisScrollViewState>();

  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

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

  int currentIndex = 0;
  onSetTabIndex(index) {
    currentIndex = index;
    notifyListeners();
  }

  /// 车辆类型 [carType]
  final Map carType = {
    'smallCar': '小型汽车',
    'mediumCar': '中型汽车',
    'largeCar': '大型汽车',
    'motorcycle': '摩托车',
    'electricBike': '电动自行车',
    'tricycle': '三轮车'
  };

  final Map parkType = {
    'titleParking': '产权车位',
    'publicParking': '公共车位',
    'defenseParking': '人防车位',
    'parkingCard': '停车卡',
    'storageRoom': '储藏间',
  };

  bool isSearch = false;
  bool isResidentSearch = false;
  bool isCarSearch = false;
  bool isParkSearch = false;

  late Map residentListparams = {
    'pageNum': 1,
    'pageSize': 20,
  };

  String residentKeyWord = '';
  String residentname = '';
  String residentMobile = '';


  late Map houseListparams = {
    'pageNum': 1,
    'pageSize': 20,
  };

  var roomNo = '';

  late Map carListparams = {
    'pageNum': 1,
    'pageSize': 20,
  };
  var carKeyWord = '';
  var fuzzyCarNo = '';
  var ownerName = '';

  late Map parkListParams = {
    'pageNum': 1,
    'pageSize': 20,
  };

  var parkingSpaceId = '';

  List<SearchCarListModel> carList = [];

  List<SearchHouseListModel> houseList = [];

  List<SearchResidentListModel> residentList = [];

  List<SearchParkListModel> parkList = [];

  ///去选择小区
  toCommunityPick() async {
    await Navigator.pushNamed(context, 'community');
    Navigator.pop(context);
  }

  /// 住户列表
  /// [isLoad] 是否加载 bool
  /// [residentListparams] 分页参数
  /// [residentname] 住户名字
  /// [residentMobile] 住户手机号
  /// [residentList] 返回的住户列表
  Future getResidentList({bool isLoad = true}) async {
    if (currentCommunity?.id == null) {
      toCommunityPick();
    }
    if ((residentname == '' && residentMobile == '')) {
      return;
    }

    var res = await SearchIndexServiceImpl.instance!.getResidentList({
      ...residentListparams,
      'communityId': currentCommunity?.id,
      'name': residentname,
      'mobile': residentMobile,
    });
    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      scorllViewKey1.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      scorllViewKey1.currentState?.isLast();
    } else {
      residentListparams['pageNum']++;
    }
    isLoad ? residentList.addAll(_list) : residentList = _list;
    notifyListeners();
  }

  /// 跳转住户详情
  /// params [item] 所选中列表项（住户）
  void route2ResidentDetail(SearchResidentListModel item) {
    Navigator.pushNamed(context, 'search/resident_detail',
        arguments: item.toJson());
  }

  /// 住户输入
  /// params [inputValue] 输入的值
  /// [pattern] 手机号正则
  void onInputResident(inputValue) {
    residentList = [];
    if (inputValue == '') {
      isResidentSearch = false;
    }
    residentKeyWord = inputValue;
    Pattern pattern = r'^\d{0,11}$';
    RegExp mobile = new RegExp(pattern as String);
    if (mobile.hasMatch(inputValue)) {
      residentname = '';
      residentMobile = inputValue;
    } else {
      residentname = inputValue;
      residentMobile = '';
    }
    onResidentSearch();
    notifyListeners();
  }

  /// 住户搜索
  /// [getResidentList] 直接请求列表
  void onResidentSearch() {
    isResidentSearch = true;
    residentList = [];
    residentListparams['pageNum'] = 1;
    // getResidentList(isLoad: true);
    scorllViewKey1.currentState?.initTrigger();
  }

  Future initResidentList() async {
    residentList = [];
    if (currentCommunity?.id == null) {
      toCommunityPick();
    }
    if (isResidentSearch) {
      getResidentList(isLoad: false);
    }
  }

  /// 获取房屋列表
  /// [isLoad] 是否加载 bool
  /// [houseListparams] 分页参数
  /// [roomNo] 房屋号
  /// [residentList] 返回的房屋列表
  Future<void> getHouseList({bool isLoad = true}) async {
    if (currentCommunity?.id == null) {
      toCommunityPick();
    }

    if (roomNo == '' || !isSearch) {
      return;
    }
    var res = await SearchIndexServiceImpl.instance!.getHouseList({
      ...houseListparams,
      'communityId': currentCommunity?.id,
      'roomNo': roomNo,
    });

    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      scorllViewKey2.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      scorllViewKey2.currentState?.isLast();
    } else {
      houseListparams['pageNum']++;
    }
    isLoad ? houseList.addAll(_list) : houseList = _list;
    notifyListeners();
  }

  /// 跳转住户详情
  /// params [item] 所选中列表项（住户）
  void route2HouseDetail(SearchHouseListModel item) {
    Navigator.pushNamed(context, 'search/house_detail',
        arguments: item.toJson());
  }

  /// 房屋号输入
  /// params [inputValue] 输入的值
  void onInputRoomNo(inputValue) {
    houseList = [];
    if (inputValue == '') {
      isSearch = false;
    }
    roomNo = inputValue;
    onHouseSearch();
    notifyListeners();
  }

  /// 房屋搜索
  /// [getHouseList] 直接请求列表
  void onHouseSearch() {
    isSearch = true;
    houseList = [];
    houseListparams['pageNum'] = 1;
    scorllViewKey2.currentState?.initTrigger();
  }

  Future initHouseList() async {
    houseList = [];
    if (isSearch) {
      getHouseList(isLoad: false);
    }
  }

  Future<void> getCarList({bool isLoad = true}) async {
    if (currentCommunity?.id == null) {
      toCommunityPick();
    }

    if (fuzzyCarNo == '' && ownerName == '') {
      return;
    }
    var res = await SearchIndexServiceImpl.instance!.getCarList({
      ...carListparams,
      'communityId': currentCommunity?.id,
      'fuzzyCarNo': fuzzyCarNo,
      'ownerName': ownerName,
    });

    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      scorllViewKey3.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      scorllViewKey3.currentState?.isLast();
    } else {
      carListparams['pageNum']++;
    }
    isLoad ? carList.addAll(_list) : carList = _list;
    notifyListeners();
  }

  void onInputCar(inputValue) {
    if (inputValue == '') {
      isCarSearch = false;
      carList = [];
    }
    carKeyWord = inputValue;
    Pattern pattern = r'[A-Za-z0-9]{1,6}$';
    // r'/^(?:[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领 A-Z]{1}[A-HJ-NP-Z]{1}(?:(?:[0-9]{5}[DF])|(?:[DF](?:[A-HJ-NP-Z0-9])[0-9]{4})))$|(?:[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领 A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9 挂学警港澳]{1})$/';
    RegExp reg = new RegExp(pattern as String);
    if (reg.hasMatch(inputValue)) {
      ownerName = '';
      fuzzyCarNo = inputValue;
    } else {
      ownerName = inputValue;
      fuzzyCarNo = '';
    }
    onCarSearch();
    notifyListeners();
  }

  void onCarSearch() {
    isCarSearch = true;
    carList = [];
    carListparams['pageNum'] = 1;
    scorllViewKey3.currentState?.initTrigger();
  }

  Future initCarList() async {
    carList = [];
    if (isCarSearch) {
      getCarList(isLoad: false);
    }
  }

  void route2CarDetail(item) {
    Navigator.pushNamed(context, 'search/car_detail', arguments: item.toJson());
  }

  Future<void> getParkList({bool isLoad = true}) async {
    if (currentCommunity?.id == null) {
      toCommunityPick();
    }

    if (parkingSpaceId == '') {
      return;
    }
    var res = await SearchIndexServiceImpl.instance!.getParkList({
      ...parkListParams,
      'communityId': currentCommunity?.id,
      'fuzzyCode': parkingSpaceId,
    });

    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      scorllViewKey4.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      scorllViewKey4.currentState?.isLast();
    } else {
      parkListParams['pageNum']++;
    }
    isLoad ? parkList.addAll(_list) : parkList = _list;
    notifyListeners();
  }

  // 输入
  void onInputPark(inputValue) {
    if (inputValue == '') {
      isParkSearch = false;
    }
    parkingSpaceId = inputValue;
    onParkSearch();
    notifyListeners();
  }

  void onParkSearch() {
    isParkSearch = true;
    parkList = [];
    parkListParams['pageNum'] = 1;
    scorllViewKey4.currentState?.initTrigger();
  }

  Future initParkList() async {
    parkList = [];
    if (isParkSearch) {
      getParkList(isLoad: false);
    }
  }

  void route2ParkDetail(item) {
    Navigator.pushNamed(context, 'search/park_detail',
        arguments: item.toJson());
  }

  Future<void> toAddresident() async {
    /// 未选择小区 则先去选择小区
    if (currentCommunity?.id == null) {
      await Navigator.pushNamed(context, 'community');
    }
    await Navigator.pushNamed(context, 'search/add_resident', arguments: {
      'isEdit': false,
      'id': null,
    });
    initResidentList();
  }
}
