<script setup lang="ts">
import {
  Banknote,
  ClipboardList,
  Gauge,
  ShieldCheck,
  UsersRound,
} from "@lucide/vue";
import { computed, onMounted, ref } from "vue";

import { exportMonthlyRun, listMonthlyRuns } from "../api/monthlyPayroll";
import type { MonthlyPayrollRun } from "../api/types";
import StatCard from "../components/StatCard.vue";
import { useAuthStore } from "../stores/auth";

const auth = useAuthStore();
const runs = ref<MonthlyPayrollRun[]>([]);
const loading = ref(false);
const errorMessage = ref("");

const latestRun = computed(() => runs.value[0]);
const recentRuns = computed(() => runs.value.slice(0, 5));
const totalEmployees = computed(() => runs.value.reduce((total, run) => total + run.employee_count, 0));
const chartBars = [32, 48, 58, 76, 68, 88];

onMounted(loadRuns);

async function loadRuns(): Promise<void> {
  if (!auth.hasPermission("monthly_payroll:view")) {
    return;
  }

  loading.value = true;
  errorMessage.value = "";
  try {
    runs.value = await listMonthlyRuns();
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : "核算历史加载失败";
  } finally {
    loading.value = false;
  }
}

async function download(run: MonthlyPayrollRun): Promise<void> {
  await exportMonthlyRun(run.id);
}

function sourceText(sourceType: string | undefined): string {
  const map: Record<string, string> = {
    excel: "Excel导入",
    dingtalk: "钉钉同步",
    manual: "手动重算",
  };
  return sourceType ? map[sourceType] || sourceType : "暂无";
}

function statusText(status: string | undefined): string {
  const map: Record<string, string> = {
    draft: "草稿",
    calculated: "已计算",
    reviewed: "已复核",
    locked: "已锁定",
    failed: "失败",
  };
  return status ? map[status] || status : "-";
}

function dateTime(value: string | null | undefined): string {
  return value ? new Date(value).toLocaleString() : "-";
}

function money(value: number): string {
  return new Intl.NumberFormat("zh-CN", {
    style: "currency",
    currency: "CNY",
    maximumFractionDigits: 0,
  }).format(value || 0);
}
</script>

<template>
  <div class="view-stack">
    <header class="page-header">
      <div>
        <h1>系统概览</h1>
        <p>实时财务状况与薪资指标。</p>
      </div>
      <div class="header-actions">
        <RouterLink v-if="auth.hasPermission('monthly_payroll:view')" class="primary-button" to="/payroll/monthly">
          <Banknote :size="19" aria-hidden="true" />
          <span>进入工资核算</span>
        </RouterLink>
        <RouterLink v-if="auth.hasPermission('monthly_payroll:view')" class="secondary-button" to="/payroll/monthly">
          <ClipboardList :size="19" aria-hidden="true" />
          <span>核算历史</span>
        </RouterLink>
      </div>
    </header>

    <section class="summary-strip">
      <StatCard
        title="最近核算人数"
        :value="String(latestRun?.employee_count || 0)"
        :icon="UsersRound"
        tone="blue"
        :meta="latestRun?.salary_month || '暂无月份'"
      />
      <StatCard
        title="核算记录"
        :value="String(runs.length)"
        :icon="ClipboardList"
        tone="neutral"
        meta="月度历史"
      />
      <StatCard
        title="累计核算人数"
        :value="String(totalEmployees)"
        :icon="Gauge"
        tone="green"
        meta="全部历史"
      />
      <StatCard
        title="当前权限"
        :value="auth.roleLabel"
        :icon="ShieldCheck"
        tone="neutral"
        :meta="auth.user?.username || '-'"
      />
    </section>

    <section class="dashboard-grid">
      <div class="panel sync-panel">
        <div class="panel-header">
          <div>
            <h2>钉钉同步</h2>
            <p>API 连接状态</p>
          </div>
          <span class="status-chip green">可用</span>
        </div>
        <dl class="compact-list">
          <div>
            <dt>最近来源</dt>
            <dd>{{ sourceText(latestRun?.source_type) }}</dd>
          </div>
          <div>
            <dt>最近生成</dt>
            <dd>{{ dateTime(latestRun?.created_at) }}</dd>
          </div>
        </dl>
        <RouterLink v-if="auth.hasPermission('monthly_payroll:calculate')" class="primary-button full" to="/payroll/monthly">
          <span>立即同步</span>
        </RouterLink>
      </div>

      <div class="panel trend-panel">
        <div class="panel-header">
          <div>
            <h2>月度薪资趋势</h2>
            <p>最近 6 个月</p>
          </div>
          <div class="legend-line">
            <span><i class="legend-blue" />实发薪资</span>
            <span><i />奖金</span>
          </div>
        </div>
        <div class="bar-chart" aria-label="月度薪资趋势">
          <div v-for="(height, index) in chartBars" :key="index" class="bar-item">
            <span class="bonus-bar" :style="{ height: `${Math.max(12, height - 22)}%` }" />
            <strong :style="{ height: `${height}%` }" />
            <em>{{ index + 1 }}月</em>
          </div>
        </div>
      </div>
    </section>

    <section class="panel">
      <div class="panel-header">
        <div>
          <h2>最近核算记录</h2>
          <p>{{ runs.length }} 条</p>
        </div>
        <RouterLink class="link-button" to="/payroll/monthly">查看全部</RouterLink>
      </div>
      <div v-if="errorMessage" class="inline-alert">{{ errorMessage }}</div>
      <div v-if="recentRuns.length" class="table-wrap">
        <table class="data-table">
          <thead>
            <tr>
              <th>工资月份</th>
              <th>来源</th>
              <th>状态</th>
              <th>员工数</th>
              <th>实发合计</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="run in recentRuns" :key="run.id">
              <td><strong>{{ run.salary_month }}</strong></td>
              <td><span class="status-chip neutral">{{ sourceText(run.source_type) }}</span></td>
              <td><span class="status-chip" :class="run.status === 'locked' ? 'green' : 'neutral'">{{ statusText(run.status) }}</span></td>
              <td>{{ run.employee_count }}</td>
              <td class="mono strong">{{ money(run.net_total) }}</td>
              <td>{{ dateTime(run.created_at) }}</td>
              <td>
                <button class="link-button" type="button" @click="download(run)">导出</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div v-else class="empty-state">
        <p>{{ loading ? "正在加载核算历史..." : "暂无核算历史" }}</p>
      </div>
    </section>
  </div>
</template>
