/*
 * @Author: XianKaiQun
 * @Date: 2020-04-15 10:43:19
 * @LastEditors: XianKaiQun
 * @LastEditTime: 2020-04-22 15:15:50
 * @Descripttion: 通用的接口model
 */

import 'package:flutter/material.dart';

class ResModel<@required T> {
  T? data;
  String? code;
  String? msg;
  late ResErrorModel responseJSON;
  int? status;
  String? statusText;

  late Function _dataToJson;

  ///[json] 传入接口返回的json数据 res.data
  ///
  ///[dataFromJson] 传入data的构造函数fromJson
  ///
  ///[dataToJson] 传入data的构造函数fromJson
  ///
  ResModel({
    required Map<String, dynamic> json,
    required T Function(dynamic dataJson) from,
    required Function(T data) to,
  }) {
    assert(from != to);
    _dataToJson = to;
    if (json['data'] != null) {
      this.data = from(json['data']);
    }
    _fromJson(json);
  }

  _fromJson(json) {
    Map<String, dynamic> map = Map.from(json ?? {});
    code = map['code'];
    msg = map['msg'];
    responseJSON = ResErrorModel.fromJson(map["responseJSON"] ?? {});
    status = map['status'];
    statusText = map['statusText'];
  }

  Map<String, dynamic> toJson() {
    Map<String, dynamic> json = Map<String, dynamic>();

    json['code'] = this.code;
    json['msg'] = this.msg;
    json['responseJSON'] = this.responseJSON.toJson();
    json['status'] = this.status;
    json['statusText'] = this.statusText;
    json['data'] = _dataToJson(this.data);
    return json;
  }
}

///接口错误提示
class ResErrorModel {
  String? code;
  String? message;

  ResErrorModel({
    this.code,
    this.message,
  });

  ResErrorModel.fromJson(Map<String, dynamic> json) {
    code = json['code'];
    message = json['message'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> json = Map<String, dynamic>();

    json['code'] = this.code;
    json['message'] = this.message;

    return json;
  }
}
