<template>
  <el-card class="color-card">
    <h3>调色盘</h3>

    <div class="color-picker-row">
      <div class="static-picker-container">
        <el-color-picker
          v-model="color"
          show-alpha
          :predefine="predefineColors"
          :teleported="false"
          popper-class="inline-picker-popper"
        />
      </div>

      <div class="color-info">
        <el-input
          v-model="hexInput"
          placeholder="输入 HEX"
          @change="updateColorFromHex"
          size="small"
          style="margin-bottom: 10px;"
        />
        <div class="preview" :style="{ background: color }"></div>
        <p>HEX: {{ toHex(color) }}</p>
        <p>RGB: {{ hexToRgb(color) }}</p>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, watch } from "vue"

// 注意：这里不需要 import 任何 Panel，让插件自动处理 el-color-picker
const color = ref("#409EFF")
const hexInput = ref(color.value)
const predefineColors = ["#409EFF", "#67C23A", "#E6A23C", "#F56C6C", "#909399"]

// --- 转换逻辑保持不变 ---
watch(color, (val) => {
  hexInput.value = toHex(val)
})

function updateColorFromHex() {
  if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(hexInput.value)) {
    color.value = hexInput.value
  }
}

function hexToRgb(hex) {
  if (!hex || typeof hex !== 'string') return ''
  if (hex.startsWith('rgb')) return hex
  let c = hex.substring(1).split('')
  if (c.length === 3) c = [c[0], c[0], c[1], c[1], c[2], c[2]]
  const r = parseInt(c[0] + c[1], 16)
  const g = parseInt(c[2] + c[3], 16)
  const b = parseInt(c[4] + c[5], 16)
  return `rgb(${r}, ${g}, ${b})`
}

function toHex(value) {
  if (!value || typeof value !== 'string') return ''
  if (value.startsWith("rgb")) {
    const nums = value.match(/\d+/g)
    if (nums && nums.length >= 3) {
      return "#" + nums.slice(0, 3).map(n => parseInt(n).toString(16).padStart(2, "0")).join("").toUpperCase()
    }
  }
  return value
}
</script>

<style scoped>
/* 1. 隐藏选择器本身的按钮小方块 */
.static-picker-container :deep(.el-color-picker__trigger) {
  display: none;
}

/* 2. 强行让本应弹出的面板显示出来 */
.static-picker-container :deep(.el-color-picker__panel),
.static-picker-container :deep(.inline-picker-popper) {
  display: block !important;
  position: relative !important;
  top: 0 !important;
  left: 0 !important;
  box-shadow: none !important;
  border: 1px solid #dcdfe6;
}

/* 3. 布局微调 */
.color-picker-row {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.preview {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  border: 1px solid #ddd;
  margin-bottom: 10px;
}

.color-card {
  max-width: 100%;
  margin: 20px auto;
}
</style>
