<template>
  <div class="page">
    <el-card v-loading="loading">
      <div class="header">
        <div>
          <h3>{{ item?.title }}</h3>
          <el-tag :type="stateColor(item?.status)">{{ stateLabel(item?.status) }}</el-tag>
        </div>
        <div class="header-actions" v-if="item">
          <PermissionAction action="finance.create">
            <el-button v-if="canEditDraft" size="small" @click="showEdit = true">编辑</el-button>
          </PermissionAction>
          <FinanceStatusActions :item="item" @success="loadItem" />
        </div>
      </div>
      <el-descriptions :column="2" border class="mt-12" v-if="item">
        <el-descriptions-item label="类别">{{ item.category }}</el-descriptions-item>
        <el-descriptions-item label="金额">￥{{ formatAmount(item.amount) }} {{ item.currency }}</el-descriptions-item>
        <el-descriptions-item label="发生日期">{{ item.occur_date }}</el-descriptions-item>
        <el-descriptions-item label="中心">{{ item.site_id || "-" }}</el-descriptions-item>
        <el-descriptions-item label="受试者">{{ item.subject_id || "-" }}</el-descriptions-item>
        <el-descriptions-item label="状态时间">
          提交: {{ item.submitted_at || "-" }} / 审批: {{ item.approved_at || "-" }} /
          支付: {{ item.paid_at || "-" }}
        </el-descriptions-item>
        <el-descriptions-item label="驳回原因">{{ item.reject_reason || "-" }}</el-descriptions-item>
        <el-descriptions-item label="描述">{{ item.description || "-" }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="mt-12" v-if="item">
      <AttachmentList
        :study-id="study.currentStudy?.id || ''"
        entity-type="finance"
        :entity-id="item.id"
        :show-uploader="true"
      />
    </el-card>

    <FinanceForm v-model="showEdit" :item="item" @success="loadItem" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import FinanceStatusActions from "../components/FinanceStatusActions.vue";
import FinanceForm from "../components/FinanceForm.vue";
import PermissionAction from "../components/PermissionAction.vue";
import AttachmentList from "../components/attachments/AttachmentList.vue";
import { fetchFinanceItem } from "../api/finance";
import { useStudyStore } from "../store/study";
import { useAuthStore } from "../store/auth";
import { usePermission } from "../utils/permission";
import { financeMachine, getAvailableActions } from "../state-machine";
import { financeStatusDict, getDictColor, getDictLabel } from "../dictionaries";

const study = useStudyStore();
const auth = useAuthStore();
const route = useRoute();

const item = ref<any>(null);
const loading = ref(false);
const showEdit = ref(false);
const { can } = usePermission();
const canEditDraft = computed(() => {
  const actions = getAvailableActions(financeMachine, item.value?.status);
  const submitAllowed = actions.some((a) => a.key === "submit");
  return submitAllowed && can("finance.create");
});

const loadItem = async () => {
  if (!study.currentStudy) return;
  const id = route.params.itemId as string;
  loading.value = true;
  try {
    const { data } = await fetchFinanceItem(study.currentStudy.id, id);
    item.value = data;
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "加载失败");
  } finally {
    loading.value = false;
  }
};

const stateLabel = (v?: string | null) => getDictLabel(financeStatusDict, v || "");
const stateColor = (v?: string | null) => getDictColor(financeStatusDict, v || "") || "info";

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

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

<style scoped>
.page {
  padding: 16px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.mt-12 {
  margin-top: 12px;
}
</style>
