import {getCertTypeOptions, getRelationTypeOptions} from '@/api/ccdiEnum'

const ccdiEnum = {
  namespaced: true,

  state: {
    // 关系类型选项
    relationTypeOptions: [],
    relationTypeLoadedTime: null,

    // 证件类型选项
    certTypeOptions: [],
    certTypeLoadedTime: null,

    // 缓存过期时间（毫秒）- 默认1小时
    cacheExpireTime: 60 * 60 * 1000
  },

  mutations: {
    SET_RELATION_TYPE_OPTIONS: (state, options) => {
      state.relationTypeOptions = options
      state.relationTypeLoadedTime = Date.now()
    },
    SET_CERT_TYPE_OPTIONS: (state, options) => {
      state.certTypeOptions = options
      state.certTypeLoadedTime = Date.now()
    },
    CLEAR_CACHE: (state) => {
      state.relationTypeOptions = []
      state.relationTypeLoadedTime = null
      state.certTypeOptions = []
      state.certTypeLoadedTime = null
    }
  },

  actions: {
    /**
     * 获取关系类型选项（带缓存检查）
     */
    async getRelationTypeOptions({ commit, state }) {
      // 检查缓存是否有效
      if (state.relationTypeOptions.length > 0 &&
          state.relationTypeLoadedTime &&
          Date.now() - state.relationTypeLoadedTime < state.cacheExpireTime) {
        return state.relationTypeOptions
      }

      // 调用接口获取数据
      const response = await getRelationTypeOptions()
      commit('SET_RELATION_TYPE_OPTIONS', response.data)
      return response.data
    },

    /**
     * 获取证件类型选项（带缓存检查）
     */
    async getCertTypeOptions({ commit, state }) {
      // 检查缓存是否有效
      if (state.certTypeOptions.length > 0 &&
          state.certTypeLoadedTime &&
          Date.now() - state.certTypeLoadedTime < state.cacheExpireTime) {
        return state.certTypeOptions
      }

      // 调用接口获取数据
      const response = await getCertTypeOptions()
      commit('SET_CERT_TYPE_OPTIONS', response.data)
      return response.data
    },

    /**
     * 清除缓存
     */
    clearCache({ commit }) {
      commit('CLEAR_CACHE')
    }
  },

  getters: {
    relationTypeOptions: state => state.relationTypeOptions,
    certTypeOptions: state => state.certTypeOptions
  }
}

export default ccdiEnum
