<template>
  <div class="page">
    <StateError v-if="errorMessage" :description="errorMessage">
      <template #action>
        <el-button type="primary" @click="load">{{ TEXT.common.actions.retry }}</el-button>
      </template>
    </StateError>

    <StateLoading v-else-if="loading" :rows="6" />

    <template v-else>
      <el-card class="detail-card unified-shell" shadow="never">
        <template #header>
          <div class="card-header actions-header">
            <span class="header-title">{{ TEXT.common.labels.basicInfo }}</span>
            <div class="actions">
              <el-button type="primary" :disabled="!canWrite || isReadOnly" @click="goEdit" class="header-action-btn copy-btn">
                <el-icon class="el-icon--left"><Edit /></el-icon>
                {{ TEXT.common.actions.edit }}
              </el-button>
              <el-button @click="goBack" class="header-action-btn">
                {{ TEXT.common.actions.back }}
              </el-button>
            </div>
          </div>
        </template>
        <el-descriptions :column="2" border class="custom-descriptions">
          <el-descriptions-item :label="TEXT.common.fields.site" label-class-name="desc-label">
            {{ centerName || TEXT.common.fallback }}
          </el-descriptions-item>
          <el-descriptions-item :label="TEXT.modules.feeContracts.contractAmount" label-class-name="desc-label">
            <span class="amount-text">{{ formatAmountWan(detail.contract_amount) }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="TEXT.modules.feeContracts.contractCases" label-class-name="desc-label">
            {{ detail.contract_cases ?? TEXT.common.fallback }}
          </el-descriptions-item>
          <el-descriptions-item :label="TEXT.modules.feeContracts.actualCases" label-class-name="desc-label">
            {{ detail.actual_cases ?? TEXT.common.fallback }}
          </el-descriptions-item>
          <el-descriptions-item :label="TEXT.modules.feeContracts.settlementAmount" label-class-name="desc-label">
            <span class="amount-text">{{ formatAmountWan(detail.settlement_amount) }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="TEXT.modules.feeContracts.finalPaymentAmount" label-class-name="desc-label">
            <span class="amount-text">{{ formatAmountWan(detail.final_payment_amount) }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card class="section-card unified-shell" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="header-title">{{ TEXT.modules.feeContracts.paymentTitle }}</span>
          </div>
        </template>
        <el-table :data="detail.payments" style="width: 100%" :header-cell-style="{ background: '#f8f9fb' }" table-layout="fixed">
          <el-table-column :label="TEXT.modules.feeContracts.paymentSeq">
            <template #default="scope">
              <span class="seq-tag">{{ TEXT.modules.feeContracts.paymentSeq }}{{ scope.row.seq }}{{ TEXT.modules.feeContracts.paymentSeqUnit }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="TEXT.common.fields.amount" align="right">
            <template #default="scope">
              <span class="amount-text">{{ formatAmountWan(scope.row.amount) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="TEXT.modules.feeContracts.paidFlag">
            <template #default="scope">
              <div v-if="scope.row.is_paid" class="status-cell">
                <el-tag type="success" size="small">{{ TEXT.modules.feeContracts.isPaid }}</el-tag>
                <span class="status-date">{{ displayDate(scope.row.paid_date) }}</span>
              </div>
              <span v-else class="text-muted">{{ TEXT.common.fallback }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="TEXT.modules.feeContracts.verifiedFlag">
            <template #default="scope">
              <div v-if="scope.row.is_verified" class="status-cell">
                <el-tag type="info" size="small">{{ TEXT.modules.feeContracts.isVerified }}</el-tag>
                <span class="status-date">{{ displayDate(scope.row.verified_date) }}</span>
              </div>
              <span v-else class="text-muted">{{ TEXT.common.fallback }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="TEXT.common.fields.remark" show-overflow-tooltip>
            <template #default="scope">{{ scope.row.remark || TEXT.common.fallback }}</template>
          </el-table-column>
          <template #empty>
            <div class="table-empty">{{ TEXT.modules.feeContracts.paymentEmpty }}</div>
          </template>
        </el-table>
      </el-card>

      <el-card class="section-card unified-shell" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="header-title">{{ TEXT.modules.feeContracts.attachmentTitle }}</span>
          </div>
        </template>
        <FeeAttachmentPanel
          v-if="contractId"
          :entity-type="'contract_fee'"
          :entity-id="contractId"
          :groups="attachmentGroups"
          :readonly="isReadOnly"
        />
      </el-card>
    </template>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Edit } from "@element-plus/icons-vue";
import { getContractFee } from "../../api/feeContracts";
import { fetchSites } from "../../api/sites";
import { useStudyStore } from "../../store/study";
import { usePermission } from "../../utils/permission";
import { displayDate } from "../../utils/display";
import StateError from "../../components/StateError.vue";
import StateLoading from "../../components/StateLoading.vue";
import FeeAttachmentPanel from "../../components/fees/FeeAttachmentPanel.vue";
import { TEXT } from "../../locales";

const route = useRoute();
const router = useRouter();
const study = useStudyStore();
const { can } = usePermission();
const canWrite = computed(() => can("fees.contract.write"));

const contractId = route.params.contractId as string;
const loading = ref(false);
const errorMessage = ref("");
const detail = reactive<any>({
  contract_amount: 0,
  contract_cases: 0,
  actual_cases: null,
  settlement_amount: null,
  final_payment_amount: null,
  payments: [],
});
const sites = ref<any[]>([]);
const siteActiveMap = computed(() => {
  const map: Record<string, boolean> = {};
  sites.value.forEach((site) => {
    if (site?.id) map[site.id] = !!site.is_active;
  });
  return map;
});
const isReadOnly = computed(() => !!detail.center_id && siteActiveMap.value[detail.center_id] === false);

const attachmentGroups = [
  {
    key: "contract",
    label: TEXT.modules.feeContracts.attachmentContract,
    description: TEXT.modules.feeContracts.attachmentContractDesc,
    emptyText: TEXT.modules.feeContracts.attachmentContractEmpty,
  },
  {
    key: "voucher",
    label: TEXT.modules.feeContracts.attachmentVoucher,
    description: TEXT.modules.feeContracts.attachmentVoucherDesc,
    emptyText: TEXT.modules.feeContracts.attachmentVoucherEmpty,
  },
  {
    key: "invoice",
    label: TEXT.modules.feeContracts.attachmentInvoice,
    description: TEXT.modules.feeContracts.attachmentInvoiceDesc,
    emptyText: TEXT.modules.feeContracts.attachmentInvoiceEmpty,
  },
];

const centerName = computed(() => {
  const match = sites.value.find((site) => site.id === detail.center_id);
  return match?.name || "";
});

const loadSites = async () => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;
  try {
    const { data } = await fetchSites(studyId, { limit: 500 });
    sites.value = Array.isArray(data) ? data : data.items || [];
  } catch {
    sites.value = [];
  }
};

const load = async () => {
  if (!contractId) return;
  loading.value = true;
  errorMessage.value = "";
  try {
    const { data } = await getContractFee(contractId);
    Object.assign(detail, data?.data || {});
    if (!Array.isArray(detail.payments)) detail.payments = [];
    
    // 同步中心名称到面包屑
    if (centerName.value) {
      study.setViewContext({ siteName: centerName.value });
    }
  } catch (e: any) {
    errorMessage.value = e?.response?.data?.message || TEXT.common.messages.loadFailed;
  } finally {
    loading.value = false;
  }
};

const formatAmountWan = (value: any) => {
  const numberValue = Number(value);
  if (Number.isNaN(numberValue)) return TEXT.common.fallback;
  return (numberValue / 10000).toFixed(2);
};

const goEdit = () => {
  if (isReadOnly.value) {
    ElMessage.warning("中心已停用");
    return;
  }
  router.push(`/fees/contracts/${contractId}/edit`);
};
const goBack = () => router.push("/fees/contracts");

onMounted(async () => {
  await loadSites();
  load();
});
</script>

<style scoped>
.page {
  display: flex;
  flex-direction: column;
  gap: 0;
}

.actions {
  display: flex;
  gap: 12px;
}

.header-action-btn {
  height: 36px;
  border-radius: 8px;
  padding: 0 16px;
}

.detail-card, .section-card {
  border-radius: 12px;
  border: 1px solid var(--ctms-border-color);
  overflow: hidden;
}

.section-card :deep(.el-card__body) {
  padding: 0;
}

.card-header {
  padding: 4px 0;
}

.actions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--ctms-text-main);
  border-left: 4px solid var(--el-color-primary);
  padding-left: 12px;
}

.custom-descriptions :deep(.desc-label) {
  background-color: var(--ctms-bg-color-page) !important;
  color: var(--ctms-text-secondary);
  width: 150px;
  font-weight: 500;
}

.amount-text {
  font-family: var(--el-font-family);
  font-weight: 600;
}

.seq-tag {
  color: var(--ctms-text-secondary);
  font-size: 13px;
}

.status-cell {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
}

.status-date {
  font-size: 12px;
  color: var(--ctms-text-secondary);
  font-family: var(--el-font-family);
}

.text-muted {
  color: var(--ctms-text-placeholder);
  font-size: 13px;
}
.table-empty {
  min-height: 220px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #8a97ab;
  font-size: 14px;
  font-weight: 500;
  letter-spacing: 0.02em;
}
</style>
