<template>
  <div class="page">
    <el-card class="mb-12">
      <div class="filters">
        <el-input v-model="filters.site_id" placeholder="中心ID" clearable @change="load" style="width: 160px" />
        <el-input v-model="filters.batch_id" placeholder="批次ID" clearable @change="load" style="width: 160px" />
        <el-select v-model="filters.tx_type" placeholder="交易类型" clearable @change="load" style="width: 160px">
          <el-option v-for="t in txTypes" :key="t" :label="txTypeLabel(t)" :value="t" />
        </el-select>
        <el-date-picker
          v-model="filters.date_from"
          type="date"
          placeholder="起始日期"
          value-format="YYYY-MM-DD"
          @change="load"
        />
        <el-date-picker
          v-model="filters.date_to"
          type="date"
          placeholder="截止日期"
          value-format="YYYY-MM-DD"
          @change="load"
        />
        <div class="spacer" />
        <PermissionAction action="imp.transaction">
          <el-button type="primary" @click="showForm = true">新建交易</el-button>
        </PermissionAction>
      </div>
    </el-card>
    <el-card>
      <el-table :data="txs" v-loading="loading" style="width: 100%">
        <el-table-column prop="tx_date" label="日期" width="120" />
        <el-table-column prop="tx_type" label="类型" width="140">
          <template #default="scope">
            {{ txTypeLabel(scope.row.tx_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="site_id" label="中心" width="180" />
        <el-table-column prop="batch_id" label="批次" width="180" />
        <el-table-column prop="subject_id" label="受试者" width="180" />
        <el-table-column prop="quantity" label="数量" width="100" align="right" />
        <el-table-column prop="reference" label="单号/备注" />
      </el-table>
      <el-pagination
        class="pagination"
        layout="prev, pager, next"
        :page-size="pageSize"
        :current-page="page"
        :total="total"
        @current-change="onPageChange"
      />
    </el-card>
    <ImpTransactionForm v-model="showForm" :batches="batches" @success="load" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import { fetchImpTransactions } from "../api/impTransactions";
import { fetchImpBatches } from "../api/impBatches";
import { useStudyStore } from "../store/study";
import { useAuthStore } from "../store/auth";
import PermissionAction from "../components/PermissionAction.vue";
import { usePermission } from "../utils/permission";
import ImpTransactionForm from "../components/ImpTransactionForm.vue";

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

const filters = ref({ site_id: "", batch_id: "", tx_type: "", date_from: "", date_to: "" });
const txTypes = ["RECEIPT", "DISPENSE", "RETURN", "DESTROY", "TRANSFER_IN", "TRANSFER_OUT"];
const txs = ref<any[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = 10;
const loading = ref(false);
const showForm = ref(false);
const batches = ref<any[]>([]);

const { can } = usePermission();
const canEdit = computed(() => can("imp.transaction"));

const loadBatches = async () => {
  if (!study.currentStudy) return;
  try {
    const { data } = await fetchImpBatches(study.currentStudy.id, { limit: 200 });
    batches.value = Array.isArray(data) ? data : data.items || [];
  } catch {
    /* ignore */
  }
};

const load = async () => {
  if (!study.currentStudy) return;
  loading.value = true;
  try {
    const params: Record<string, any> = { skip: (page.value - 1) * pageSize, limit: pageSize };
    Object.entries(filters.value).forEach(([k, v]) => {
      if (v) params[k] = v;
    });
    const { data } = await fetchImpTransactions(study.currentStudy.id, params);
    if (Array.isArray(data)) {
      txs.value = data;
      total.value = data.length;
    } else {
      txs.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;
  load();
};

const txTypeLabel = (t: string) =>
  ({
    RECEIPT: "入库",
    DISPENSE: "发放",
    RETURN: "回收",
    DESTROY: "销毁",
    TRANSFER_IN: "调入",
    TRANSFER_OUT: "调出",
  }[t] || t);

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

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