<template>
  <div class="page">
    <FinanceSummary :summary="summary" class="mb-12" />

    <el-card class="mb-12">
      <div class="filters">
        <el-select v-model="filters.status" placeholder="状态" clearable @change="loadList">
          <el-option v-for="s in statuses" :key="s" :label="s" :value="s" />
        </el-select>
        <el-select v-model="filters.category" placeholder="类别" clearable @change="loadList">
          <el-option v-for="c in categories" :key="c" :label="c" :value="c" />
        </el-select>
        <el-date-picker
          v-model="filters.date_from"
          type="date"
          placeholder="开始日期"
          value-format="YYYY-MM-DD"
          @change="loadList"
        />
        <el-date-picker
          v-model="filters.date_to"
          type="date"
          placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="loadList"
        />
        <div class="spacer" />
        <el-button type="primary" v-if="canCreate" @click="showForm = true">新建费用</el-button>
      </div>
    </el-card>

    <el-card>
      <el-table :data="items" v-loading="loading" @row-click="goDetail" style="width: 100%">
        <el-table-column prop="title" label="标题" min-width="160" />
        <el-table-column prop="category" label="类别" width="140" />
        <el-table-column prop="amount" label="金额" width="140" align="right">
          <template #default="scope">
            ￥{{ formatAmount(scope.row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="occur_date" label="发生日期" width="140" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="statusTag(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="submitted_at" label="提交时间" width="160" />
        <el-table-column prop="approved_at" label="审批时间" width="160" />
        <el-table-column prop="paid_at" label="支付时间" width="160" />
      </el-table>
      <el-pagination
        class="pagination"
        layout="prev, pager, next"
        :page-size="pageSize"
        :current-page="page"
        :total="total"
        @current-change="onPageChange"
      />
    </el-card>

    <FinanceForm v-model="showForm" @success="loadList" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import FinanceSummary from "../components/FinanceSummary.vue";
import FinanceForm from "../components/FinanceForm.vue";
import { fetchFinanceItems, fetchFinanceSummary } from "../api/finance";
import { useStudyStore } from "../store/study";
import { useAuthStore } from "../store/auth";

const study = useStudyStore();
const auth = useAuthStore();
const router = useRouter();

const items = ref<any[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = 10;
const loading = ref(false);
const summary = ref<any>(null);

const filters = ref({
  status: "",
  category: "",
  date_from: "",
  date_to: "",
});

const statuses = ["DRAFT", "SUBMITTED", "APPROVED", "REJECTED", "PAID"];
const categories = ["SITE_FEE", "SUBJECT_STIPEND", "TRAVEL", "OTHER"];

const showForm = ref(false);

const canCreate = computed(() => {
  const role = auth.user?.role;
  return role === "ADMIN" || role === "PM" || role === "CRA";
});

const formatAmount = (num?: number | string) => {
  const n = Number(num);
  return Number.isFinite(n) ? n.toFixed(2) : "0.00";
};

const statusTag = (status?: string) => {
  switch (status) {
    case "DRAFT":
      return "info";
    case "SUBMITTED":
      return "warning";
    case "APPROVED":
      return "success";
    case "REJECTED":
      return "danger";
    case "PAID":
      return "success";
    default:
      return "info";
  }
};

const loadSummary = async () => {
  if (!study.currentStudy) return;
  try {
    const { data } = await fetchFinanceSummary(study.currentStudy.id);
    summary.value = Array.isArray(data) ? data[0] : data;
  } catch (e: any) {
    /* ignore summary errors */
  }
};

const loadList = async () => {
  if (!study.currentStudy) return;
  loading.value = true;
  try {
    const params: Record<string, any> = { skip: (page.value - 1) * pageSize, limit: pageSize };
    if (filters.value.status) params.status = filters.value.status;
    if (filters.value.category) params.category = filters.value.category;
    if (filters.value.date_from) params.date_from = filters.value.date_from;
    if (filters.value.date_to) params.date_to = filters.value.date_to;
    const { data } = await fetchFinanceItems(study.currentStudy.id, params);
    if (Array.isArray(data)) {
      items.value = data;
      total.value = data.length;
    } else {
      items.value = data.items || [];
      total.value = data.total || 0;
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "费用列表加载失败");
  } finally {
    loading.value = false;
  }
};

const onPageChange = (p: number) => {
  page.value = p;
  loadList();
};

const goDetail = (row: any) => {
  router.push(`/study/finance/${row.id}`);
};

onMounted(async () => {
  if (!auth.user && auth.token) {
    await auth.fetchMe().catch(() => {});
  }
  await loadSummary();
  await loadList();
});
</script>

<style scoped>
.page {
  padding: 16px;
}
.filters {
  display: flex;
  gap: 8px;
  align-items: center;
}
.spacer {
  flex: 1;
}
.pagination {
  margin-top: 12px;
  text-align: right;
}
.mb-12 {
  margin-bottom: 12px;
}
</style>
