import 'dart:io';
import 'dart:convert';

import 'package:zhiying_comm/util/net_util.dart';
import 'package:zhiying_comm/util/shared_prefe_util.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class BaseSettingModel {
  String fileProvider;
  String fileBucketHost;
  String fileBucketHostProtocol;
  String isIosReview;
  Map<String, dynamic> tab;

  static BaseSettingModel _setting;

  static BaseSettingModel get setting {
    if (_setting == null) {
      Logger.error('暂未初始化');
    }
    return _setting;
  }

  BaseSettingModel({this.fileProvider, this.fileBucketHost, this.fileBucketHostProtocol});

  BaseSettingModel.fromJson(Map<String, dynamic> json) {
    fileProvider = json['file_provider'];
    fileBucketHost = json['file_bucket_host'];
    fileBucketHostProtocol = json['file_bucket_host_protocol'];
    isIosReview = json['is_ios_review']?.toString();
    tab = Map<String, dynamic>.from(json['bottom_nav']);
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['file_provider'] = this.fileProvider;
    data['file_bucket_host'] = this.fileBucketHost;
    data['file_bucket_host_protocol'] = this.fileBucketHostProtocol;
    data['bottom_nav'] = this.tab;
    data['is_ios_review'] = this.isIosReview;
    return data;
  }

  static Future<BaseSettingModel> init({bool isGetCache}) async {
    try {
      ///判断是否获取缓存
       String configData = await SharedPreferencesUtil.getStringValue(GlobalConfig.MAIN_CONFIG, defaultVal: '1');
      if (isGetCache != null && isGetCache && configData != "1") {

        createBaseSet(json.decode(configData));
        Logger.debug('基础设置初始化');
        NetUtil.request('/api/v1/new/config.json',onSuccess: (data){
         print(data);
         var cacheString=json.encode(data);
         SharedPreferencesUtil.setNetCacheResult(GlobalConfig.MAIN_CONFIG, cacheString);
        });
        return _setting;

      } else {
        Map result =
        await NetUtil.post('/api/v1/new/config.json', method: NetMethod.GET);
        var data = result['data'];
        var cacheString=json.encode(data);
        SharedPreferencesUtil.setNetCacheResult(GlobalConfig.MAIN_CONFIG, cacheString);
        createBaseSet(data);
        return _setting;
      }
    } catch (err,s) {
      print(s);
      Logger.error(err);
    }
    return null;
  }

  static createBaseSet(dynamic data){
    _setting = BaseSettingModel.fromJson(Map<String, dynamic>.from(data));
    if (Platform.isIOS) {
      if (null != setting && _setting.isIosReview == '1') {
        SharedPreferencesUtil.setStringValue(GlobalConfig.IS_IOS_REVIEW, '1');
      } else {
        SharedPreferencesUtil.setStringValue(GlobalConfig.IS_IOS_REVIEW, '0');
      }
    }
    Logger.debug('基础设置初始化');
  }
}
