/*
 * @Author       : WuWei
 * @LastEditors  : WuWei
 * @Date         : 2021-04-15 15:28:36
 * @LastEditTime : 2023-06-15 15:45:42
 * @FilePath     : /wisdom-huiguanjia-app/search_package/lib/src/view_models/add_resident_store.dart
 * @Description  : Do not edit
 */

import 'package:app_package/app_package.dart';
import 'package:collection/collection.dart' show IterableExtension;
import 'package:flutter/material.dart';
import 'package:mobx/mobx.dart';
import 'package:search_package/src/impl/searchindex_service_impl.dart';
import 'package:search_package/src/models/cascade_house.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import '../pages/add_resident/index.dart';
part 'add_resident_store.g.dart';

class AddResidentStore = _AddResidentStore
    with _$AddResidentStore, ChangeNotifier;

abstract class _AddResidentStore with Store {
  ///上下文（请勿修改）
  final BuildContext context1;

  ///路由参数（请勿修改）
  AddresidentPageArguments get arguments =>
      AddresidentPageArguments.fromRouteArguments(context1);
  String? get id => arguments.id ?? null;

  bool get isEdit => arguments.isEdit ?? false;
  String get title => id != null ? '编辑住户' : '添加住户';

  _AddResidentStore(this.context1) {
    ///可在此处理进入页面前的操作，比如响应路由的传参进行赋值。
  }

  /// 表单的key
  final formKey = GlobalKey<WFormState>();

  @observable
  var detail;

  @action
  onSetDetail(data) {
    detail = data;
  }

  /// 表单的值
  @observable
  Map<String, dynamic> formValue = {
    'billOwner': false,
  };
  @observable
  String? name;
  @observable
  String? mobile;
  @action
  Future getResidentDetail() async {
    if (isEdit != true) {
      return;
    }
    late Map<String, dynamic> params = {
      'residentId': id,
    };
    var res =
        await SearchIndexServiceImpl.instance!.getResidentDetail({...params});
    onSetDetail(res.data);
    formValue['name'] = detail?.name;
    name = detail?.name;
    formValue['sex'] = detail?.sex;
    formValue['mobile'] = detail?.mobile;
    mobile = detail?.mobile;
    formValue['identity'] = detail?.identity;
    formValue['billOwner'] = detail?.billOwner;
    formValue['certificateType'] = detail?.certificateType;
    formValue['idNumber'] = detail?.idNumber;
    formValue['address'] = detail?.address;
    formValue['remark'] = detail?.remark;
    formValue['residenceStartAt'] = detail?.residenceStartAt;
    formValue['residenceEndAt'] = detail?.residenceEndAt;
    formValue['otherMobile'] = detail?.otherMobile;
    formValue['houseId'] = detail?.otherMobile;
    formValue = formValue;
    // residentDetail = res?.data ?? SearchResidentDetailModel();
    // notifyListeners();
  }

  @action
  Future onAddResident() async {
    if (onCheckForm() != true) {
      return;
    }
    if (isEdit != true) {
      await onHandleAdd();
    } else {
      await onHandleEdit();
    }
  }

  /// 新增
  Future<void> onHandleAdd() async {
    final Map<String, dynamic>? values = formKey.currentState!.values;
    final res = await SearchIndexServiceImpl.instance!.postAddResident({
      ...formValue,
      'houseId': values!['house'][3].id,
      'isEnduring': formValue['residenceEndAt'] != null ? false : true,
    });
    if (res != null) {
      WToastUtil.show('添加用户成功！');
      Navigator.pop(context1);
    }
  }

  var idcardInfo = {
    'IdCard': "身份证",
    'HKAndMacaoPass': "港澳通行证",
    'officerCertificate': "军官证",
    'other': "其他",
  };
  String? operationEvent;

  /// 编辑
  Future<void> onHandleEdit() async {
    // 修改{房屋}住户，姓名：{旧姓名}->{新姓名}，手机号：{旧手机号}->{新手机号}，{证件类型}：{旧证件号}->{新证件号}
    if (formValue['name'] != detail.name ||
        formValue['mobile'] != detail.mobile ||
        formValue['certificateType'] != detail.certificateType ||
        formValue['idNumber'] != detail.idNumber) {
      operationEvent =
          '修改${detail?.roomNo}住户，${(formValue['name'] != detail.name) ? '姓名：${detail.name}->${formValue['name']}，' : ''}${(formValue['mobile'] != detail.mobile) ? '手机号：${detail.mobile}->${formValue['mobile']}，' : ''}${(formValue['idNumber'] != detail.idNumber) ? '${idcardInfo[formValue['certificateType']]}：${detail?.idNumber ?? ''}->${formValue['idNumber'] ?? ''}' : ''}';
    }
    final res = await SearchIndexServiceImpl.instance!.patchEditResident(id, {
      ...formValue,
      'isEnduring': formValue['residenceEndAt'] != null ? false : true,
      'operationEvent': operationEvent,
    });
    if (res != null) {
      WToastUtil.show('编辑用户成功！');
      Navigator.pop(context1);
    }
  }

// 校验身份证合法性
  bool verifyCardId(String? cardId) {
    const Map city = {
      11: "北京",
      12: "天津",
      13: "河北",
      14: "山西",
      15: "内蒙古",
      21: "辽宁",
      22: "吉林",
      23: "黑龙江 ",
      31: "上海",
      32: "江苏",
      33: "浙江",
      34: "安徽",
      35: "福建",
      36: "江西",
      37: "山东",
      41: "河南",
      42: "湖北 ",
      43: "湖南",
      44: "广东",
      45: "广西",
      46: "海南",
      50: "重庆",
      51: "四川",
      52: "贵州",
      53: "云南",
      54: "西藏 ",
      61: "陕西",
      62: "甘肃",
      63: "青海",
      64: "宁夏",
      65: "新疆",
      71: "台湾",
      81: "香港",
      82: "澳门",
      91: "国外 "
    };
    // ignore: unused_local_variable
    String tip = '';
    bool pass = true;

    RegExp cardReg = RegExp(
        r'^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$');
    if (cardId == null || cardId.isEmpty || !cardReg.hasMatch(cardId)) {
      tip = '身份证号格式错误';
      pass = false;
      return pass;
    }
    if (city[int.parse(cardId.substring(0, 2))] == null) {
      tip = '地址编码错误';
      pass = false;
      return pass;
    }
    // 18位身份证需要验证最后一位校验位，15位不检测了，现在也没15位的了
    if (cardId.length == 18) {
      List numList = cardId.split('');
      //∑(ai×Wi)(mod 11)
      //加权因子
      List factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
      //校验位
      List parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
      int sum = 0;
      int ai = 0;
      int wi = 0;
      for (var i = 0; i < 17; i++) {
        ai = int.parse(numList[i]);
        wi = factor[i];
        sum += ai * wi;
      }
      if (parity[sum % 11].toString() != numList[17]) {
        tip = "校验位错误";
        pass = false;
      }
    } else {
      tip = '身份证号不是18位';
      pass = false;
    }
    return pass;
  }

  /// 手机号
  final regExpPhone = RegExp(r"1[3456789]\d{9}$");

  /// 固话
  final regExpTel = RegExp('^[0-9]{0,12}\$');

  /// 校验表单
  bool onCheckForm() {
    final values = formKey.currentState?.values;

    if (isEdit != true &&
        (values == null ||
            values['house'] == null ||
            values['house'][3] == null ||
            values['house'][3].id == null)) {
      WToastUtil.show('请完成带红色*表单');
      return false;
    }
    if (formValue['name'] == null ||
        formValue['mobile'] == null ||
        formValue['sex'] == null ||
        formValue['identity'] == null ||
        formValue['billOwner'] == null) {
      WToastUtil.show('请完成带红色*表单');
      return false;
    }

    if (formValue['certificateType'] != null &&
        (formValue['idNumber'] == null || formValue['idNumber'] == '')) {
      WToastUtil.show('请完成带红色*表单');
      return false;
    }
    if (formValue['identity'] != 'enterprise' &&
        regExpPhone.hasMatch(formValue['mobile']) == false) {
      WToastUtil.show('请输入正确的手机号码');
      return false;
    }

    if (formValue['identity'] == 'enterprise' &&
        regExpPhone.hasMatch(formValue['mobile'] ?? '') == false &&
        regExpTel.hasMatch(formValue['mobile'] ?? '') == false) {
      WToastUtil.show('请输入正确的电话号码');
      return false;
    }

    if (formValue['certificateType'] == 'IdCard' &&
        (formValue['idNumber'] == null ||
            formValue['idNumber'] == '' ||
            verifyCardId(formValue['idNumber']) == false)) {
      WToastUtil.show('请输入正确的身份证号码');
      return false;
    }
    return true;
  }

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

  ///房号==============
  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);

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

      default:
        final res = await SearchIndexServiceImpl.instance!.getBuildInfo({
          'communityId': communityGlobalStore.data.id,
        });
        back = res.data;
    }
    return back ?? [];
  }

  /// 房屋号
  // @action
  // void onSetHouse(v) {
  //   formValue['houseId'] = v;
  // }

  /// 住户姓名
  @action
  void onSetName(v) {
    formValue['name'] = v;
  }

  /// 性别
  @action
  void onSetSex(v) {
    formValue['sex'] = v;
  }

  /// 手机号
  @action
  void onSetMobile(v) {
    formValue['mobile'] = v.trim();
  }

  /// 住户性质
  @action
  void onSetProperty(v) {
    formValue['identity'] = v;
    formValue = formValue;
  }

  ///账单权属人
  @action
  void onSetPeople(v) {
    formValue['billOwner'] = v;
  }

  /// 证件类型
  @action
  void onSetCertType(v) {
    formValue['certificateType'] = v;
    formValue = formValue;
  }

  /// 证件号码
  @action
  void onSetCertNum(v) {
    formValue['idNumber'] = v.trim();
  }

  /// 居住开始时间
  @observable
  String? residenceStartAt;
  @action
  void onSetStarDate(v) {
    formValue['residenceStartAt'] = v;
    residenceStartAt = v;
  }

  /// 居住截止时间
  @observable
  String? residenceEndAt;
  @action
  void onSetEndDate(v) {
    formValue['residenceEndAt'] = v;
    residenceEndAt = v;
  }

  /// 其他号码
  @action
  void onSetOtherNum(v) {
    formValue['otherMobile'] = v;
  }

  /// 常住地址
  @action
  void onSetAddress(v) {
    formValue['address'] = v;
  }

  /// 备注
  @action
  void onSetRemark(v) {
    formValue['remark'] = v;
  }
}
