import md5 from "./md5";
class PageCache {
  //页面
 // page = null;
  //路由缓存
 // _route = {};
  //路由地址
 // _path = "";
  //key数据
  //_key = "";
  //查询数据
  //_query  ={};
  //存储初始化数据
 // _data = {};

  constructor(page = null) {
    this.page = null;
    this._route = {};
    this._path = "";
    this._key = "";
    this._query = {};
    this._data = {};

    this.page = page;
    this._path = page.$route.path;
    this._key = this.md5Key(page.$route.query);
    this._query = page.$route.query;
    this._route[this._key] = {query : page.$route.query,data:{}};
    this._data = JSON.stringify(page.$data);
  }
  /**
   * 切换路由坏境
   * @param $to
   *
   */
  routeView($to,fn = null) {
    var path = $to.path;
    var query = $to.query;
    if(path == this._path) {
      var key = this.md5Key(query);
      var data = JSON.stringify(this.page.$data);
      if(this._route[key] != null) {
        if(fn != null) fn('cache',this._route[key].data);
      } else {
        if(fn != null) fn('update',JSON.parse(data));
      }
      this._route[this._key] = {query:this._query,data:JSON.parse(data)};
      this._key = key;
      this._query = query;
    }
  }
  /**
   * 查询数据
   * @param query
   * @returns {string}
   */
  md5Key(query){
    var key = "";
    for (var i in query) { key += i + "=" + query[i]; }
    return md5.md5(key);
  }

}



export default PageCache
