<template>
  <div>
    <template v-for="(item, index) in dataSource" :key="index">
      <Checkbox v-model="model[index]" :disabled="readonly" @on-change="change(index)">{{ item[labelKey] }}</Checkbox>
    </template>
  </div>
</template>
<script>
  import mixinPage from '../../mixins/page';

  /**
   * @displayName check-group 单选框组
   */
  export default {
    mixins: [mixinPage],
    data() {
      return {
        model: []
      };
    },
    created() {},
    props: {
      /**
       * @model
       */
      modelValue: {
        type: String
      },
      /**
       * 数据源
       */
      dataSource: {
        type: Array,
        default: () => {
          return [];
        }
      },
      /**
       * 大小
       * @values small, default, large
       */
      size: {
        type: String
      },
      /**
       * 值
       */
      valueKey: {
        type: String
      },
      /**
       * 标签
       */
      labelKey: {
        type: String
      },
      /**
       * 只读
       */
      readonly: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      modelValue(v) {
        this.model.length = 0;
        let val = [];
        if (!!(this.modelValue || '').trim() && JSON.parse(this.modelValue) instanceof Array) {
          val = JSON.parse(this.modelValue);
        }

        for (let data of this.dataSource) {
          if (
            val.some(item => {
              return item == data[this.valueKey];
            })
          ) {
            this.model.push(true);
          } else {
            this.model.push(false);
          }
        }
      }
    },
    methods: {
      change(changedIndex) {
        let val = [];
        for (let index in this.model) {
          if (this.model[index]) {
            val.push(this.dataSource[index][this.valueKey]);
          }
        }

        this.$emit('update:modelValue', JSON.stringify(val));

        this.$emit('on-change');
      }
    }
  };
</script>
