<template>
  <!-- 节点编辑弹窗 -->
  <el-dialog :model-value="showNodeDialog" @update:model-value="$emit('update:showNodeDialog', $event)" :title="isEditing ? '编辑目标' : '添加目标'" width="520px" :close-on-click-modal="true">
    <div class="mc-dialog-body">
      <div class="mc-form-item">
        <label>目标名称 <span class="mc-required">*</span></label>
        <input v-model="form.name" class="mc-input" placeholder="请输入目标名称" ref="dialogNameRef" />
      </div>
      <div class="mc-form-item">
        <label>描述</label>
        <textarea v-model="form.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: form.icon === key }"
            @click="form.icon = key" :title="ico">{{ iconEmoji(key) }}</button>
        </div>
      </div>
      <div class="mc-form-item">
        <label>目标值 <span class="mc-hint">（CMA字段）</span></label>
        <input v-model="form.targetValue" class="mc-input" type="number" placeholder="目标值" />
      </div>
      <div class="mc-row">
        <input v-model="form.currentValue" class="mc-input mc-input-half" type="number" placeholder="当前值" />
        <input v-model="form.unit" class="mc-input mc-input-half" placeholder="单位（如%、万元）" />
      </div>
      <div class="mc-row">
        <input v-model="form.owner" class="mc-input" placeholder="责任人" />
      </div>
      <div class="mc-form-item">
        <label>指标类型</label>
        <label class="mc-radio-label"><input type="radio" v-model="form.isLeading" :value="false" /> 滞后指标（结果）</label>
        <label class="mc-radio-label"><input type="radio" v-model="form.isLeading" :value="true" /> 领先指标（驱动）</label>
      </div>
    </div>
    <template #footer>
      <el-button size="small" @click="$emit('update:showNodeDialog', false)">取消</el-button>
      <el-button size="small" type="primary" @click="$emit('save-node-dialog')">保存</el-button>
    </template>
  </el-dialog>

  <!-- KPI因果链推荐弹窗 -->
  <el-dialog :model-value="showCausalityDialog" @update:model-value="$emit('update:showCausalityDialog', $event)" title="🔗 KPI因果链推荐" width="680px">
    <div style="max-height:400px;overflow-y:auto;">
      <div v-if="causalityLoading" style="text-align:center;padding:20px;color:#999;">加载中...</div>
      <div v-else-if="causalityRecommendations.length === 0" style="text-align:center;padding:20px;color:#999;">暂无因果链推荐</div>
      <div v-else>
        <div v-for="(rec,idx) in causalityRecommendations" :key="idx" style="padding:10px 0;border-bottom:1px solid #f0f0f0;display:flex;justify-content:space-between;align-items:center;">
          <div>
            <strong>{{ rec.source_kpi_code || rec.source_code }}</strong>
            <span style="color:#999;margin:0 8px;">→</span>
            <strong>{{ rec.target_kpi_code || rec.target_code }}</strong>
            <span style="margin-left:8px;font-size:12px;color:#666;">强度: {{ rec.strength || '-' }}</span>
          </div>
          <el-button size="small" @click="$emit('apply-causality', rec)">应用</el-button>
        </div>
      </div>
    </div>
    <template #footer>
      <el-button size="small" @click="$emit('update:showCausalityDialog', false)">取消</el-button>
      <el-button size="small" type="primary" @click="$emit('apply-all-causality')">一键全部应用</el-button>
    </template>
  </el-dialog>

  <!-- 版本历史弹窗 -->
  <el-dialog :model-value="showVersions" @update:model-value="$emit('update:showVersions', $event)" title="版本历史" width="620px">
    <div style="max-height:400px;overflow-y:auto;">
      <table class="mc-table" v-if="versions.length > 0">
        <thead><tr><th>说明</th><th>创建时间</th><th>操作</th></tr></thead>
        <tbody>
          <tr v-for="v in versions" :key="v.id">
            <td>{{ v.comment || '-' }}</td>
            <td>{{ v.created_at }}</td>
            <td><el-button size="small" type="warning" @click="$emit('rollback-version', v.id)">回滚</el-button></td>
          </tr>
        </tbody>
      </table>
      <div v-else style="text-align:center;color:#999;padding:20px;">暂无版本记录</div>
    </div>
  </el-dialog>

  <!-- KPI详情浮层 -->
  <el-dialog :model-value="showKpiDetail" @update:model-value="$emit('update:showKpiDetail', $event)" :title="'📊 ' + kpiDetailObjName + ' — KPI详情'" width="560px">
    <div style="max-height:360px;overflow-y:auto;">
      <div v-if="kpiDetailList.length === 0" style="text-align:center;color:#999;padding:20px;">
        该目标暂未关联KPI
      </div>
      <div v-for="(item, idx) in kpiDetailList" :key="idx" class="kpi-detail-card" :class="'kpi-detail-' + getKpiLevel(item)">
        <div class="kpi-detail-top">
          <span class="kpi-detail-badge">{{ badgeIcon(getKpiLevel(item)) }}</span>
          <span class="kpi-detail-code">{{ item.code }}</span>
          <span class="kpi-detail-name">{{ item.name }}</span>
        </div>
        <div class="kpi-detail-values">
          <div class="kdv-item">
            <span class="kdv-label">实际值</span>
            <span class="kdv-val">{{ item.actual != null ? fmtKpiVal(item.actual) : '—' }}</span>
          </div>
          <div class="kdv-item">
            <span class="kdv-label">目标值</span>
            <span class="kdv-val">{{ item.target != null ? fmtKpiVal(item.target) : '—' }}</span>
          </div>
          <div v-if="item.actual != null && item.target" class="kdv-item">
            <span class="kdv-label">达成率</span>
            <span class="kdv-val" :style="{ color: getKpiLevel(item) === 'red' ? '#f56c6c' : getKpiLevel(item) === 'yellow' ? '#e6a23c' : '#67c23a' }">
              {{ (item.actual / item.target * 100).toFixed(1) }}%
            </span>
          </div>
          <div v-if="item.unit" class="kdv-item">
            <span class="kdv-label">单位</span>
            <span class="kdv-val">{{ item.unit }}</span>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <el-button size="small" @click="$emit('update:showKpiDetail', false)">关闭</el-button>
      <el-button size="small" type="primary" @click="$emit('edit-kpi-obj')">编辑目标</el-button>
    </template>
  </el-dialog>

  <!-- 行动方案列表弹窗 -->
  <el-dialog :model-value="showPlanPopup" @update:model-value="$emit('update:showPlanPopup', $event)" :title="'📋 ' + planPopupObjName + ' — 关联行动方案'" width="600px">
    <div style="max-height:400px;overflow-y:auto;">
      <div v-if="planPopupList.length === 0" style="text-align:center;color:#999;padding:20px;">
        暂无关联的行动方案
      </div>
      <div v-for="p in planPopupList" :key="p.id" class="plan-popup-card">
        <div class="plan-popup-top">
          <span class="plan-popup-status" :class="'pps-' + p.status">{{ planStatusLabel(p.status) }}</span>
          <span class="plan-popup-title">{{ p.title }}</span>
        </div>
        <div class="plan-popup-meta">
          <span v-if="p.assignee">👤 {{ p.assignee }}</span>
          <span v-if="p.due_date">📅 {{ p.due_date.slice(0, 10) }}</span>
          <span v-if="p.progress > 0">进度 {{ p.progress }}%</span>
        </div>
      </div>
    </div>
    <template #footer>
      <el-button size="small" @click="$emit('update:showPlanPopup', false)">关闭</el-button>
      <el-button size="small" type="primary" @click="$emit('quick-create-plan')">+ 新建行动方案</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
defineProps<{
  showNodeDialog: boolean
  showCausalityDialog: boolean
  showVersions: boolean
  showKpiDetail: boolean
  showPlanPopup: boolean
  isEditing: boolean
  form: any
  causalityLoading: boolean
  causalityRecommendations: any[]
  versions: any[]
  kpiDetailObjName: string
  kpiDetailList: any[]
  planPopupObjName: string
  planPopupList: any[]
}>()

const emit = defineEmits<{
  (e: 'update:showNodeDialog', v: boolean): void
  (e: 'update:showCausalityDialog', v: boolean): void
  (e: 'update:showVersions', v: boolean): void
  (e: 'update:showKpiDetail', v: boolean): void
  (e: 'update:showPlanPopup', v: boolean): void
  (e: 'save-node-dialog'): void
  (e: 'apply-causality', rec: any): void
  (e: 'apply-all-causality'): void
  (e: 'rollback-version', id: number): void
  (e: 'edit-kpi-obj'): void
  (e: 'quick-create-plan'): void
}>()

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

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

function getKpiLevel(item: any): string {
  if (item.actual != null && item.target) {
    const ratio = item.actual / item.target
    if (ratio >= 0.9) return 'green'
    if (ratio >= 0.7) return 'yellow'
    return 'red'
  }
  return 'gray'
}

function fmtKpiVal(val: any): string {
  if (val == null) return '—'
  if (typeof val === 'number') {
    if (Math.abs(val) >= 10000) return (val / 10000).toFixed(1) + '万'
    return val.toLocaleString()
  }
  return String(val)
}

function badgeIcon(level: string): string {
  return level === 'green' ? '🟢' : level === 'yellow' ? '🟡' : level === 'red' ? '🔴' : '⚪'
}

function planStatusLabel(status: string): string {
  const map: Record<string, string> = { pending: '待处理', in_progress: '进行中', completed: '已完成', cancelled: '已取消' }
  return map[status] || status
}
</script>

<style scoped>
.mc-dialog-body { padding: 0; }
.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-input-half { width:48%; }
.mc-row { display:flex; gap:4%; margin-bottom:16px; }
.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; }
.mc-icon-btn:hover { border-color:#409eff; transform:scale(1.1); }
.mc-icon-btn.active { border-color:#409eff; background:#ecf5ff; }
.mc-radio-label { display:inline-flex; align-items:center; gap:4px; margin-right:16px; font-size:13px; color:#666; cursor:pointer; }
.mc-radio-label input { margin:0; }
.mc-table { width:100%; border-collapse:collapse; font-size:13px; }
.mc-table th, .mc-table td { padding:10px 12px; text-align:left; border-bottom:1px solid #f0f0f0; }
.mc-table th { background:#fafafa; font-weight:600; color:#666; font-size:12px; }
.mc-table tr:hover td { background:#f5f7fa; }
.kpi-detail-card { border: 1px solid #eee; border-radius: 8px; padding: 12px; margin-bottom: 8px; }
.kpi-detail-red { border-left: 4px solid #f56c6c; }
.kpi-detail-yellow { border-left: 4px solid #e6a23c; }
.kpi-detail-green { border-left: 4px solid #67c23a; }
.kpi-detail-gray { border-left: 4px solid #ccc; }
.kpi-detail-top { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
.kpi-detail-badge { font-size: 14px; }
.kpi-detail-code { font-size: 11px; color: #999; font-family: monospace; }
.kpi-detail-name { font-weight: 600; font-size: 14px; }
.kpi-detail-values { padding-left: 24px; display: flex; flex-direction: column; gap: 4px; }
.kdv-item { display: flex; align-items: center; gap: 8px; font-size: 13px; }
.kdv-label { color: #999; width: 56px; }
.kdv-val { font-weight: 500; }
.plan-popup-card { border: 1px solid #eee; border-radius: 8px; padding: 10px 12px; margin-bottom: 6px; }
.plan-popup-card:hover { background: #fafafa; }
.plan-popup-top { display: flex; align-items: center; gap: 8px; margin-bottom: 4px; }
.plan-popup-status { font-size: 10px; padding: 1px 6px; border-radius: 3px; font-weight: 500; flex-shrink: 0; }
.pps-pending { background: #f5f7fa; color: #909399; }
.pps-in_progress { background: #fdf6ec; color: #e6a23c; }
.pps-completed { background: #f0f9eb; color: #67c23a; }
.pps-cancelled { background: #f5f7fa; color: #bbb; }
.plan-popup-title { font-weight: 500; font-size: 13px; }
.plan-popup-meta { display: flex; gap: 12px; font-size: 11px; color: #999; padding-left: 4px; }
</style>
