<template>
  <span class="dg-dict">{{ dimValue }}</span>
</template>

<script>
import { getDimData } from './main.js'

export default {
  name: 'DgDict',
  props: {
    apiCode: { type: String, default: '' },
    dimCode: { type: String, default: '' },
    queryTerms: { type: String, default: '' },
    filterVal: { type: String, default: '' },
    value: { type: String, required: true },
  },
  data() {
    return { dimData: [] }
  },
  computed: {
    dimKey() {
      const { dimCode, apiCode, filterVal, queryTerms } = this
      return [dimCode, apiCode, filterVal, queryTerms].filter(Boolean).join('_')
    },
    dimValue() {
      const { dimData, value } = this
      const match = dimData.find(({ id }) => id === value)
      return match ? match.name : value
    },
  },
  watch: {
    dimKey: {
      immediate: true,
      async handler() {
        this.dimData = await getDimData.bind(this)()
      },
    },
  },
}
</script>
