<template>
  <div class="x-question-options">
    <x-radio
      v-if="!effectiveMultiple"
      :options="mappedOptions"
      :name="name"
      :value="innerValue"
      no-default-first
      class="x-question-options-inner"
      @change="onSingleChange"
    />
    <x-checkbox
      v-else
      :options="mappedOptions"
      :value="innerValueArray"
      class="x-question-options-inner"
      @change="onMultipleChange"
    />
  </div>
</template>

<script>
import XRadio from '@vue2-client/base-client/components/his/XRadio/XRadio.vue'
import XCheckbox from '@vue2-client/base-client/components/his/XCheckbox/XCheckbox.vue'

export default {
  name: 'XQuestionOptions',
  components: { XRadio, XCheckbox },
  props: {
    /** 原始问题的 JSON 数据；传入时与 questionLabelField/optionsField/multipleField 一起使用，组件内部做转换并 emit 完整 { question, selected } */
    questionData: {
      type: Object,
      default: null
    },
    /** 从原始问题中取「问题文案」的字段名 */
    questionLabelField: {
      type: String,
      default: 'label'
    },
    /** 从原始问题中取「是否多选」的字段名 */
    multipleField: {
      type: String,
      default: 'multiple'
    },
    /** 从原始问题中取「选项列表」的字段名 */
    optionsField: {
      type: String,
      default: 'options'
    },
    /** 选择结果写入原始问题对象的字段名；传入时选择后直接修改 questionData[selectedField]，后端数据无需转换 */
    selectedField: {
      type: String,
      default: 'selected'
    },
    /** 选项列表（与 questionData 二选一，兼容旧用法） */
    options: {
      type: Array,
      default: () => []
    },
    /** 是否多选（与 questionData 二选一） */
    multiple: {
      type: Boolean,
      default: false
    },
    /** 当前选中值（v-model）；单选为单值，多选为值数组 */
    value: {
      type: [String, Number, Array, Object],
      default: undefined
    },
    name: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      innerValue: undefined,
      innerValueArray: []
    }
  },
  computed: {
    /** 是否使用「原始问题」模式（有 questionData 时从其中解析） */
    useQuestionData () {
      return this.questionData != null && typeof this.questionData === 'object'
    },
    /** 实际选项列表：questionData 模式取 questionData[optionsField]，否则用 options */
    effectiveOptions () {
      if (this.useQuestionData) {
        const arr = this.questionData[this.optionsField]
        return Array.isArray(arr) ? arr : []
      }
      return this.options || []
    },
    /** 实际是否多选 */
    effectiveMultiple () {
      if (this.useQuestionData) return !!this.questionData[this.multipleField]
      return this.multiple
    },
    mappedOptions () {
      return this.effectiveOptions.map(opt => ({
        label: this.optLabel(opt),
        value: this.optVal(opt)
      }))
    }
  },
  watch: {
    value: {
      handler (val) {
        if (this.effectiveMultiple) {
          this.innerValueArray = Array.isArray(val) ? [...val] : []
        } else {
          this.innerValue = val
        }
      },
      immediate: true
    }
  },
  emits: ['input', 'change'],
  methods: {
    optVal (opt) {
      return opt.value !== undefined ? opt.value : opt.label
    },
    optLabel (opt) {
      if (opt.label !== undefined && opt.label !== null) return opt.label
      if (opt.value != null && typeof opt.value === 'object') {
        return (opt.value.text || opt.value.label || opt.value.name) || JSON.stringify(opt.value)
      }
      return opt.value
    },
    /** 发出变更：questionData 模式下写入 questionData[selectedField] 并 emit，否则仅 emit */
    emitChange (selected) {
      this.$emit('input', selected)
      if (this.useQuestionData) {
        this.$set(this.questionData, this.selectedField, selected)
        this.$emit('change', { question: this.questionData, selected })
      } else {
        this.$emit('change', selected)
      }
    },
    onSingleChange (val) {
      this.innerValue = val
      this.emitChange(val)
    },
    onMultipleChange (vals) {
      this.innerValueArray = Array.isArray(vals) ? [...vals] : []
      this.emitChange(this.innerValueArray)
    }
  }
}
</script>

<style scoped>
.x-question-options {
  width: 100%;
  margin-top: 8px;
}
.x-question-options-inner :deep(.x-radio-group),
.x-question-options-inner :deep(.x-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  width: 100%;
}
.x-question-options-inner :deep(.x-radio-item-container),
.x-question-options-inner :deep(.x-checkbox-item-container) {
  min-width: 120px;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  background: #fafafa;
  cursor: pointer;
  transition: border-color 0.2s, background 0.2s;
}
.x-question-options-inner :deep(.x-radio-item-container:hover),
.x-question-options-inner :deep(.x-checkbox-item-container:hover) {
  border-color: #1890ff;
  background: #e6f7ff;
}
.x-question-options-inner :deep(.x-radio-item-container.x-radio-item-selected),
.x-question-options-inner :deep(.x-checkbox-item-container.x-checkbox-item-selected) {
  border-color: #1890ff;
  background: #e6f7ff;
}
.x-question-options-inner :deep(.x-radio-item-container .ant-radio-wrapper),
.x-question-options-inner :deep(.x-checkbox-item-container .ant-checkbox-wrapper) {
  margin-right: 0;
}
.x-question-options-inner :deep(.ant-radio-wrapper),
.x-question-options-inner :deep(.ant-checkbox-wrapper) {
  font-size: 13px;
  color: #333;
}
</style>
