/* eslint-disable no-empty */
export class Searchs {
  saveKey = 'searchs'

  initSearch = {
    form: {},
    page: {}
  }

  searchs = {} as any
  key = '' as string

  constructor(key: string) {
    this.key = key
    this.searchs = this.parse()
  }

  save() {
    localStorage.setItem(this.saveKey, JSON.stringify(this.searchs))
  }

  parse() {
    let json = { ...initSearch }
    try {
      const val = localStorage.getItem(this.saveKey) as string
      json = JSON.parse(val) || json
    } catch (error) {}
    return json
  }

  get(key: string) {
    const k = key || this.key
    if (!this.searchs[k]) {
      this.searchs[k] = { ...initSearch }
    }
    return this.searchs[k]
  }

  remove(type: 'page' | 'form') {
    if (this.searchs && this.searchs[this.key]) {
      type ? delete this.searchs[this.key][type] : delete this.searchs[this.key]
      this.save()
    }
    return this.searchs
  }

  getSearchs() {
    return this.searchs
  }

  removeByKey(key: string) {
    console.log('真正的删', key)
    delete this.searchs[key]
    this.save()
    return this.searchs
  }
  removeAll() {
    this.searchs = {}
    localStorage.setItem(this.saveKey, JSON.stringify(this.searchs))
    return this.searchs
  }
  removeByRouter(path: string) {
    this.searchs = this.parse()
    for (let key in this.searchs) {
      // console.log('清除的循环', key, this.searchs[key]?.bind)
      if (path === key || path === this.searchs[key]?.bind) {
        console.log('清除的页面', key)
        this.removeByKey(key)
      }
    }
  }

  removeByOtherRouter(path: string) {
    this.searchs = this.parse()
    for (let key in this.searchs) {
      if (path === key || path === this.searchs[key]?.bind) {
      } else {
        this.removeByKey(key)
      }
    }
  }

  update(data: any, key: string | any, type: 'page' | 'form' | 'bind' | '') {
    this.searchs = this.parse()
    const k = key || this.key
    if (!this.searchs[k]) {
      this.searchs[k] = { ...initSearch }
    }

    if (type) {
      this.searchs[k][type] = data
    } else {
      this.searchs[k] = data
    }
    this.save()
    return this.searchs
  }
}

const initSearch = {
  form: {},
  page: {}
}
