/*
 * @Author: XianKaiQun
 * @Date: 2020-07-29 11:48:08
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-02-08 15:48:02
 * @Description: 
 */
import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:qrcode_package/src/common/common.dart';
import 'package:qrcode_package/src/impl/qr_service_impl.dart';
import 'package:qrcode_package/src/impl/repair_service_impl.dart';
import 'package:qrcode_package/src/models/repair_equipment_norm.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

class PrivateRepairHandleStore with ChangeNotifier {
  final BuildContext context, providerContext;
  late Map<String, dynamic> routingArgs;
  PrivateRepairHandleStore(this.context, this.providerContext) {
    routingArgs = (ModalRoute.of(context)?.settings.arguments ??
            new Map<String, dynamic>()) as Map<String, dynamic>? ??
        {};
  }

  ///表单类型
  ///[pqc] 巡检 否则保养
  String? get type => routingArgs['type'];

  ///接受参数
  String? get id => routingArgs['id'];

  ///标题
  String get title => type == 'pqc' ? '巡检' : '养护';

  ///规范
  RepairEquipmentNormModel? norm;

  ///设备id
  String? get equipmentId => norm?.id;

  ///统一请求
  Future getData() async {
    await Future.wait([
      getNorm(),
      antiCheat(),
    ]);
    notifyListeners();
  }

  ///获取规范
  Future<void> getNorm() async {
    final res = await RepairServiceImpl.instance!.getEquipmentNorm({
      'type': type,
      'id': id,
    });
    norm = res.data ?? RepairEquipmentNormModel();
    for (var item in norm!.operators!) {
      contents['${item.id}'] = null;
    }
  }

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

  String? get communityId => communityGlobalStore.data.id;

  ///是否必须拍照
  bool cheatPhoto = false;

  ///是否必须上传位置
  bool cheatLocation = false;

  ///最大随机拍照照片数量(默认一张)
  int? cheatPhotoMaxCount = 1;

  ///获取防作弊配置
  Future<void> antiCheat() async {
    final res = await QrServiceImpl.instance!.getCheatSetting({
      'communityId': communityId,
      'qrcodeType': 5, //巡检、保养为5
    });
    if (res.data?.isNotEmpty ?? false) {
      final data = res.data![0];

      ///此二维码是否在白名单内,白名单不做限制
      if ((data.qrcodeManagementIds?.indexOf(id) ?? -1) != -1) {
        return;
      }
      cheatLocation = data.uploadCoord ?? false;

      ///如果要求随机拍照  需要再校验一次必须拍照的概率
      ///然后通过概率计算必须拍照的概率
      if (data.randomTakePhoto == true) {
        cheatPhoto = await AntiCheating.instance!.probability(
          data.takePhotoCheckProb ?? 100,
          id,
        );
      }
      //最大随机拍照照片数量
      if (data.takePhotoFrame != null) {
        cheatPhotoMaxCount = data.takePhotoFrame as int?;
      }
    }
  }

  route2detail() {
    Navigator.pushNamed(
      context,
      'qrcode/repair_detail',
      arguments: {'id': equipmentId},
    );
  }

  ///表单内容---------------------------------------
  ///后续还需要转换成
  /// [
  ///   {'opreateId':'xxx',
  ///   content:'content',
  ///   },
  ///   ...
  /// ]
  Map<String?, String?> contents = {
    // 'item.opreateId': 'content',
  };

  ///单选
  onRadioChange(String? id, String? value) {
    contents[id] = value;
    notifyListeners();
  }

  ///多选
  ///先切割字符串到数组，然后操作数组 添加或者移除，然后转换成字符串
  onCheckBoxChange(String? id, String value, bool boolean) {
    var checkboxs = [];
    if (contents[id] != null) {
      checkboxs = contents[id]?.split(',').toList() ?? [];
    }
    if (boolean) {
      checkboxs.add(value);
    } else {
      checkboxs.remove(value);
    }
    contents[id] = checkboxs.join(',');
    notifyListeners();
  }

  ///输入框
  onInputChange(String? id, String value) {
    contents[id] = value;
  }

  ///图片
  Future onImagePicker(String? id, int maxCount) async {
    final imageIds = contents[id]?.split(',').toList() ?? [];
    final files = await WAssetPickerUtil.image(
      maxCount: maxCount,
      source: WImageSource.cameraAndGallery,
    );
    if (files.isNotEmpty == true) {
      final futures =
          files.map((e) => GlobalApi.postUploadImage(e.file)).toList();
      final res = await Future.wait(futures);

      imageIds.addAll(res.map((e) => e!.data!));
      contents[id] = imageIds.join(',');
      notifyListeners();
    }
  }

  ///图片
  removeImage(String? id, String value) {
    final imageIds = contents[id]?.split(',').toList() ?? [];
    imageIds.remove(value);
    contents[id] = imageIds.join(',');
    if (contents[id]!.isEmpty) {
      contents[id] = null;
    }
    notifyListeners();
  }

  ///------------------------------

  ///防作弊图片列表
  List<String> imageIds = [];

  ///防作弊拍照
  Future photograph() async {
    final files = await WAssetPickerUtil.image(
      source: WImageSource.camera,
      maxCount: cheatPhotoMaxCount! - imageIds.length,
    );
    if (files.isNotEmpty) {
      final futures =
          files.map((e) => GlobalApi.postUploadImage(e.file)).toList();
      final res = await Future.wait(futures);
      imageIds.addAll(
        res.map((e) => e!.data!),
      );
      notifyListeners();
    }
  }

  ///防作弊图片移除
  removeimageId(i) {
    imageIds.removeAt(i);
    notifyListeners();
  }

  ///定位 TOD
  // Future<BdLatLng> get getLocation async {
  //   final res = await WisLocaitonUtil.instance.getLocation();
  //   if ((res?.latLng?.latitude ?? 0.0) == 0.0) {
  //     WToastUtil.show('无法获取您的位置信息');
  //     return null;
  //   }
  //   return res?.latLng?.toBmap();
  // }

  Future submit() async {
    ///判断contents里是否存在null，防空表单
    final unFilled = contents.values.toList().indexWhere(
              (v) => ['', null].indexOf(v) != -1,
            ) !=
        -1;
    if (unFilled) {
      WToastUtil.show('请完成选项');
      return;
    }

    ///校验防作弊拍照必须性
    if (cheatPhoto && (imageIds.isEmpty)) {
      WToastUtil.show('请上传现场照片');
      return;
    }

    ///校验位置必须性
    // 定位  TOD
    // BdLatLng location;
    // if (cheatLocation) {
    //   location = await getLocation;
    //   if (location == null) return;
    // }

    final params = {
      'normId': norm!.normId,
      'photos': imageIds,
      // 定位  TOD
      // 'longitude': location?.longitude,
      // 'latitude': location?.latitude,
      'equipmentId': equipmentId,
      'mustUploadPhoto': cheatPhoto, //前端校验是否防作弊的结果
      'normAppAddFroms': contents.keys
          .map((e) => {
                'opreateId': e,
                'content': contents[e],
              })
          .toList(),
    };
    final res = await RepairServiceImpl.instance!.postCheck(params);
    if (res.data != null) {
      await AntiCheating.instance!.remove(id); //移除防作弊id
      final boolean = await WModalUtil.showSync(
        '成功',
        cancelText: '回首页',
        confirmText: '继续$title',
      );
      if (boolean!) {
       WNavUtil.instance!.pushNamedAndRemoveUntil(
      'main',
      (route) => false,
    );
      } else {
        Navigator.popAndPushNamed(
          context,
          'qrcode/repair_detail',
          arguments: {
            'id': equipmentId,
          },
        );
      }
    }
  }
}
