import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:marking_app/common/mixin/common.dart';
import 'package:marking_app/common/model/common/base_structure_result.dart';
import 'package:marking_app/common/model/marking/marking_abnormal_res.dart';
import 'package:marking_app/utils/request/rest_client.dart';
import 'package:marking_app/utils/toast_utils.dart';

class UseAbnormal with CommonMixin {
  ValueNotifier<Map<String, String>> abnormals; // 设置主页
  ValueNotifier<String?> abnormalsReason; // 设置主页

  UseAbnormal._({required this.abnormals, required this.abnormalsReason});

  factory UseAbnormal.use() {
    return UseAbnormal._(abnormals: useState({}), abnormalsReason: useState(null));
  }

  getData() async {
    RestClient client = await getClient();
    BaseStructureResult<MarkingAbnormalRes> result = await client.getAbnormalTypes();
    MarkingAbnormalRes? data = result.data;
    if (result.success && data != null) {
      Map<String, String> errorsTypeDic = {};
      data.errorsTypeDic.forEach((key, value) => errorsTypeDic[value] = key);
      abnormals.value = errorsTypeDic;
    }
  }

  submit(BuildContext context, TextEditingController controller, Function(String? reasonType, String? reason) call) {
    String? reasonType = abnormals.value[abnormalsReason.value];
    String? reason = controller.text;
    if (reasonType == null) {
      return ToastUtils.getFluttertoast(context: context, msg: '请选择异常类型');
    }
    print(reason);
    if (reasonType == '-1' && (reason == null || reason.length <= 0)) {
      return ToastUtils.getFluttertoast(context: context, msg: '请填写异常原因');
    }
    call(reasonType, reason);
  }
}
