<template>
  <div class="x-radio-container" :class="wrapperClassObject()">
    <!-- 按钮模式 -->
    <a-radio-group
      v-if="config.buttonMode"
      v-model="innerValue"
      @change="onChange"
      :name="name"
      :class="['x-radio-group', 'x-radio-group-button', { 'x-radio-group-left': config.alignLeft }]"
      button-style="solid">
      <a-radio-button
        v-for="(item, idx) in data"
        :key="'xradio-' + idx"
        :value="item.value"
        class="x-radio-button-item"
      >
        {{ item.label }}
      </a-radio-button>
    </a-radio-group>

    <!-- 普通模式 -->
    <a-radio-group
      v-else
      v-model="innerValue"
      @change="onChange"
      :name="name"
      :class="['x-radio-group', { 'x-radio-group-left': config.alignLeft }]">
      <div
        v-for="(item, idx) in data"
        :key="'xradio-' + idx"
        class="x-radio-item-container"
        :class="{
          'x-radio-item-bordered': config.showBorder,
          'x-radio-item-highlight': config.highlightBorder,
          'x-radio-item-selected': isOptionSelected(item)
        }"
        :style="getHighlightBorderStyle(item)">
        <div class="x-radio-item-wrapper">
          <div
            v-if="config.showIndicator && item.bottomLine !== false"
            class="x-radio-indicator-left"
            :style="{
              width: item.indicatorWidth || '4px',
              backgroundColor: item.indicatorColor || config.indicatorActiveColor,
              height: item.indicatorHeight || '16px'
            }"
          ></div>
          <div
            v-if="isTabStyle"
            class="x-radio-tab-icon"
            :class="{ 'x-radio-tab-icon-active': isOptionSelected(item) }"
          ></div>
          <a-radio
            :value="item.value"
            class="x-radio-item"
            :class="{ 'x-radio-item-no-dot': config.highlightBorder || isTabStyle }"
          >
            {{ item.label }}
          </a-radio>
        </div>
        <div
          v-if="config.showIndicator && item.bottomLine !== false && !config.showBorder && !config.highlightBorder && !isTabStyle"
          class="x-radio-indicator-bottom"
          :style="{
            width: item.indicatorWidth || '100%',
            backgroundColor: item.indicatorColor || config.indicatorActiveColor,
            height: config.indicatorHeight + 'px'
          }"
        ></div>
        <div
          v-if="isTabStyle && isOptionSelected(item)"
          class="x-radio-tab-underline"
        ></div>
      </div>
    </a-radio-group>
  </div>
</template>

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

  export default {
    name: 'XRadio',
    inject: ['getComponentByName'],
    props: {
      queryParamsName: {
        type: [String, Object],
        default: null
      },
      /** 选项列表（每项 { label, value }）；传入时优先使用，不走 queryParamsName 配置 */
      options: {
        type: Array,
        default: null
      },
      /** radio-group 的 name，用于区分同页多组 */
      name: {
        type: String,
        default: ''
      },
      /** 为 true 时单选不默认选中第一项，便于区分用户是否真的选过 */
      noDefaultFirst: {
        type: Boolean,
        default: false
      },
      // eslint-disable-next-line vue/require-default-prop
      value: [String, Number, Object]
    },
    data () {
      return {
        data: [],
        innerValue: null,
        config: {
          showIndicator: true,
          indicatorHeight: 3,
          indicatorActiveColor: '#1890ff',
          alignLeft: false,
          showBorder: false,
          highlightBorder: false,
          buttonMode: false
        }
      }
    },
    created () {
      if (this.options != null && Array.isArray(this.options)) {
        this.useOptionsProp()
      } else {
        this.getData(this.queryParamsName)
      }
    },
    watch: {
      value (val) {
        this.innerValue = this.resolveValueToOption(val)
      },
      options: {
        handler (val) {
          if (val != null && Array.isArray(val)) {
            this.data = val
            this.innerValue = this.resolveValueToOption(this.value)
          }
        },
        deep: true
      }
    },
    computed: {
      isTabStyle () {
        const val = this.$attrs && this.$attrs['tab-style']
        return val === true || val === '' || val === 'true'
      }
    },
    emits: ['change', 'init'],
    methods: {
      /** 使用 options 参数作为数据源（不请求配置） */
      useOptionsProp () {
        this.data = this.options || []
        if (this.value !== undefined && this.value !== null) {
          this.innerValue = this.resolveValueToOption(this.value)
        } else if (this.data.length > 0 && !this.noDefaultFirst) {
          this.innerValue = this.data[0].value
        } else {
          this.innerValue = null
        }
        this.$emit('init', this.innerValue)
      },
      async getData (data) {
        getConfigByName(data, 'af-his', res => {
          // 1. 先加载选项
          if (res.radio && Array.isArray(res.radio)) {
            this.data = res.radio
            // 2. 加载指示器配置
            if (res.indicator !== undefined) {
              // 如果indicator是布尔值，则只控制显示/隐藏
              if (typeof res.indicator === 'boolean') {
                this.config.showIndicator = res.indicator
              } else if (typeof res.indicator === 'object') {
                this.config = {
                  ...this.config,
                  ...res.indicator
                }
              }
            }
            // 3. 加载布局配置
            if (res.layout !== undefined) {
              if (typeof res.layout === 'object') {
                this.config = {
                  ...this.config,
                  ...res.layout
                }
              }
            }
            // 4. 加载按钮模式配置
            if (res.buttonMode !== undefined) {
              this.config.buttonMode = res.buttonMode
            }
            // 5. 初始化默认值（优先级： 配置defaultValue > 第一个选项；noDefaultFirst 为 true 时不选第一项）
            if (this.value !== undefined && this.value !== null) {
              this.innerValue = this.resolveValueToOption(this.value)
            } else if (res.defaultValue !== undefined && res.defaultValue !== null) {
              // 使用配置中的 defaultValue（对象时匹配到选项引用，保证 v-model 一致）
              this.innerValue = this.resolveValueToOption(res.defaultValue)
            } else if (this.data.length > 0 && !this.noDefaultFirst) {
              // 如果没有默认值但有选项且允许默认第一项，使用第一个选项
              this.innerValue = this.data[0].value
            } else {
              this.innerValue = null
            }
            // 6. 触发初始化事件
            this.$emit('init', this.innerValue)
          } else {
            this.$message.error('配置错误，radio字段不是数组')
          }
        })
      },
      onChange (e) {
        this.innerValue = e.target.value
        this.$emit('change', e.target.value)
      },
      /** 判断当前选项是否被选中（支持基本类型与对象 value） */
      isOptionSelected (item) {
        if (this.innerValue === item.value) return true
        if (typeof this.innerValue === 'object' && this.innerValue !== null && typeof item.value === 'object' && item.value !== null) {
          return this.deepEqual(this.innerValue, item.value)
        }
        return false
      },
      /** 将外部 value/defaultValue 解析为选项引用（对象时用 deepEqual 匹配，保证与 options 同引用） */
      resolveValueToOption (val) {
        if (val === undefined || val === null) return val
        if (this.data.length === 0) return val
        const opt = this.data.find(item => this.deepEqual(item.value, val))
        return opt ? opt.value : val
      },
      /** 深度相等（用于对象 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 = [
          'item-0padding', 'compact', 'out-radio', 'distributed', 'tab-style'
        ]
        booleanStyleKeys.forEach(key => {
          const val = attrs[key]
          const truthy = val === true || val === '' || val === 'true'
          if (truthy) classes[`x-radio-${key}`] = true
        })
        return classes
      },
      getHighlightBorderStyle (item) {
        if (!this.config.highlightBorder) return {}

        // 如果当前选项被选中且有边框颜色配置，使用配置的颜色
        if (this.isOptionSelected(item) && item.borderColor) {
          return {
            borderColor: item.borderColor
          }
        }

        // 如果当前选项被选中且有indicatorColor配置，使用indicatorColor作为边框颜色
        if (this.isOptionSelected(item) && item.indicatorColor) {
          return {
            borderColor: item.indicatorColor
          }
        }

        // 默认返回空对象，使用CSS中的默认灰色边框
        return {}
      }
    }
  }
  </script>

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

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

    &.x-radio-group-left {
      justify-content: flex-start;
    }

    &.x-radio-group-button {
      display: flex;
      justify-content: flex-end; // 居右对齐
      gap: 0; // 移除间距，让按钮紧密相连
      &.x-radio-group-left {
        justify-content: flex-start;
      }
      :deep(.ant-radio-button-wrapper) {
        border-radius: 0; // 先移除所有圆角
        border: 1px solid #d9d9d9;
        background: #fff;
        color: #000;
        transition: all 0.3s;
        min-width: 80px;
        text-align: center;
        margin: 0; // 确保没有外边距

        &:hover {
          border-color: #40a9ff;
          color: #40a9ff;
        }

        &.ant-radio-button-wrapper-checked {
          background-color: #0057FE;
          border-color: #0057FE;
          color: #fff;

          &:hover {
            background-color: #0057FE;
            border-color: #0057FE;
            color: #fff;
          }
        }
        // 第一个按钮只保留左侧圆角
        &:first-child {
          border-top-left-radius: 6px;
          border-bottom-left-radius: 6px;
          border-right: none; // 移除右边框，与下一个按钮连接
        }
        // 最后一个按钮只保留右侧圆角
        &:last-child {
          border-top-right-radius: 6px;
          border-bottom-right-radius: 6px;
        }
        // 中间按钮（如果有）移除所有圆角和右边框
        &:not(:first-child):not(:last-child) {
          border-radius: 0;
          border-right: none;
        }
        // 除了最后一个按钮，其他按钮都移除右边框
        &:not(:last-child) {
          border-right: none;
        }
      }
    }
  }

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

    .x-radio-group-left & {
      flex: none;
      align-items: flex-start;
      text-align: left;
      margin-right: 16px;
      padding: 0 4px;

      &:last-child {
        margin-right: 0;
      }
    }

    &.x-radio-item-bordered {
      border: 1px solid #d9d9d9;
      border-radius: 173px;
      padding: 8px 12px;
      margin-right: 8px;
      background-color: #fff;
      transition: all 0.3s;

      &:hover {
        border-color: #40a9ff;
      }

      &:last-child {
        margin-right: 0;
      }

      .x-radio-group-left & {
        margin-right: 8px;

        &:last-child {
          margin-right: 0;
        }
      }
    }

    &.x-radio-item-highlight {
      border: 2px solid #d9d9d9;
      border-radius: 173px;
      padding: 8px 12px;
      margin-right: 8px;
      background-color: #fff;
      transition: all 0.3s;
      position: relative;

      &:last-child {
        margin-right: 0;
      }

      .x-radio-group-left & {
        margin-right: 8px;

        &:last-child {
          margin-right: 0;
        }
      }

      // 动态边框颜色通过内联样式设置
    }
  }

  .x-radio-item-wrapper {
    display: flex;
    align-items: center;
    width: 100%;

    .x-radio-group-left & {
      justify-content: flex-start;
    }
  }

  .x-radio-item {
    margin-bottom: 8px;

    .x-radio-item-bordered & {
      margin-bottom: 0;
    }

    &.x-radio-item-no-dot {
      :deep(.ant-radio) {
        display: none;
      }

      :deep(.ant-radio-wrapper) {
        padding-left: 0;
      }
    }
  }

  .x-radio-indicator-left {
    width: 4px;
    height: 16px;
    margin-right: 8px;
    border-radius: 6px;
    transition: all 0.3s;
  }

  .x-radio-indicator-bottom {
    height: 3px;
    transition: all 0.3s;
    max-width: 100%;
  }

  .x-radio-description {
    padding: 4px 4px 4px 4px;
  }

  .x-radio-item-0padding {
    &.x-radio-container,
    .x-radio-container {
      :deep(.x-radio-item-container) {
        padding: 0px;
      }
    }
  }
  .x-radio-compact {
    &.x-radio-container,
    .x-radio-container {
      :deep(.simple-inline-item){
        padding: 0px !important;
      }
      :deep(.ant-radio-group){
        display: flex;
        justify-content: space-between;
      }
      :deep(.x-radio-item) > span:last-child {
        padding-right: 2px;
        padding-left: 2px;
      }
    }
  }
  /* 门诊收费样式：字体规格与间距 42px */
  .x-radio-out-radio {
    &.x-radio-container,
    .x-radio-container {
      :deep(.x-radio-group) {
        justify-content: flex-start !important; /* 覆盖默认的 space-around */
      }
      :deep(.ant-radio-wrapper) {
        /* 仅归零内外边距，避免额外空隙 */
        padding: 0;
        margin: 0;
      }
      /* 确保文字本身也应用同样的字体样式（提高优先级并可视化高度） */
      :deep(.ant-radio-wrapper > span:last-child) {
        display: inline-block;
        height: 23px !important;
        line-height: 23px !important;
        font-family: "Source Han Sans" !important;
        font-size: 16px !important;
        font-weight: normal !important;
        letter-spacing: 0em !important;
        color: #313131 !important;
      }
      /* 单选框与文字之间保持 5px 间距 */
      :deep(.ant-radio) { margin-right: 0; }
      :deep(.ant-radio + span) { padding: 0; margin-left: 5px; }
      /* 单选框外圈视觉 16x16，边框 #CDCFD4，背景白色 */
      :deep(.ant-radio-inner) {
        width: 16px;
        height: 16px;
        background: #FFFFFF;
        box-sizing: border-box;
        border: 1px solid #CDCFD4;
      }
      /* 选中时内部实心点 10x10，背景 #0057FE */
      :deep(.ant-radio-checked .ant-radio-inner::after) {
        width: 10px;
        height: 10px;
        background: #0057FE;
        margin: 0;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%) scale(1);
      }
      /* 保持外圈边框颜色不被默认覆盖 */
      :deep(.ant-radio-checked .ant-radio-inner) {
        border-color: #CDCFD4;
        background: #FFFFFF;
      }
      :deep(.x-radio-item-container) {
        margin-right: 42px; /* 直接设置42px间距，让第二个单选框与第一个文字距离为42px */
        padding: 0 !important;
        flex: none !important; /* 覆盖默认的 flex: 1 */
        align-items: flex-start !important; /* 覆盖默认的 center */
        text-align: left !important; /* 覆盖默认的 center */
      }
      :deep(.x-radio-item-wrapper) {
        width: auto !important; /* 覆盖默认的 width: 100% */
      }
      :deep(.x-radio-item-container:first-child) {
        margin-left: 4px;
      }
      :deep(.x-radio-item-container:last-child) {
        margin-right: 0;
      }
    }
  }

  /* 分布布局样式 */
  .x-radio-distributed {
    &.x-radio-container,
    .x-radio-container {
      width: 100%;
      :deep(.x-radio-group) {
        width: 100%;
        display: flex;
        justify-content: space-between;
        flex-wrap: nowrap;
        gap: 0;
        overflow: hidden;
      }
    :deep(.x-radio-item-container) {
      flex: 0 0 auto;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 0 2px;
        min-width: 0;
      }
    :deep(.x-radio-item-wrapper) {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }
      :deep(.ant-radio-wrapper) {
        padding: 0;
        margin: 0;
        display: flex;
        align-items: center;
      }
      :deep(.ant-radio) {
        margin-right: 0;
      }
      :deep(.ant-radio + span) {
        margin-left: 3px;
        padding: 0;
      }
      :deep(.ant-radio-inner) {
        width: 16px;
        height: 16px;
        opacity: 1;
        background: #FFFFFF;
        box-sizing: border-box;
        border: 1px solid #CDCFD4;
        transition: none !important;
      }
      :deep(.ant-radio-checked .ant-radio-inner::after) {
        width: 10px;
        height: 10px;
        opacity: 1;
        background: #0057FE;
        margin: 0;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%) scale(1);
        transition: none !important;
        animation: none !important;
      }
      :deep(.ant-radio-checked .ant-radio-inner) {
        border-color: #CDCFD4;
        background: #FFFFFF;
        transition: none !important;
      }
      :deep(.ant-radio-wrapper > span:last-child) {
        height: 23px;
        opacity: 1;
        font-family: "Source Han Sans";
        font-size: 16px;
        font-weight: normal;
        line-height: normal;
        letter-spacing: 0em;
        color: #5D5C5C;
        white-space: nowrap;
      }
    /* 改为内容自适应宽度，父容器使用 space-between 保证等距 */
    }
  }

  /* 标签页样式：带圆形图标和下划线 */
  .x-radio-tab-style {
    &.x-radio-container,
    .x-radio-container {
      :deep(.x-radio-group) {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        gap: 0;
        flex-wrap: nowrap;
      }
      :deep(.x-radio-item-container) {
        flex: none;
        display: flex;
        flex-direction: column;
        align-items: center;
        position: relative;
        padding: 0;
        margin-right: 0;
      }
      :deep(.x-radio-item-wrapper) {
        display: flex;
        align-items: center;
        justify-content: center;
        width: auto;
        position: relative;
      }
      :deep(.x-radio-item) {
        margin-bottom: 0;
        display: none;
        padding-left: 0;
        display: flex;
        align-items: center;
        font-family: "Source Han Sans" !important;
        font-size: 16px !important;
        font-weight: bold !important;
        color: #5D5C5C;
        line-height: normal;
        padding: 0;
        margin: 0;
      }
      :deep(.x-radio-tab-icon) {
        width: 12px;
        height: 12px;
        background-color: #0057FE;
        border-radius: 50%;
        margin-right: 8px;
        flex-shrink: 0;
        display: block;
      }
      :deep(.x-radio-tab-underline) {
        position: absolute;
        bottom: -8px;
        left: 0;
        right: 0;
        height: 2px;
        background-color: #0057FE;
        border-radius: 2px;
      }
      :deep(.x-radio-item-container:not(:last-child)) {
        margin-right: 12px;
      }
    }
  }
  </style>
