<template>
  <el-checkbox-group v-model="checkedValue" @change="handleChange">
    <el-checkbox v-for="(item, index) in options"  :key="index" :label="item.key">{{item.value}}</el-checkbox>
  </el-checkbox-group>
</template>

<style scoped>

</style>

<script>
export default {
  props: {
    value: String,
    config: [String, Object]
  },

  data() {
    return {
      options: [],
      checkedValue: []
    }
  },

  watch: {
    value(val) {
      this.checkedValue = val.split(',')
    }
  },

  created() {
    let val = this.value || ''
    this.checkedValue = val.split(',') || []
    this.updateOptions(this.config)
  },

  methods: {
    handleChange(val) {
      this.checkedValue = val
      this.$emit('input', this.checkedValue.join(','))
    },
    async updateOptions(config) {
      if (config.options && config.options.length) {
        this.options = JSON.parse(JSON.stringify(config.options))
        return
      }
      if (config.listOptions) {
        let items = config.listOptions.split(':')
        if (items.length !== 2) {
          this.options = []
          return
        }
        if (items[0] === 'Input') {
          let list = items[1].split('<br>')
          this.options = list.map(val => {
            return { value: val, key: val }
          })
          return
        }
        let res = await axios.get(`/ui/contentextends/fields/options/${items[0]}`, {
          params: {
            method: items[1]
          }
        })
        this.options = res.data.data
      }
    }
  }
}
</script>
