<template>
  <div class="pl-3 pr-3">
    <a-checkbox-group :value="modelValue" @change="handleCheckboxChange">
      <a-checkbox v-for="item in dictOptions" :key="item.value" :value="item.value">{{ item.text }} </a-checkbox>
    </a-checkbox-group>
  </div>
</template>

<script>
import { ajaxGetDictItems } from '@/api/services/base'

export default {
  name: 'HDictCheckbox',
  props: {
    value: {
      type: String,
      required: false,
      default: ''
    },
    dictCode: {
      type: String,
      required: false,
      default: ''
    }
  },
  data() {
    return {
      modelValue: !this.value ? [] : this.value.split(','),
      dictOptions: []
    }
  },
  watch: {
    value: {
      handler(val) {
        if (!val) {
          this.modelValue = []
        } else {
          this.modelValue = this.value.split(',')
        }
      }
    },
    dictCode: {
      handler() {
        this.initDictData()
      },
      immediate: true
    }
  },
  methods: {
    initDictData() {
      if (this.options && this.options.length > 0) {
        this.dictOptions = [...this.options]
      } else {
        //根据字典Code, 初始化字典数组
        ajaxGetDictItems(this.dictCode, null).then(res => {
          this.dictOptions = res.value
        })
      }
    },
    handleCheckboxChange(rows) {
      this.$emit('input', rows.join(','))
      this.$emit('change', rows.join(','))
    }
  }
}
</script>
