<!-- webview only -->
<template>
  <div
      @click="changeCheck"
      :class="['bili-checkbox-default', checked_show ? 'bili-checkbox-checked': '', disabled ? 'bili-checkbox-disabled': ''] "
      :style="[propsStyle.default, checked_show && {'color': color}, checked_show && propsStyle.selected, disabled && propsStyle.disabled]"
  >
    <i :class="[checked_show ? (icon ? icon : 'icon-select') : '']"></i>
  </div>
</template>
<script>
import shortId from 'shortid';

global.test = [];
export default {
  name: 'BCheckBox',
  inject: ['checkbox'],
  props: {
    checked: {
      type: Boolean,
      default: false,
    },
    color: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: 'default',
    },
    value: {
      type: String,
      default: '',
    },
    icon: {
      type: String,
      default: ''
    },
    propsStyle: {
      type: Object,
      default: {
        default: {},
        selected: {},
        disabled: {}
      }
    }
  },
  data() {
    return {
      id: '',
      checked_show: false
    };
  },
  watch: {
    // 动态变更
    checked(value) {
      this.checked_show = value;
      if (this.checkbox) {
        const index = this.checkbox.selected.findIndex(fv => fv.id === this.id);
        if (value) {
          if (index === -1) {
            this.checkbox.selected.push({
              id: this.id,
              value: this.value
            });
          }
        } else {
          const index = this.checkbox.selected.findIndex(fv => fv.id === this.id);
          if (index !== -1) {
            this.checkbox.selected.splice(index, 1);
          }
        }
      }
    }
  },
  mounted() {
    this.id = shortId.generate();
    this.checked_show = this.checked;
    if (this.checkbox && this.checked_show) {
      this.checkbox.selected.push({
        id: this.id,
        value: this.value
      });
    }
  },
  methods: {
    changeCheck() {
      if (this.disabled) {
        return;
      }
      this.checked_show = !this.checked_show;
      if (this.checkbox) {
        if (this.checked_show) {
          this.checkbox.selected.push({
            id: this.id,
            value: this.value
          });
        } else {
          const index = this.checkbox.selected.findIndex(fv => fv.id == this.id);
          if (index !== -1) {
            this.checkbox.selected.splice(index, 1);
          }
        }
      }
    }
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.bili-checkbox-default {
  line-height: 24px;
  display: inline-block;
  margin-right: 4px;
  width: 22px;
  height: 22px;
  border-radius: 3px;
  border: 1px solid #cccccc;
  background-color: #ffffff;
  vertical-align: bottom;
  text-align: center;
}

.bili-checkbox-checked {
  color: #fb7299;
}

.bili-checkbox-disabled {
  background-color: #dddddd;
}

</style>
