/*
 * @Author: XianKaiQun
 * @Date: 2020-08-06 10:37:11
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-07-18 15:51:13
 * @Description: 
 */

import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:qrcode_package/src/impl/register_service_impl.dart';
import 'package:qrcode_package/src/models/name_code.dart';
import 'package:qrcode_package/src/models/name_id.dart';
import 'package:qrcode_package/src/models/norm.dart';
import 'package:qrcode_package/src/models/place.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:intl/intl.dart';

class PrivateRegisterFormStore with ChangeNotifier {
  final BuildContext context, providerContext;
  late Map<String, dynamic> routingArgs;
  PrivateRegisterFormStore(this.context, this.providerContext) {
    routingArgs = (ModalRoute.of(context)?.settings.arguments ??
            new Map<String, dynamic>()) as Map<String, dynamic>? ??
        {};
    params['communityId'] = community!.id;
    params['communityName'] = community!.name;

    params['qrNumber'] = routingArgs['value'];
  }
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

  CommunityModel? get community => communityGlobalStore.data;
  String? get type => routingArgs['type'];

  late Map params = {
    'buidingId': "",
    'buidingName': "",
    'category': "",
    'communityId': "",
    'communityName': "",
    'equipmentRoomId': "",
    'equipmentTypeId': "",
    'houseId': "",
    'houseName': "",
    'housefloor': "",
    'installDate': "",
    'life': "1;1;1", //使用年限
    'maintenancecodeId': "",
    'managerId': "",
    'name': "",
    'number': "",
    'productDate': "",
    'productNumber': "",
    'qrNumber': "", //设备二维码
    'routinginspectionId': "",
    'status': "",
    'unitId': "", //单元
    'unitName': "",
  };

  List<PlaceModel> positionInfo = [];

  Future<void> init() async {
    params['status'] = 'open';
    params['statusName'] = '启用';
    notifyListeners();
    if (type != 'implement') {
      final res = await RegisterServiceImpl()
          .getPositionInfo({'communityId': community!.id});
      positionInfo.add(PlaceModel(
        id: res.data!.other!.value,
        name: res.data!.other!.label,
        status: res.data!.other!.type,
      ));
      res.data!.parkingLots!.forEach((item) {
            positionInfo.add(PlaceModel(
              id: item.value,
              name: item.label,
              status: item.type,
            ));
          });
      notifyListeners();
    }
  }

  String placeName = '';
  onParamsChange(String field, String value) {
    params[field] = value;
  }

  ///设备状态
  List<NameCodeModel>? statusList;
  Future<List<NameCodeModel>?> getStatusList() async {
    if (statusList != null) {
      return statusList;
    }
    final res = await RegisterServiceImpl().getStatusList({'method': '0'});
    statusList = res.data;
    return statusList;
  }

  statusPicker() async {
    final res = await WPickerUtil.single<NameCodeModel>(
      context,
      title: Text('设备状态'),
      getData: (() => getStatusList().then((value) => value!)),
      initialValue: NameCodeModel(code: params['status']),
    );
    if (res != null) {
      params['status'] = res.code;
      params['statusName'] = res.name;
      notifyListeners();
    }
  }

  ///所属位置
  List<PlaceModel>? placeList;

  String? _buildId;
  String? get currentCommunityId => community!.id ?? '';

  /// 获取位置列表
  Future<List<PlaceModel>?> getPlaceData(List<PlaceModel>? list) async {
    final last = list != null && list.length > 0
        ? list.lastWhere((e) => true, orElse: null)
        : null;

    if (last == null) {
      if (type == 'implement') {
        return [
          PlaceModel(name: '设备间', status: 'parent_rooms', id: '设备间'),
          PlaceModel(name: '楼栋', status: 'parent_build', id: '楼栋'),
          PlaceModel(name: '其他', status: 'parent_other', id: '其他'),
        ];
      } else {
        final res = await RegisterServiceImpl()
            .getBuildList({'communityId': community!.id});
        return res.data != null && res.data!.length > 0
            ? [...positionInfo, ...res.data!]
            : [];
      }
    }
    if (last.status == 'parent_rooms') {
      final res = await RegisterServiceImpl()
          .getRoomList({'communityId': community!.id});
      return res.data;
    }

    ///parent_build-build-unit-house
    //////house居然需要buildId然后unit中不返回！！！！
    ///无奈只能存下_buildId
    if (last.status == 'parent_build') {
      final res = await RegisterServiceImpl()
          .getBuildList({'communityId': community!.id});
      return res.data;
    }
    if (last.status == 'build') {
      _buildId = last.id;
      final res = await RegisterServiceImpl()
          .getUnitList({'communityId': community!.id, 'buildId': last.id});
      return res.data;
    }
    if (last.status == 'unit') {
      final res = await RegisterServiceImpl().getHouseList({
        'communityId': community!.id,
        'unitId': last.id,
        'buildId': _buildId,
        'houseFloor': ''
      });
      return res.data;
    }
    return null;
  }

  // Future<List>

  final formKey = GlobalKey<WFormState>();

  ///巡检规范
  pollingNormPicker() async {
    final res = await Navigator.pushNamed(
      context,
      'qrcode/norm_picker',
      arguments: {'type': 'pqc'},
    );
    routinginspectionId = res as NormModel;
    notifyListeners();
  }

  ///保养
  upkeepNormPicker() async {
    final res = await Navigator.pushNamed(
      context,
      'qrcode/norm_picker',
      arguments: {'type': 'upkeep'},
    );
    maintenancecodeId = res as NormModel;
    notifyListeners();
  }

  List<NameIdModel> catagoryChooseList = [];

  /// 获取设备品类列表
  Future<List<NameIdModel>> getCatagoryList(List<NameIdModel> list) async {
    final last =
        list.length > 0 ? list.lastWhere((e) => true, orElse: null) : null;
    if (last == null || list.length == 0) {
      final res = await RegisterServiceImpl()
          .getCatagoryList({'communityId': community!.id});
      return res.data ?? [];
    } else {
      final res = await RegisterServiceImpl().getEquipmentTypes(
          {'communityId': community!.id, 'categoryId': last.id});
      List<NameIdModel> list = [];
      list.add(NameIdModel(id: null, name: '不选择'));
      res['data'].forEach((item) => {
            list.add(
              NameIdModel(id: item['id'], name: item['type']),
            )
          });
      return list;
    }
  }

  NameIdModel? person;

  /// 选择负责人
  Future<void> choosePerson(v) async {
    person = v;
    notifyListeners();
  }

  /// 获取设备负责人列表
  Future<List<NameIdModel>?> getPersonList() async {
    final res = await RegisterServiceImpl().getEquipmentPersonList({
      'communityId': community!.id,
    });
    return res.data;
  }

  Future<List<NameIdModel>> getBlankList() async {
    return [];
  }

  String month = '';

  Future<void> chooseMonth(v) async {
    month = DateFormat('yyyy-MM').format(v);
    notifyListeners();
  }

  // 巡检规范
  NormModel? routinginspectionId;
  // 保养规范
  NormModel? maintenancecodeId;

  /// 提交表单
  ///
  // name: name,
  // number: number,
  // qrNumber: qrNumber,
  // category: category,
  // equipmentTypeId: equipmentTypeId,
  // buidingId: buidingId,
  // unitId: unitId,
  // housefloor: housefloor,
  // houseId: houseId,
  // productDate: productDate,
  // status: status,
  // routinginspectionId: routinginspectionId,
  // maintenancecodeId: maintenancecodeId,
  // productNumber: productNumber,
  // installDate: installDate,
  // equipmentRoomId: equipmentRoomId,
  // managerId: managerId,
  // communityId: communitys.value,
  // houseName: houseName,
  // buidingName: buidingName,
  // unitName: unitName,
  // life: newLife.join(";"),
  Future<void> submit() async {
    final values = formKey.currentState?.values;
    if (params['name'] == null || params['name'] == '') {
      WToastUtil.show('请输入名称~');
      return;
    }
    if (type == 'implement') {
      if (params['number'] == null) {
        WToastUtil.show('请输入编号~');
        return;
      }
      if (params['status'] == null) {
        WToastUtil.show('请选择设备状态~');
        return;
      }
    }
    if (values!['position'] == null) {
      WToastUtil.show('请选择所属位置~');
      return;
    }
    Map<String, dynamic> data = {
      'communityId': community!.id,
    };
    if (type == 'implement') {
      if (values['position'].length == 4) {
        data['buidingId'] = values['position'][1]?.id ?? null;
        data['buidingName'] = values['position'][1]?.name ?? null;
        data['unitId'] = values['position'][2]?.id ?? null;
        data['unitName'] = values['position'][2]?.name ?? null;
        data['houseId'] = values['position'][3]?.id ?? null;
        data['houseName'] = values['position'][3]?.name ?? null;
      }
      if (values['month'] != null) {
        data['productDate'] = DateFormat('yyyy-MM').format(values['month']);
      }
      data['qrNumber'] = routingArgs['value'];
      data['name'] = params['name'] != '' ? params['name'] : null;
      data['status'] = params['status'];
      data['number'] = params['number'] != '' ? params['number'] : null;
      data['productNumber'] = values['productNumber'];
      if (values['installDate'] != null) {
        data['installDate'] =
            DateFormat('yyyy-MM-dd').format(values['installDate']);
      }
      if (values['catagory'] != null && values['catagory'].length == 2) {
        data['category'] = values['catagory']?.first?.id ?? null;
        data['equipmentTypeId'] = values['catagory']?.last?.id ?? null;
      }

      data['managerId'] = values['person']?.id ?? null;
      data['routinginspectionId'] = routinginspectionId?.id ?? null;
      data['maintenancecodeId'] = maintenancecodeId?.id ?? null;
      data['life'] =
          '${values['uyear'] ?? ''};${values['umonth'] ?? ''};${values['uday'] ?? ''}';
      final res = await RegisterServiceImpl().postEquipment(data);
      if (res.data != null) {
        backHome();
      }
    } else {
      data['platformQrcodeNumber'] = routingArgs['value'];
      if (values['position'].length == 2) {
        data['positionId'] = values['position'][1]?.id;
        data['position'] = values['position'][1]?.name;
      }
      if (values['position'].length == 1) {
        data['positionId'] = values['position'][0]?.id;
        data['position'] = values['position'][0]?.name;
      }
      data['positionName'] = params['name'] != '' ? params['name'] : null;
      data['type'] = type == 'clean' ? 4 : 3;
      final res = await RegisterServiceImpl().postQrcode(data);
      if (res.data! > 0) {
        backHome();
      }
    }
  }

  backHome() async {
    bool confirm = (await WModalUtil.showSync('登记成功，继续登记或者返回首页?',
        cancelText: '继续登记', confirmText: '返回首页'))!;
    if (confirm) {
      Navigator.pushNamed(context, 'main');
    } else {
      Navigator.pop(context);
      Navigator.pop(context);
      await Route2business.scan2page(
        context: context,
        scene: ScanScene.qrRegister,
      );
    }
  }
}
