<template>
  <ElDialog
    :model-value="visible"
    append-to-body
    align-center
    width="min(960px, calc(100vw - 64px))"
    :show-close="false"
    :lock-scroll="true"
    destroy-on-close
    class="expense-profile-dialog"
    modal-class="expense-profile-dialog-overlay"
    body-class="expense-profile-dialog-body"
    transition="expense-profile-dialog-zoom"
    aria-labelledby="expense-profile-modal-title"
    @update:model-value="handleVisibleChange"
  >
    <template #header>
      <header class="profile-dialog-header">
        <div class="profile-dialog-title-block">
          <span class="profile-dialog-eyebrow">User Behavior Profile</span>
          <h2 id="expense-profile-modal-title">{{ userName }}的用户画像详情</h2>
          <p>基于真实费用操作、AI 协作、流程质量和审核行为形成。</p>
        </div>

        <ElButton
          class="profile-dialog-close"
          text
          aria-label="关闭用户画像详情"
          @click="emitClose"
        >
          <i class="mdi mdi-close"></i>
        </ElButton>
      </header>
    </template>

    <section class="profile-dialog-content" aria-label="用户画像分析">
      <div v-if="profileStatusText" :class="['profile-dialog-alert', profileStatusTone]">
        <i :class="loading ? 'mdi mdi-loading mdi-spin' : 'mdi mdi-information-outline'"></i>
        <span>{{ profileStatusText }}</span>
      </div>

      <section v-if="metrics.length" class="profile-summary-grid" aria-label="画像核心指标">
        <article v-for="metric in metrics" :key="metric.key" class="profile-summary-item">
          <span>{{ metric.label }}</span>
          <strong>{{ metric.value }}<small>{{ metric.unit }}</small></strong>
          <em>{{ metric.hint }}</em>
        </article>
      </section>

      <div class="profile-analysis-grid">
        <section class="profile-panel profile-tags-panel" aria-label="画像标签">
          <div class="profile-section-title">
            <div>
              <span>画像标签</span>
              <small>按分数和业务解释排序</small>
            </div>
          </div>

          <ExpenseProfileTagPager v-if="tags.length" :tags="tags" :visible="visible" />
          <p v-else class="profile-panel-empty">暂无可展示的画像标签。</p>
        </section>

        <section class="profile-panel profile-radar-panel" aria-label="行为雷达图">
          <div class="profile-section-title profile-radar-title">
            <div>
              <span>行为雷达</span>
              <small>{{ currentRadarView.description }}</small>
            </div>
            <ElSelect
              v-model="selectedRadarView"
              class="profile-radar-view-select"
              size="small"
              aria-label="切换行为雷达视角"
            >
              <ElOption
                v-for="option in radarViewOptions"
                :key="option.value"
                :label="option.shortLabel"
                :value="option.value"
              />
            </ElSelect>
          </div>

          <div v-if="filteredRadarDimensions.length" class="profile-radar-layout">
            <RadarChart
              :key="radarRenderKey"
              class="profile-radar-chart"
              :items="filteredRadarDimensions"
              :label="`${currentRadarView.shortLabel}评分`"
            />
          </div>
          <p v-else class="profile-panel-empty profile-radar-empty">暂无可展示的雷达维度。</p>

          <div :class="['profile-behavior-tags', { 'is-empty': !filteredBehaviorTags.length }]" :aria-hidden="!filteredBehaviorTags.length" aria-label="行为标签">
            <span class="profile-behavior-tags-title">行为标签：</span>
            <div v-if="filteredBehaviorTags.length" class="profile-behavior-tag-list">
              <span
                v-for="tag in filteredBehaviorTags"
                :key="`behavior-${tag.code}`"
                :class="[
                  'profile-behavior-tag',
                  `profile-behavior-tag--${tag.tone}`,
                  `profile-behavior-tag--accent-${tag.colorIndex || 0}`
                ]"
              >
                {{ tag.label || tag.displayLabel }}
              </span>
            </div>
          </div>
        </section>
      </div>

      <section class="profile-panel profile-operation-panel" aria-label="最近 5 次操作内容">
        <div class="profile-section-title">
          <div>
            <span>最近 5 次操作内容</span>
            <small>用于理解画像标签的近期行为依据</small>
          </div>
        </div>

        <div v-if="operations.length" class="profile-operation-list">
          <article v-for="operation in operations" :key="operation.id" class="profile-operation-row">
            <time>{{ operation.time }}</time>
            <div class="profile-operation-copy">
              <strong>{{ operation.action }}</strong>
              <span>{{ operation.target }} · {{ operation.channel }}</span>
            </div>
            <ElTag
              class="profile-operation-status"
              :type="resolveOperationStatusType(operation.tone)"
              effect="light"
            >
              {{ operation.status }}
            </ElTag>
          </article>
        </div>
        <p v-else class="profile-panel-empty">暂无最近操作记录。</p>
      </section>
    </section>

    <template #footer>
      <footer class="profile-dialog-footer">
        <span>画像仅用于辅助分析，不作为自动审批或处罚依据。</span>
      </footer>
    </template>
  </ElDialog>
</template>

<script setup>
import { computed, nextTick, ref, watch } from 'vue'
import { ElButton } from 'element-plus/es/components/button/index.mjs'
import { ElDialog } from 'element-plus/es/components/dialog/index.mjs'
import { ElOption, ElSelect } from 'element-plus/es/components/select/index.mjs'
import { ElTag } from 'element-plus/es/components/tag/index.mjs'

import ExpenseProfileTagPager from './ExpenseProfileTagPager.vue'
import RadarChart from '../charts/RadarChart.vue'
import { USER_PROFILE_RADAR_VIEW_OPTIONS, filterUserProfileRadarDimensions, filterUserProfileTagsByRadarView } from '../../utils/employeeProfileViewModel.js'

const props = defineProps({
  visible: { type: Boolean, default: false },
  userName: { type: String, default: '同事' },
  metrics: { type: Array, default: () => [] },
  tags: { type: Array, default: () => [] },
  radarDimensions: { type: Array, default: () => [] },
  radarDefaultView: { type: String, default: 'financial_risk' },
  operations: { type: Array, default: () => [] },
  loading: { type: Boolean, default: false },
  errorMessage: { type: String, default: '' },
  emptyReason: { type: String, default: '' }
})

const emit = defineEmits(['close'])
const radarRenderKey = ref(0)
const selectedRadarView = ref(props.radarDefaultView)
const radarViewOptions = USER_PROFILE_RADAR_VIEW_OPTIONS
const currentRadarView = computed(() => radarViewOptions.find((option) => option.value === selectedRadarView.value) || radarViewOptions[0])
const filteredRadarDimensions = computed(() => filterUserProfileRadarDimensions(props.radarDimensions, selectedRadarView.value))
const filteredBehaviorTags = computed(() => filterUserProfileTagsByRadarView(props.tags, selectedRadarView.value))

function emitClose() {
  emit('close')
}

function handleVisibleChange(value) {
  if (!value) {
    emitClose()
  }
}

const profileStatusText = computed(() => {
  if (props.loading) {
    return '正在读取真实用户画像数据...'
  }
  if (props.errorMessage) {
    return props.errorMessage
  }
  if (props.emptyReason) {
    return props.emptyReason
  }
  return ''
})

const profileStatusTone = computed(() => {
  if (props.errorMessage) {
    return 'is-error'
  }
  if (props.emptyReason) {
    return 'is-empty'
  }
  return 'is-loading'
})

function resolveOperationStatusType(tone) {
  const normalized = String(tone || '').trim()

  if (['success', 'positive', 'emerald'].includes(normalized)) {
    return 'success'
  }
  if (['warning', 'risk', 'amber'].includes(normalized)) {
    return 'warning'
  }
  if (['danger', 'high'].includes(normalized)) {
    return 'danger'
  }
  return 'info'
}

function scheduleRadarFrame(callback) {
  if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') {
    window.requestAnimationFrame(callback)
    return
  }
  callback()
}

watch(
  () => props.visible,
  async (visible) => {
    if (!visible) {
      return
    }
    await nextTick()
    scheduleRadarFrame(() => {
      radarRenderKey.value += 1
    })
  }
)

watch(
  () => props.radarDefaultView,
  (value) => {
    selectedRadarView.value = value || 'financial_risk'
  },
  { immediate: true }
)

watch(
  [filteredRadarDimensions, selectedRadarView],
  async () => {
    if (!props.visible) {
      return
    }
    await nextTick()
    scheduleRadarFrame(() => {
      radarRenderKey.value += 1
    })
  }
)
</script>

<style scoped src="../../assets/styles/components/expense-profile-detail-modal.css"></style>

