import 'package:get/get.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/view/common/base_choose_person.dart';

///@Description     选择列表
///@author          lixiuming
///@create          2023-11-17 16:28
class ChooseList extends BaseChoose {
  Map<String, dynamic> api;

  ChooseList({Map person, this.api}) : super(person: person);

  @override
  BaseChooseState getBaseChoosePersonState() => _ChooseList(api: api);
}

class _ChooseList extends BaseChooseState {
  Map<String, dynamic> api;

  _ChooseList({this.api}) : super();

  @override
  Future<void> getData() => _getData();

  @override
  String getIdKey() => _getIdKey();

  @override
  String getNameKey() => _getNameKey();

  Future<void> _getData() async {
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      String url = api['apiPath'];
      String httpMethod = api['httpMethod'];
      List<dynamic> queryParams = api['queryParams'];

      Map<String, dynamic> params = {};
      if (queryParams != null) {
        for (int i = 0; i < queryParams.length; i++) {
          Map queryParam = queryParams[i];
          params[queryParam['name']] = queryParam['value']['value'];
        }
      }

      dynamic resp;
      if (httpMethod == 'POST') {
        resp = await API.postDynamicSelectList(url, params);
      } else {
        var newUrl = '';
        for (final key in params.keys) {
          newUrl += key + '=' + params[key] + '&';
        }
        if (newUrl.isNotEmpty) {
          newUrl = newUrl.substring(0, newUrl.length - 1);
        }
        url = url + '?' + newUrl;
        resp = await API.getDynamicSelectList(url);
      }
      if (resp == null) {
        return;
      }
      // 判断resp的类型：如果是List，则直接赋值给persons；如果是Map，则将Map的键值对赋值给persons
      List<dynamic> options = [];
      if (resp is List) {
        options = resp;
      }
      if (resp is Map) {
        options = (resp['records'] ?? []).map((e) => {_getIdKey(): e[_getNameKey()]}).toList();
      }
      Get.back();
      setState(() {
        persons.addAll(options);
      });
    });
  }

  String _getIdKey() {
    Map ruleData = api['ruleData'];
    if (ruleData!= null) {
      return ruleData['valueKey'];
    }
    return null;
  }

  String _getNameKey() {
    Map ruleData = api['ruleData'];
    if (ruleData!= null) {
      return ruleData['nameKey'];
    }
    return null;
  }
}
