<template>
  <a-checkbox-group :options="checkBoxOptions" :value="checkboxArray" v-bind="$attrs" @change="onChange" />
</template>

<script>
  import { getDictItems } from '@comp/dict/JDictSelectUtil'

  export default {
    name: 'JCheckbox',
    props: {
      value:{
        type: String,
        required: false
      },
      dictCode:{
        type: String,
        required: false
      },
      /*label value*/
      options:{
        type: Array,
        required: false,
        default: () => []
      }
    },
    data(){
      return {
        checkBoxOptions:this.options,
        checkboxArray:!this.value?[]:this.value.split(",")
      }
    },
    watch:{
      value (val) {
        if(!val){
          this.checkboxArray = []
        }else{
          this.checkboxArray = this.value.split(",")
        }
      }
    },
    mounted() {
      if(this.dictCode){
        this.loadDictOptions()
      }
    },
    methods:{
      loadDictOptions(){
        let temp = this.dictCode || '';
        if (temp.indexOf(',') > 0 && temp.indexOf(' ') > 0) {
          // 编码后 是不包含空格的
          temp = encodeURI(temp);
        }

        //update-end-author:taoyan date:2022-6-21 for: 字典数据请求前将参数编码处理，但是不能直接编码，因为可能之前已经编码过了
        getDictItems(temp).then((res) => {
          if (res) {
            this.checkBoxOptions = res.map((item) => ({value: item.value, label: item.text, color: item.color}));
            //console.info('res', this.checkOptions);
          } else {
            console.error('getDictItems error: : ', res);
            this.checkBoxOptions = [];
          }
        });
      },
      onChange (checkedValues) {
        this.$emit('change', checkedValues.join(","));
      },
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>
