/*
 * @Author: XianKaiQun
 * @Date: 2020-07-28 11:52:50
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-02-07 17:15:52
 * @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/clean_service_impl.dart';
import 'package:qrcode_package/src/impl/qr_service_impl.dart';
import 'package:qrcode_package/src/models/clean_template.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

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

  String? get id => routingArgs['id'];
  CleanTemplateModel? tpl;

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

  ///获取模板
  Future getTpl() async {
    final res = await instance!.getCleanTemplate({
      'qrcodeManagementId': id,
    });
    tpl = res.data;

    ///初始化清单
    checkboxs = tpl?.cleanTemplateVos
            ?.map((e) => {'item': e.item, 'complete': false})
            .toList() ??
        [];
  }

  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': 4, //巡检、保养为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?;
      }
    }
  }

  ///去详情页
  route2list() {
    Navigator.pushNamed(
      context,
      'qrcode/clean_list',
      arguments: {'id': tpl!.id},
    );
  }

  ///清单选择
  List<Map<dynamic, dynamic>> checkboxs = [];

  onCheckboxchange(item, complete) {
    int index = checkboxs.indexWhere((e) => e['item'] == item);
    if (index != -1) {
      checkboxs[index]['complete'] = complete;
    }
    notifyListeners();
  }

  ///工作内容
  String remark = '';
  remarkChange(v) {
    remark = v;
  }

  ///异常备注
  String exRemark = '';
  exRemarkChange(v) {
    exRemark = v;
  }

  ///图片列表
  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 {
    FocusScope.of(context).requestFocus(FocusNode()); //失去焦点
    ///校验防作弊拍照必须性
    if (cheatPhoto && (imageIds.isEmpty)) {
      WToastUtil.show('请上传现场照片');
      return;
    }

    ///校验位置必须性
    // 定位  TOD
    // BdLatLng location;
    // if (cheatLocation) {
    //   // location = await getLocation;
    //   if (location == null) return;
    // }
    final params = {
      'qrcodeManagementId': id,

      // 定位  TOD
      // 'longitude': location?.longitude,
      // 'latitude': location?.latitude,
      'photos': imageIds,
      'remark': remark,
      'exRemark': exRemark,
      'mustUploadPhoto': cheatPhoto,
      'securityPatrolsAndCleanItemAppForms': checkboxs,
    };
    final res = await CleanServiceImpl.instance!.postCleanRecord(params);
    if (res.data != null) {
      await AntiCheating.instance!.remove(id); //移除防作弊id
      final boolean = await WModalUtil.showFormWidgetSync(
        cancelText: Text('查看详情'),
        confirmText: Text('回首页'),
        content: Text('成功'),
      );
      if (boolean!) {
        WNavUtil.instance!.pushNamedAndRemoveUntil(
      'main',
      (route) => false,
    );
      } else {
        Navigator.popAndPushNamed(
          context,
          'qrcode/clean_list',
          arguments: {
            'id': tpl!.id,
          },
        );
      }
    }
  }
}
