<template>
  <section class="workbench" aria-label="个人工作台">
    <PanelHead
      v-if="showHeader"
      eyebrow="Personal Workspace"
      title="个人工作台"
      note="把费用申请、报销进度、制度问答和待办处理集中到一个入口。"
    />

    <article class="panel workbench-trend-hero">
      <div class="workbench-trend-card" aria-label="报销趋势同比">
        <div class="trend-summary-panel">
          <h1>报销趋势</h1>
          <p>{{ reimbursementTrendRangeLabel }}</p>
          <strong class="trend-total">{{ reimbursementTrendTotalLabel }}</strong>
          <span class="trend-change" :class="reimbursementTrendGrowthTone">
            <i :class="reimbursementTrendGrowthIcon" aria-hidden="true"></i>
            {{ reimbursementTrendGrowthLabel }} 同比去年同期
          </span>
          <small>{{ displayUserName }} · {{ reimbursementTrendSignalLabel }}</small>
        </div>

        <div class="trend-chart-panel">
          <div class="trend-chart-head">
            <strong>月度报销明细</strong>
            <span class="trend-chart-source">与分析看板同源</span>
          </div>

          <TrendChart
            class="workbench-trend-chart"
            mode="compareAmount"
            :labels="reimbursementTrendLabels"
            :claim-amount="reimbursementTrendAmounts"
            :comparison-amount="reimbursementTrendPreviousAmounts"
            primary-label="本期"
            comparison-label="去年同期"
            compact
          />
        </div>
      </div>
    </article>

    <div :class="['capability-grid', capabilityGridClass]" aria-label="AI 财务助手能力">
      <button
        v-for="(item, index) in visibleAssistantCapabilities"
        :key="item.key"
        type="button"
        class="capability-card panel"
        :class="`capability-card--${item.tone}`"
        :style="{ '--delay': `${index * 80 + 100}ms` }"
        @click="openCapabilityAssistant(item)"
      >
        <WorkbenchListIcon
          class="capability-icon"
          :icon-key="item.key"
          color="var(--capability-color)"
          accent="var(--capability-soft)"
        />
        <span class="capability-copy">
          <strong>{{ item.title }}</strong>
          <small>{{ item.primary }}</small>
          <small>{{ item.secondary }}</small>
        </span>
        <i class="mdi mdi-chevron-right capability-arrow"></i>
      </button>
    </div>

    <div class="workbench-content-grid">
      <PersonalWorkbenchProgressPanel
        :progress-items="workbenchSummary.progressItems || []"
        @open-target="openWorkbenchTarget"
      />

      <aside class="side-column">
        <article class="panel workbench-card side-panel expense-stats-panel" style="--delay: 300ms;">
          <div class="section-head side-card-head">
            <h2>费用统计</h2>
            <button
              type="button"
              class="detail-action"
              aria-haspopup="dialog"
              :aria-expanded="expenseStatsModalOpen"
              @click="openExpenseStatsModal"
            >
              <span>查看详情</span>
              <i class="mdi mdi-chevron-right"></i>
            </button>
          </div>

          <div class="insight-metric-list" aria-label="费用统计">
            <div
              v-for="(item, index) in visibleExpenseStatItems"
              :key="item.key"
              class="insight-metric-row"
              :class="`insight-metric-row--${item.tone}`"
              :style="{ '--item-index': index }"
            >
              <span class="insight-metric-icon" aria-hidden="true">
                <i :class="item.icon"></i>
              </span>
              <span class="insight-metric-label">{{ item.label }}</span>
              <strong class="insight-metric-value">
                {{ item.value }}<small v-if="item.unit">{{ item.unit }}</small>
              </strong>
            </div>
          </div>
        </article>

        <article class="panel workbench-card side-panel usage-profile-panel" style="--delay: 400ms;">
          <div class="section-head side-card-head">
            <h2>用户画像</h2>
            <button
              type="button"
              class="detail-action"
              aria-haspopup="dialog"
              :aria-expanded="expenseProfileModalOpen"
              @click="openExpenseProfileModal"
            >
              <span>查看详情</span>
              <i :class="employeeProfileLoading ? 'mdi mdi-loading mdi-spin' : 'mdi mdi-chevron-right'"></i>
            </button>
          </div>

          <div class="insight-profile-list" aria-label="用户画像">
            <div
              v-for="(metric, index) in visibleUsageProfileMetrics"
              :key="metric.key"
              class="insight-profile-card"
              :class="`insight-profile-card--${metric.tone}`"
              :style="{ '--item-index': index }"
            >
              <span class="insight-profile-icon" aria-hidden="true">
                <i :class="metric.icon"></i>
              </span>
              <div class="insight-profile-copy">
                <span class="insight-profile-label">{{ metric.label }}</span>
                <strong class="insight-profile-value">
                  {{ metric.value }}<small>{{ metric.unit }}</small>
                </strong>
                <span class="insight-profile-hint">{{ metric.hint }}</span>
              </div>
            </div>
          </div>
        </article>
      </aside>
    </div>

    <ExpenseStatsDetailModal
      :visible="expenseStatsModalOpen"
      :user-name="displayUserName"
      :summary="workbenchSummary"
      :detail="expenseStatsDetail"
      @close="closeExpenseStatsModal"
    />

    <ExpenseProfileDetailModal
      :visible="expenseProfileModalOpen"
      :user-name="displayUserName"
      :metrics="expenseProfileModalMetrics"
      :tags="expenseProfileTags"
      :radar-dimensions="expenseProfileRadarDimensions"
      :radar-default-view="expenseProfileRadarDefaultView"
      :operations="expenseProfileOperations"
      :loading="employeeProfileLoading"
      :error-message="employeeProfileError"
      :empty-reason="expenseProfileEmptyReason"
      @close="closeExpenseProfileModal"
    />
  </section>
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import PanelHead from '../shared/PanelHead.vue'
import WorkbenchListIcon from '../shared/WorkbenchListIcon.vue'
import TrendChart from '../charts/TrendChart.vue'
import ExpenseStatsDetailModal from './ExpenseStatsDetailModal.vue'
import ExpenseProfileDetailModal from './ExpenseProfileDetailModal.vue'
import PersonalWorkbenchProgressPanel from './PersonalWorkbenchProgressPanel.vue'
import { useSystemState } from '../../composables/useSystemState.js'
import {
  buildExpenseStatItems,
  filterAssistantCapabilitiesForUser,
  resolveWorkbenchCapabilityGridClass,
} from '../../data/personalWorkbench.js'
import { fetchAgentRuns } from '../../services/agentAssets.js'
import { fetchCurrentEmployeeLatestProfile } from '../../services/reimbursements.js'
import { buildWorkbenchCapabilityAssistantPayload } from '../../utils/personalWorkbenchAssistantEntry.js'
import {
  buildProfileOperationsFromAgentRuns,
  buildUserProfileMetricCards,
  buildUserProfileSummaryMetrics,
  normalizeUserProfileRadarDimensions,
  normalizeUserProfileTags,
  resolveUserProfileDefaultRadarView,
  resolveCurrentUserProfileError
} from '../../utils/employeeProfileViewModel.js'
const props = defineProps({
  showHeader: { type: Boolean, default: true },
  assistantModalOpen: { type: Boolean, default: false },
  workbenchSummary: { type: Object, default: () => ({}) }
})

const emit = defineEmits(['open-assistant', 'open-document'])
const { currentUser } = useSystemState()
const expenseStatsModalOpen = ref(false)
const expenseProfileModalOpen = ref(false)
const employeeProfile = ref(null)
const employeeProfileRuns = ref([])
const employeeProfileLoading = ref(false)
const employeeProfileError = ref('')
let employeeProfileLoadSeq = 0
const SESSION_TYPE_EXPENSE = 'expense'
const SESSION_TYPE_STEWARD = 'steward'

const displayUserName = computed(() => {
  const user = currentUser.value || {}
  return String(user.name || user.username || '同事').trim() || '同事'
})
const visibleAssistantCapabilities = computed(() => filterAssistantCapabilitiesForUser(currentUser.value))
const capabilityGridClass = computed(() => resolveWorkbenchCapabilityGridClass(currentUser.value))
const expenseStatItems = computed(() => buildExpenseStatItems(props.workbenchSummary))
const visibleExpenseStatItems = computed(() => {
  const preferredKeys = ['monthly-amount', 'monthly-count', 'in-review', 'pending-payment']
  return preferredKeys
    .map((key) => expenseStatItems.value.find((item) => item.key === key))
    .filter(Boolean)
})
const visibleUsageProfileMetrics = computed(() => {
  return buildUserProfileMetricCards(
    employeeProfile.value,
    employeeProfileRuns.value,
    currentUser.value
  ).slice(0, 4)
})
const expenseProfileModalMetrics = computed(() => {
  return buildUserProfileSummaryMetrics(
    employeeProfile.value,
    employeeProfileRuns.value,
    currentUser.value
  )
})
const expenseProfileTags = computed(() => normalizeUserProfileTags(employeeProfile.value))
const expenseProfileRadarDimensions = computed(() => normalizeUserProfileRadarDimensions(employeeProfile.value))
const expenseProfileRadarDefaultView = computed(() => resolveUserProfileDefaultRadarView(employeeProfile.value))
const expenseProfileOperations = computed(() =>
  buildProfileOperationsFromAgentRuns(employeeProfileRuns.value, currentUser.value)
)
const expenseProfileEmptyReason = computed(() => String(employeeProfile.value?.empty_reason || '').trim())
const expenseStatsDetail = computed(() => props.workbenchSummary.expenseStatsDetail || {})
const currentUserProfileKey = computed(() => {
  const user = currentUser.value || {}
  return [user.username, user.email, user.name, user.employeeNo, user.employee_no].map((item) => String(item || '').trim()).filter(Boolean).join('|')
})

function formatCurrencyValue(value) {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0
  }).format(Number(value) || 0)
}

function normalizeTrendRows(rows = []) {
  return rows.map((row, index) => {
    const amount = Number(row?.amount || 0)
    const previousAmount = Number(row?.previousAmount || row?.previous_amount || 0)
    return {
      key: String(row?.key || `trend-${index}`),
      label: String(row?.label || `${index + 1}月`),
      amount,
      amountLabel: String(row?.amountLabel || row?.amount_label || formatCurrencyValue(amount)),
      previousKey: String(row?.previousKey || row?.previous_key || `previous-${index}`),
      previousAmount,
      previousAmountLabel: String(
        row?.previousAmountLabel || row?.previous_amount_label || formatCurrencyValue(previousAmount)
      )
    }
  })
}

const sourceReimbursementTrendRows = computed(() => normalizeTrendRows(props.workbenchSummary.reimbursementTrendRows || []))
const reimbursementTrendHasSignal = computed(() =>
  sourceReimbursementTrendRows.value.some((item) => item.amount > 0 || item.previousAmount > 0)
)
const reimbursementTrendRows = computed(() => sourceReimbursementTrendRows.value)
const reimbursementTrendSignalLabel = computed(() =>
  reimbursementTrendHasSignal.value ? '来自您的真实单据' : '暂无单据时展示空走势'
)
const reimbursementTrendLabels = computed(() => reimbursementTrendRows.value.map((item) => item.label))
const reimbursementTrendAmounts = computed(() => reimbursementTrendRows.value.map((item) => item.amount))
const reimbursementTrendPreviousAmounts = computed(() => reimbursementTrendRows.value.map((item) => item.previousAmount))
const reimbursementTrendTotal = computed(() =>
  reimbursementTrendRows.value.reduce((total, item) => total + item.amount, 0)
)
const reimbursementTrendPreviousTotal = computed(() =>
  reimbursementTrendRows.value.reduce((total, item) => total + item.previousAmount, 0)
)
const reimbursementTrendTotalLabel = computed(() => formatCurrencyValue(reimbursementTrendTotal.value))
const reimbursementTrendRangeLabel = computed(() => {
  const rows = reimbursementTrendRows.value
  const first = rows[0]
  const last = rows[rows.length - 1]
  if (!first || !last) {
    return '近 6 个月'
  }
  return `${first.label} - ${last.label}`
})
const reimbursementTrendGrowthRate = computed(() => {
  const previousTotal = reimbursementTrendPreviousTotal.value
  if (previousTotal > 0) {
    return ((reimbursementTrendTotal.value - previousTotal) / previousTotal) * 100
  }
  return reimbursementTrendTotal.value > 0 ? 100 : 0
})
const reimbursementTrendGrowthLabel = computed(() => {
  const value = reimbursementTrendGrowthRate.value
  const prefix = value >= 0 ? '+' : ''
  return `${prefix}${value.toFixed(1)}%`
})
const reimbursementTrendGrowthTone = computed(() =>
  reimbursementTrendGrowthRate.value >= 0 ? 'is-up' : 'is-down'
)
const reimbursementTrendGrowthIcon = computed(() =>
  reimbursementTrendGrowthRate.value >= 0 ? 'mdi mdi-arrow-up-right' : 'mdi mdi-arrow-down-right'
)
function buildAssistantPayload() {
  return {
    prompt: '',
    source: 'workbench',
    sessionType: SESSION_TYPE_STEWARD,
    files: []
  }
}

function emitAssistant(payload) {
  emit('open-assistant', payload)
}

function openPromptAssistant(prompt, sessionType = SESSION_TYPE_STEWARD) {
  emitAssistant({
    prompt: String(prompt || '').trim(),
    source: 'workbench',
    sessionType,
    files: [],
    conversation: null
  })
}

function openWorkbenchTarget(item) {
  const target = item?.target || {}
  if (target.type === 'document' && (target.id || target.claimNo)) {
    emit('open-document', {
      source: 'workbench',
      returnTo: 'workbench',
      claimId: target.id,
      id: target.id || target.claimNo,
      claimNo: target.claimNo
    })
    return
  }

  openPromptAssistant(item?.prompt || `查询 ${item?.id || ''} 的单据进度`, SESSION_TYPE_EXPENSE)
}

function openCapabilityAssistant(item) {
  emitAssistant(buildWorkbenchCapabilityAssistantPayload(item, buildAssistantPayload()))
}

async function loadCurrentEmployeeProfile() {
  const sequence = ++employeeProfileLoadSeq
  employeeProfileLoading.value = true
  employeeProfileError.value = ''

  const [profileResult, runsResult] = await Promise.allSettled([
    fetchCurrentEmployeeLatestProfile({
      scene: 'operations',
      window_days: 90,
      expense_type_scope: 'overall'
    }),
    fetchAgentRuns({ limit: 100 })
  ])

  if (sequence !== employeeProfileLoadSeq) {
    return
  }

  if (profileResult.status === 'fulfilled') {
    employeeProfile.value = profileResult.value || null
  } else {
    employeeProfile.value = null
    employeeProfileError.value = resolveCurrentUserProfileError(profileResult.reason)
  }

  employeeProfileRuns.value = runsResult.status === 'fulfilled' ? runsResult.value || [] : []
  employeeProfileLoading.value = false
}

function openExpenseStatsModal() {
  expenseStatsModalOpen.value = true
}

function closeExpenseStatsModal() {
  expenseStatsModalOpen.value = false
}

function openExpenseProfileModal() {
  expenseProfileModalOpen.value = true
  if (!employeeProfile.value && !employeeProfileLoading.value) {
    void loadCurrentEmployeeProfile()
  }
}

function closeExpenseProfileModal() {
  expenseProfileModalOpen.value = false
}

onMounted(() => {
  loadCurrentEmployeeProfile()
})

watch(currentUserProfileKey, (nextKey, previousKey) => {
  if (nextKey && nextKey !== previousKey) {
    loadCurrentEmployeeProfile()
  }
})
</script>

<style scoped src="../../assets/styles/components/personal-workbench.css"></style>
<style scoped src="../../assets/styles/components/personal-workbench-glass.css"></style>
<style scoped src="../../assets/styles/components/personal-workbench-insights.css"></style>
<style scoped src="../../assets/styles/components/personal-workbench-responsive.css"></style>
