<template>
  <view class="form-checkbox">
    <view v-for="(item, index) in options" :key="index" class="checkbox-item" @click="onToggle(item)">
      <view class="checkbox-dot" :class="{ active: isChecked(item) }"></view>
      <text class="checkbox-label">{{ getOptionLabel(item) }}</text>
    </view>
  </view>
</template>

<script>
export default {
  name: 'FormItemCheckbox',
  props: {
    value: { type: Array, default: function () { return []; } },
    options: { type: Array, default: function () { return []; } },
    maxCount: { type: Number, default: 0 }
  },
  methods: {
    getOptionValue: function (item) {
      if (item && typeof item === 'object') {
        if (item.value !== undefined) return item.value;
        if (item.id !== undefined) return item.id;
        if (item.key !== undefined) return item.key;
        if (item.code !== undefined) return item.code;
        return item.label;
      }
      return item;
    },
    getOptionLabel: function (item) {
      if (item && typeof item === 'object') {
        var label = item.label || item.title || item.name || item.text;
        if (label !== undefined && label !== null) return label;
        return String(this.getOptionValue(item));
      }
      return item;
    },
    findValueIndex: function (list, value) {
      for (var i = 0; i < list.length; i++) {
        if (list[i] == value) return i;
      }
      return -1;
    },
    isChecked: function (item) {
      return this.findValueIndex(this.value || [], this.getOptionValue(item)) !== -1;
    },
    onToggle: function (item) {
      var val = this.getOptionValue(item);
      var newValue = (this.value || []).slice();
      var index = this.findValueIndex(newValue, val);
      if (index === -1) {
        if (this.maxCount > 0 && newValue.length >= this.maxCount) {
          uni.showToast({
            title: '最多只能选择' + this.maxCount + '项',
            icon: 'none'
          });
          return;
        }
        newValue.push(val);
      } else {
        newValue.splice(index, 1);
      }
      this.$emit('input', newValue);
    }
  }
};
</script>

<style scoped>
.form-checkbox {
  display: flex;
  flex-wrap: wrap;
}

.checkbox-item {
  display: flex;
  align-items: center;
  margin-right: 40rpx;
  margin-bottom: 16rpx;
}

.checkbox-dot {
  width: 36rpx;
  height: 36rpx;
  border-radius: 8rpx;
  border: 2rpx solid #cccccc;
  margin-right: 12rpx;
  position: relative;
}

.checkbox-dot.active {
  border-color: #e8101e;
  background-color: #e8101e;
}

.checkbox-dot.active::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -60%) rotate(-45deg);
  width: 20rpx;
  height: 12rpx;
  border-left: 4rpx solid #ffffff;
  border-bottom: 4rpx solid #ffffff;
}

.checkbox-label {
  font-size: 28rpx;
  color: #333333;
}
</style>
