/*
 * @Author: XianKaiQun
 * @Date: 2020-09-25 16:51:44
 * @LastEditors: XianKaiQun
 * @LastEditTime: 2020-09-25 17:44:26
 * @Description: 
 */
library response_model_library;

import 'package:flutter/foundation.dart';

class ResponseModel<T> {
  T? data;
  String? code;
  String? msg;
  late ResponseErrorModel responseJSON;
  int? status;
  String? statusText;

  late Function _dataToJson;

  ///[json] 传入接口返回的json数据 res.data
  ///
  ///[dataFromJson] 传入data的构造函数fromJson
  ///
  ///[dataToJson] 传入data的构造函数fromJson
  ///
  ResponseModel({
    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);
  }

  void _fromJson(json) {
    Map<String, dynamic> map = Map.from(json ?? {});
    code = map['code'];
    msg = map['msg'];
    responseJSON = ResponseErrorModel.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 ResponseErrorModel {
  String? code;
  String? message;

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

  ResponseErrorModel.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;
  }
}

class ResponsePagingModel<@required T> {
  List<T>? list;
  num? pageNum;
  num? pageSize;
  num? pages;
  num? total;

  late Function _itemToJson;

  ///[json] 传入接口返回的data数据
  ///
  ///[from] 传入List Item的构造函数fromJson
  ///
  ///[to] 传入List Item的构造函数fromJson
  ///
  ResponsePagingModel({
    required Map<String, dynamic> json,
    required T Function(dynamic dataJson) from,
    required Function(T data) to,
  }) {
    _itemToJson = to;
    _fromJson(json);
    if (json['list'] != null) {
      list = json['list'].map<T>((item) => from(item)).toList();
    }
  }
  _fromJson(json) {
    Map<String, dynamic> map = Map.from(json ?? {});
    pageNum = map['pageNum'];
    pageSize = map['pageSize'];
    pages = map['pages'];
    total = map['total'];
  }

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

    json['list'] = List<dynamic>.from((list ?? []).map((x) => _itemToJson(x)));
    json['pageNum'] = this.pageNum;
    json['pageSize'] = this.pageSize;
    json['pages'] = this.pages;
    json['total'] = this.total;

    return json;
  }
}
