<template>
  <div v-if="visible" class="mc-dialog-overlay" @click.self="$emit('close')">
    <div class="mc-dialog-box">
      <div class="mc-dialog-header">
        <span>{{ isEditing ? '编辑目标' : '添加目标' }}</span>
        <button class="mc-dialog-close" @click="$emit('close')">×</button>
      </div>
      <div class="mc-dialog-body">
        <div class="mc-form-item">
          <label>目标名称 <span class="mc-required">*</span></label>
          <input v-model="localForm.name" class="mc-input" placeholder="请输入目标名称" ref="nameInputRef" />
        </div>
        <div class="mc-form-item">
          <label>描述</label>
          <textarea v-model="localForm.description" class="mc-input mc-textarea" rows="3" placeholder="目标描述（可选）"></textarea>
        </div>
        <div class="mc-form-item">
          <label>图标</label>
          <div class="mc-icon-picker">
            <button
              v-for="(ico, key) in iconOptions" :key="key"
              class="mc-icon-btn"
              :class="{ active: localForm.icon === key }"
              @click="localForm.icon = key"
              :title="ico"
            >{{ iconEmoji(key) }}</button>
          </div>
        </div>
        <div class="mc-form-item">
          <label>关联KPI <span class="mc-hint">（最多3个）</span></label>
          <div class="mc-kpi-select-wrap">
            <div class="mc-kpi-tags" v-if="localForm.kpis.length > 0">
              <span class="mc-kpi-tag" v-for="(code, i) in localForm.kpis" :key="code">
                {{ getKpiName(code) }}
                <button class="mc-tag-remove" @click="localForm.kpis.splice(i, 1)">×</button>
              </span>
            </div>
            <div class="mc-kpi-add-row" v-if="localForm.kpis.length < 3 && allKpis.length > 0">
              <select class="mc-select mc-select-sm" @change="addKpi($event)" style="flex:1;">
                <option value="">+ 选择KPI（{{ dimLabel }}）</option>
                <option v-for="k in availableKpis" :key="k.id" :value="k.kpi_code">{{ k.kpi_name }}</option>
                <option value="__new__">+ 新建KPI...</option>
              </select>
            </div>
            <div v-if="allKpis.length === 0" style="color:#999;font-size:12px;">
              暂无该维度KPI，
              <el-button text size="small" type="primary" @click="onNewKpi">点击新建</el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="mc-dialog-footer">
        <button class="mc-btn" @click="$emit('close')">取消</button>
        <button class="mc-btn mc-btn-primary" @click="onSave">保存</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps<{
  visible: boolean
  form: { name: string; description: string; icon: string; kpis: string[] }
  dimKey: string
  dimLabel: string
  isEditing: boolean
  allKpis: any[]
  kpiNameMap: Record<string, string>
}>()

const emit = defineEmits<{
  (e: 'close'): void
  (e: 'save', form: { name: string; description: string; icon: string; kpis: string[] }): void
  (e: 'new-kpi'): void
}>()

const nameInputRef = ref<HTMLElement | null>(null)
const localForm = reactive({ name: '', description: '', icon: 'target', kpis: [] as string[] })

watch(() => props.visible, (v) => {
  if (v) {
    localForm.name = props.form.name
    localForm.description = props.form.description
    localForm.icon = props.form.icon || 'target'
    localForm.kpis = [...(props.form.kpis || [])]
    nextTick(() => nameInputRef.value?.focus())
  }
})

const iconOptions: Record<string, string> = {
  target: '目标', star: '星级', rocket: '火箭', chart: '图表', team: '团队',
  light: '灯泡', shield: '盾牌', gear: '齿轮', handshake: '握手', medal: '奖牌',
}

function iconEmoji(key: string): string {
  const map: Record<string, string> = {
    target: '🎯', star: '⭐', rocket: '🚀', chart: '📊', team: '👥',
    light: '💡', shield: '🛡️', gear: '⚙️', handshake: '🤝', medal: '🏅',
  }
  return map[key] || '📌'
}

const availableKpis = computed(() => {
  return props.allKpis.filter((k: any) => {
    if (k.dimension !== props.dimKey) return false
    if (localForm.kpis.includes(k.kpi_code)) return false
    return true
  })
})

function getKpiName(code: string): string {
  return props.kpiNameMap[code] || code
}

function addKpi(e: any) {
  const val = e.target.value
  if (val === '__new__') {
    e.target.value = ''
    emit('new-kpi')
    return
  }
  if (val && !localForm.kpis.includes(val) && localForm.kpis.length < 3) {
    localForm.kpis.push(val)
  }
  e.target.value = ''
}

function onNewKpi() {
  emit('new-kpi')
}

function onSave() {
  if (!localForm.name?.trim()) {
    ElMessage.warning('请输入目标名称')
    nextTick(() => nameInputRef.value?.focus())
    return
  }
  emit('save', {
    name: localForm.name.trim(),
    description: localForm.description?.trim() || '',
    icon: localForm.icon || 'target',
    kpis: [...localForm.kpis],
  })
}
</script>

<style scoped>
.mc-dialog-overlay {
  position: fixed; top:0; left:0; right:0; bottom:0;
  background:rgba(0,0,0,0.5); z-index:9999;
  display:flex; align-items:center; justify-content:center;
}
.mc-dialog-box {
  background:#fff; border-radius:12px; width:520px;
  box-shadow:0 8px 32px rgba(0,0,0,0.18); overflow:hidden;
}
.mc-dialog-header {
  display:flex; justify-content:space-between; align-items:center;
  padding:16px 20px; border-bottom:1px solid #f0f0f0;
  font-weight:600; font-size:16px;
}
.mc-dialog-close {
  background:none; border:none; font-size:22px; color:#999;
  cursor:pointer; padding:0 4px; line-height:1;
}
.mc-dialog-close:hover { color:#333; }
.mc-dialog-body { padding:20px; }
.mc-dialog-footer {
  display:flex; justify-content:flex-end; gap:10px;
  padding:12px 20px; border-top:1px solid #f0f0f0;
}
.mc-form-item { margin-bottom:16px; }
.mc-form-item label {
  display:block; font-size:13px; color:#666; margin-bottom:6px; font-weight:500;
}
.mc-required { color:#f56c6c; margin-left:2px; }
.mc-hint { font-weight:400; color:#999; font-size:12px; }
.mc-input {
  width:100%; padding:8px 12px; border:1px solid #dcdfe6;
  border-radius:6px; font-size:14px; outline:none; box-sizing:border-box;
}
.mc-input:focus { border-color:#409eff; }
.mc-textarea { resize:vertical; min-height:60px; font-family:inherit; }
.mc-select {
  width:100%; padding:8px 12px; border:1px solid #dcdfe6;
  border-radius:6px; font-size:14px; outline:none; background:#fff; box-sizing:border-box;
}
.mc-select:focus { border-color:#409eff; }
.mc-select-sm { font-size:13px; padding:6px 10px; }
.mc-btn {
  padding:8px 20px; border:1px solid #dcdfe6; border-radius:6px;
  background:#fff; color:#333; font-size:14px; cursor:pointer;
}
.mc-btn-primary { background:#409eff; color:#fff; border-color:#409eff; }
.mc-btn:hover { opacity:0.85; }
.mc-icon-picker {
  display:flex; flex-wrap:wrap; gap:6px;
}
.mc-icon-btn {
  width:40px; height:40px; display:flex; align-items:center; justify-content:center;
  font-size:20px; border:2px solid #e8e8e8; border-radius:8px;
  background:#fff; cursor:pointer; transition:all .15s;
}
.mc-icon-btn:hover { border-color:#409eff; transform:scale(1.1); }
.mc-icon-btn.active { border-color:#409eff; background:#ecf5ff; box-shadow:0 0 0 2px rgba(64,158,255,0.2); }
.mc-kpi-select-wrap { display:flex; flex-direction:column; gap:6px; }
.mc-kpi-tags { display:flex; flex-wrap:wrap; gap:6px; }
.mc-kpi-tag {
  display:inline-flex; align-items:center; gap:4px;
  padding:4px 10px; background:#ecf5ff; color:#409eff;
  border-radius:4px; font-size:12px;
}
.mc-tag-remove {
  background:none; border:none; color:#a0cfff; cursor:pointer;
  font-size:14px; padding:0; line-height:1;
}
.mc-tag-remove:hover { color:#f56c6c; }
</style>
