import 'dart:async';

import 'package:base/services/api_address.dart';
import 'package:base/utils/HttpUtil.dart';

import '../model/CheckItem.dart';
import '../model/ExtClass.dart';
import '../model/PlanTaskInitConfig.dart';

Future<PlanTaskInitConfig> getInitPlanTaskConfig(int planTaskId, int pointId) async {
  try {
    PlanTaskInitConfig planTaskInitConfig;
    //String url = ApiAddress.INIT_PLAN_TASK + '?pointId=' + pointId.toString();
    String url = ApiAddress.INIT_PLAN_TASK_V2 + '?pointId=' + pointId.toString();

    if (null != planTaskId && planTaskId > 0) {
      url = url + '&planTaskId=' + planTaskId.toString();
    }
    var data = await HttpUtil().get(url);
    if (data['result'] == 'SUCCESS') {
      if (data['dataList'].toString() != '[]') {
        planTaskInitConfig = PlanTaskInitConfig.fromJson(data['dataList']);
        List<CheckItem> checkItem = [];
        var checkItemsMap = data['dataList']['checkItem'];
        for (final checkItemKey in checkItemsMap.keys) {
          for (final _checkItemKey in checkItemsMap[checkItemKey].keys) {
            var _checkItemsList = checkItemsMap[checkItemKey][_checkItemKey];
            for (final _checkItem in _checkItemsList) {
              checkItem.add(CheckItem.fromJson(_checkItem));
            }
          }
        }
        planTaskInitConfig.checkItem = checkItem;
        if (planTaskInitConfig.extClass != null && planTaskInitConfig.extClass.isNotEmpty) {
          if (planTaskInitConfig.checkItem.where((f) => f.classifyIds == null).isNotEmpty) {
            ExtClass cls = ExtClass.fromParams(id: null, name: '其他');
            planTaskInitConfig.extClass.add(cls);
          }
        }
      }
    } else {
      planTaskInitConfig = PlanTaskInitConfig.fromParams();
      planTaskInitConfig.errorMsg = data['message'];
    }
    return planTaskInitConfig;
  } catch (e) {
    rethrow;
  }
}
