<template>
  <div class="vote-results">
    <div v-for="opt in options" :key="opt.id" class="progressContainer">
      <!-- 居中显示的状态 -->
      <el-progress
        v-if="voteStatus"
        class="centered-progress"
        :percentage="100"
        :format="() => opt.content"
        :stroke-width="30"
        :text-inside="true"
        :color="colors[opt.id]"
        style="width: 300px;"
        @click="clickBtn(opt.id)"
      />
      <!-- 显示 count 于灰条最右侧的状态 -->
      <div v-else class="progressWrapper">
        <el-progress
          class="left-progress"
          :percentage="opt.count"
          :format="() => opt.content + ' √'"
          :stroke-width="30"
          :text-inside="true"
          :color="colors[opt.id]"
        />
        <!-- 绝对定位在灰色轨道的最右边 -->
        <span class="count-right">{{ opt.count }}</span>
      </div>
    </div>
    <el-button @click="totalStatus">确认</el-button>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const voteStatus = ref(true)
const totalStatus = () => {
  voteStatus.value = !voteStatus.value
}

const options = ref([
  { id: 1, content: '选择1', count: 20 },
  { id: 2, content: '选择2', count: 30 },
  { id: 3, content: '选择3', count: 40 },
])

const colors = ref({})
function genUniqueColors() {
  const used = new Set()
  options.value.forEach(opt => {
    let c
    do {
      c = '#' + Math.floor(Math.random() * 0x1000000)
        .toString(16)
        .padStart(6, '0')
    } while (used.has(c))
    used.add(c)
    colors.value[opt.id] = c
  })
}
genUniqueColors()

const clickBtn = idx => {
  console.log('点击了：', idx)
}
</script>

<style scoped>
.progressContainer {
  width: 300px;
  margin-bottom: 20px;
}

/* 包含进度条的相对定位容器 */
.progressWrapper {
  position: relative;
  width: 300px; /* 同进度条宽度 */
}

/* count 数字，绝对定位到右端，中间垂直对齐 */
.count-right {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  margin-right: 4px; /* 根据需要微调，让数字在灰条内稍留空隙 */
  font-weight: bold;
  z-index: 1;
}

/* 居中状态 */
.centered-progress :deep(.el-progress-bar__inner) {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}
.centered-progress :deep(.el-progress-bar__inner-text) {
  margin: 0 !important;
  width: auto !important;
}

/* 左对齐文本状态 */
.left-progress :deep(.el-progress-bar__inner) {
  display: flex !important;
  align-items: center !important;
  justify-content: flex-start !important;
  padding-left: 8px !important;
}
.left-progress :deep(.el-progress-bar__inner-text) {
  margin: 0 !important;
}
</style>
