/**
 * 缓存数据字典
 * 把数据字典缓存到
 * */
import {
  queryDictionaryList
} from '@/api/common'
// 超时时间15分钟
const timeOut = 1000 * 60 * 15
// const timeOut = 1000

// 静态字典
const dist = {
  hospital_grade: [{
      name: '一级',
      val: 1,
      id: 1
    },
    {
      name: '二级',
      val: 2,
      id: 2
    },
    {
      name: '三级',
      val: 3,
      id: 3
    },
    {
      name: '未分级',
      val: 4,
      id: 4
    },
  ],
  hospital_class: [{
      name: '甲等',
      val: 1,
      id: 1
    },
    {
      name: '已等',
      val: 2,
      id: 2
    },
    {
      name: '丙等',
      val: 3,
      id: 3
    },
    {
      name: '未评定',
      val: 4,
      id: 4
    }
  ],
  ID_type: [{
      name: '居民身份证',
      val: '01',
      id: 1
    },
    {
      name: '居民户口簿',
      val: '02',
      id: 2
    },
    {
      name: '护照',
      val: '03',
      id: 3
    },
    {
      name: '军官证',
      val: '04',
      id: 4
    },
    {
      name: '驾驶证',
      val: '05',
      id: 5
    },
    {
      name: '港澳居民来往内地通行证',
      val: '06',
      id: 6
    },
    {
      name: '台湾居民来往内地通行证',
      val: '07',
      id: 7
    },
    {
      name: '出生医学证明',
      val: '08',
      id: 8
    },
    {
      name: '其他法定有效证件',
      val: '09',
      id: 9
    }
  ]
}

export async function getDic(list) {
  let data = {}
  if (!Array.isArray(list) && list.length === 0) {
    return data
  }
  const paramsList = []
  list.forEach(item => {
    if (dist[item]) { // 是否静态
      data[item] = dist[item]
    } else if (getSS(item)) { // 是否还在缓存中
      data[item] = getSS(item)
    } else { // 发请求获取
      paramsList.push(item)
    }
  })
  if (paramsList.length > 0) {
    const res = await queryDictionaryList({
      nameList: paramsList
    })
    if (res && res.respData) {
      // 缓存字典
      setSS(res.respData)
      data = Object.assign(data, res.respData)
    }
  }
  return data
}

function getSS(item) {
  const data = sessionStorage.getItem(item)
  if (data) {
    // 判断是否超时
    const time = sessionStorage.getItem(item + '_time') || 0
    if (parseInt(time) > new Date().getTime() - timeOut) {
      return JSON.parse(data)
    } else {
      // 清除超时缓存
      sessionStorage.removeItem(item)
      sessionStorage.removeItem(item + '_time')
      return false
    }
  } else {
    return false
  }
}

function setSS(obj) {
  for (const key in obj) {
    if (Object.hasOwnProperty.call(obj, key)) {
      const item = obj[key];
      sessionStorage.setItem(key, JSON.stringify(item))
      sessionStorage.setItem(key + '_time', new Date().getTime())
    }
  }
}
