import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../models/region.dart';

class RegionProvider extends ChangeNotifier {
  RegionProvider() {
    loadRegionData();
  }

  String _provinceName = '';
  String _cityName = '';
  String _tempProvinceName = '';
  String _tempCityName = '';

  String get provinceName => _provinceName;

  String get cityName => _cityName;

  String get tempProvinceName => _tempProvinceName;

  String get tempCityName => _tempCityName;

  final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

  loadRegionData() {
    _prefs.then((prefs) {
      if (prefs.getString('REGION') != null) {
        final region =
            RegionData.fromJson(jsonDecode(prefs.getString('REGION')));
        _provinceName = region.provinceName;
        _cityName = region.cityName;
        _tempProvinceName = region.provinceName;
        _tempCityName = region.cityName;
        notifyListeners();
      }
    });
  }

  updateRegion(pname, cname) {
    // _provinceName = pname;
    // _cityName = cname;
    _tempProvinceName = pname;
    _tempCityName = cname;

    notifyListeners();
  }

  //将临时变量保存到正式变量，并保存本地
  saveRegion() {
    _provinceName = _tempProvinceName;
    _cityName = _tempCityName;
    print(_tempCityName);
    final region = <String, dynamic>{
      "provinceName": _tempProvinceName,
      'cityName': _tempCityName
    };
    _prefs.then((prefs) {
      prefs.setString('REGION', jsonEncode(region));
    });
    notifyListeners();
  }

  // 覆盖临时的变量
  resetTemp() async {
    _tempProvinceName = _provinceName;
    _tempCityName = _cityName;
    notifyListeners();
  }

  // 将临时的省市名设为空
  clearTemp() {
    _tempProvinceName = '';
    _tempCityName = '';
    notifyListeners();
  }
}
