<template>
  <div class="x-checkbox-container" :class="wrapperClassObject()">
    <a-checkbox-group v-model="innerValue" @change="onChange" class="x-checkbox-group">
      <div
        v-for="(item, idx) in data"
        :key="'xcb-' + idx"
        class="x-checkbox-item-container"
        :class="{ 'x-checkbox-item-selected': isOptionSelected(item) }"
      >
        <a-checkbox :value="item.value" class="x-checkbox-item">
          {{ item.label }}
        </a-checkbox>
      </div>
    </a-checkbox-group>
  </div>
</template>

<script>
import { getConfigByName } from '@vue2-client/services/api/common'
import { Checkbox } from 'ant-design-vue'

export default {
  name: 'XCheckbox',
  components: {
    ACheckboxGroup: Checkbox.Group,
    ACheckbox: Checkbox
  },
  props: {
    queryParamsName: {
      type: Object,
      default: null
    },
    /** 选项列表（每项 { label, value }）；传入时优先使用，不走 queryParamsName 配置 */
    options: {
      type: Array,
      default: null
    },
    value: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      data: [],
      innerValue: [],
      config: null
    }
  },
  created () {
    if (this.options != null && Array.isArray(this.options)) {
      this.useOptionsProp()
    } else {
      this.getData(this.queryParamsName)
    }
  },
  watch: {
    value: {
      handler (val) {
        this.innerValue = Array.isArray(val) ? this.resolveValuesToOptions(val) : (val || [])
      },
      deep: true
    },
    options: {
      handler (val) {
        if (val != null && Array.isArray(val)) {
          this.data = val
          this.innerValue = this.resolveValuesToOptions(this.value)
        }
      },
      deep: true
    }
  },
  emits: ['change', 'init'],
  methods: {
    /** 使用 options 参数作为数据源（不请求配置） */
    useOptionsProp () {
      this.data = this.options || []
      this.innerValue = Array.isArray(this.value) && this.value.length > 0
        ? this.resolveValuesToOptions(this.value)
        : []
      this.$emit('init', { config: null, options: this.data, value: this.innerValue })
    },
    async getData (data) {
      getConfigByName(data, 'af-his', res => {
        // 1. 加载选项
        if (res.checkbox && Array.isArray(res.checkbox)) {
          this.data = res.checkbox
          // 2. 初始化默认值（对象时匹配到选项引用，保证 v-model 与选项一致）
          if (this.value !== undefined && Array.isArray(this.value) && this.value.length > 0) {
            this.innerValue = this.resolveValuesToOptions(this.value)
          } else if (res.defaultValue !== undefined && Array.isArray(res.defaultValue)) {
            this.innerValue = this.resolveValuesToOptions(res.defaultValue)
          }
          // 3. 触发初始化事件
          this.$emit('init', {
            config: res,
            options: this.data,
            value: this.innerValue
          })
        } else {
          this.$message.error('配置错误，checkbox字段不是数组')
        }
      })
    },
    /** 将外部 value/defaultValue 数组解析为选项引用（对象项用 deepEqual 匹配） */
    resolveValuesToOptions (arr) {
      if (!Array.isArray(arr) || this.data.length === 0) return arr
      return arr.map(v => {
        const opt = this.data.find(item => this.deepEqual(item.value, v))
        return opt ? opt.value : v
      })
    },
    /** 判断当前选项是否被选中（支持对象 value） */
    isOptionSelected (item) {
      if (this.innerValue.some(v => v === item.value)) return true
      if (typeof item.value === 'object' && item.value !== null) {
        return this.innerValue.some(v => typeof v === 'object' && v !== null && this.deepEqual(v, item.value))
      }
      return false
    },
    /** 深度相等（用于对象 value 比较与匹配） */
    deepEqual (a, b) {
      if (a === b) return true
      if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') return false
      const keysA = Object.keys(a)
      const keysB = Object.keys(b)
      if (keysA.length !== keysB.length) return false
      return keysA.every(key => keysB.includes(key) && this.deepEqual(a[key], b[key]))
    },
    wrapperClassObject () {
      const attrs = this.$attrs || {}
      const classes = {}
      const booleanStyleKeys = [
        'compact', 'out-checkbox', 'justify-content-start'
      ]
      booleanStyleKeys.forEach(key => {
        const val = attrs[key]
        const truthy = val === true || val === '' || val === 'true'
        if (truthy) classes[`x-checkbox-${key}`] = true
      })
      return classes
    },
    onChange (checkedValues) {
      this.innerValue = checkedValues
      this.$emit('change', checkedValues)
    }
  }
}
</script>

<style scoped lang="less">
.x-checkbox-container {
  display: flex;
  flex-direction: column;
}

.x-checkbox-group {
  display: flex;
  justify-content: space-around;
}

.x-checkbox-item-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 0 8px;
  box-sizing: border-box;
}

.x-checkbox-item {
  margin-bottom: 8px;
}
.x-checkbox-compact {
  &.x-checkbox-container,
  .x-checkbox-container {
    :deep(.x-checkbox-item-container){
      padding: 0px !important;
      flex: auto !important;
    }
    :deep(.x-checkbox-item){
      margin: 0px;
    }
    :deep(.x-checkbox-item) > span:last-child {
      padding-right: 2px;
      padding-left: 2px;
    }
  }
}

/* out-checkbox：外排版紧凑风格，与表单风格配置保持一致的布尔开关用法 */
.x-checkbox-container.x-checkbox-out-checkbox {
  margin-top: 9px;

  :deep(.x-checkbox-group) {
    justify-content: flex-start;
    flex-wrap: wrap;
    gap: 0 46px;
  }

  :deep(.x-checkbox-item-container) {
    flex: 0 0 auto;
    align-items: flex-start;
    text-align: left;
    padding: 0;
  }

  :deep(.x-checkbox-item) {
    margin: 0;
    display: flex;
    align-items: center;

    .ant-checkbox {
      width: 20px;
      height: 20px;
      margin-right: 10px;

      .ant-checkbox-inner {
        width: 20px;
        height: 20px;
      }
    }

    /* 文字标签样式 */
    span {
      height: 23px;
      opacity: 1;
      font-family: 'Source Han Sans', sans-serif;
      font-size: 16px;
      font-weight: normal;
      line-height: normal;
      letter-spacing: 0em;
      color: #313131;
    }
  }
}
// 从左到右右排列
.x-checkbox-justify-content-start{
  &.x-checkbox-container,
  .x-checkbox-container {
    :deep(.x-checkbox-group){
      display: flex;
      justify-content: start;
    }
    :deep(.x-checkbox-item-container){
      flex-direction: row
    }
  }
}
</style>
