import Vue from 'vue'

const vm = new Vue()

export const formatDictValue = async (value, { apiCode, dimCode, queryTerms, filterVal, store } = {}) => {
  const dimKey = [dimCode, apiCode, filterVal, queryTerms].filter(Boolean).join('_')
  if (!dimKey) return value
  const dimData = await getDimData.bind(
    Object.assign(vm, { dimCode, apiCode, filterVal, queryTerms, dimKey, $store: store })
  )()

  const match = dimData.find(({ id }) => id === value)
  return match ? match.name : value
}

/**
 *
 * @internal
 */
export async function getDimData() {
  const { dimCode, apiCode, filterVal, queryTerms, dimKey } = this

  let state = this.$store?.state?.dimData || {}
  if (!this.noCache && state[dimKey] && state[dimKey].length) {
    return state[dimKey]
  }

  let params = new URLSearchParams(queryTerms)
  params.append('command', 'init')

  if (dimCode) params.append('dimCode', dimCode)
  if (filterVal) params.append('supDimValCode', filterVal)

  const { root } = await this.$api.DgJsonStore({ apiCode: apiCode || 'sysDictMember', params: params.toString() })
  return (root || []).map((item) => {
    const { ROWNAME: name, ROWCODE: id, SUPROWCODE: supId = '' } = item
    const option = { id, name, supId }

    if (this.codeType) {
      option[this.codeType] = item[this.codeType]
    }

    return option
  })
}
