<template>
  <div class="page">
    <h2 class="page-title">订单管理</h2>
    <div class="panel">
      <div class="inline-form">
        <t-button theme="primary" @click="load">
          <template #icon><t-icon name="refresh" /></template>
          刷新
        </t-button>
        <t-button v-if="canEdit" variant="outline" @click="openCreate">
          <template #icon><t-icon name="add" /></template>
          新增订单
        </t-button>
      </div>
      <t-table :data="list" :columns="columns" row-key="id" bordered stripe hover>
        <template #visitId="{ row }">
          {{ getVisitLabel(row.visitId) }}
        </template>
        <template #status="{ row }">
          <span class="status-badge" :class="getStatusClass(row.status)">
            {{ getStatusText(row.status) }}
          </span>
        </template>
        <template #paymentMethod="{ row }">
          <span>{{ getPaymentMethodText(row.paymentMethod) }}</span>
        </template>
        <template #op="{ row }">
          <div class="table-actions">
            <t-button v-if="canEdit" size="small" variant="outline" @click="openEdit(row)">
              <template #icon><t-icon name="edit" /></template>
              编辑
            </t-button>
          </div>
        </template>
      </t-table>
    </div>

    <t-dialog v-model:visible="dialogVisible" :header="dialogTitle" :on-confirm="submit" width="600">
      <t-form :data="form" layout="vertical">
        <div class="form-section-title">订单信息</div>
        <t-form-item label="就诊记录" required>
          <t-select v-model="form.visitId" :options="visitOptions" placeholder="请选择就诊记录" clearable />
        </t-form-item>
        <t-form-item label="订单金额" required>
          <t-input-number v-model="form.amount" placeholder="0.00" suffix="元" />
        </t-form-item>
        <t-row :gutter="[16, 16]">
          <t-col :span="6">
            <t-form-item label="订单状态">
              <t-select v-model="form.status" :options="statusOptions" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="支付方式">
              <t-select v-model="form.paymentMethod" :options="payOptions" />
            </t-form-item>
          </t-col>
        </t-row>
        <t-form-item label="备注">
          <t-textarea v-model="form.remark" placeholder="请输入备注信息" :maxlength="200" />
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { api } from '../api';
import { useAuthStore } from '../store/auth';

const list = ref([] as any[]);
const visits = ref([] as any[]);
const dialogVisible = ref(false);
const dialogTitle = ref('新增订单');
const editingId = ref<number | null>(null);
const form = reactive({ visitId: '', amount: '', paymentMethod: 'OFFLINE', status: 'UNPAID' });
const auth = useAuthStore();

const canEdit = computed(() => auth.user?.role === 'ADMIN');

const visitOptions = computed(() => {
  return visits.value.map((visit: any) => ({
    label: `就诊#${visit.id} - 宠物ID:${visit.petId}, 顾客ID:${visit.customerId}`,
    value: visit.id
  }));
});

const getVisitLabel = (visitId: number) => {
  const visit = visits.value.find((item: any) => item.id === visitId);
  if (!visit) return visitId ? `就诊ID ${visitId}` : '-';
  return `就诊#${visit.id}`;
};

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'UNPAID': '未支付',
    'PAID': '已支付',
    'CANCELLED': '已取消',
    'REFUNDING': '退款中',
    'REFUNDED': '已退款'
  };
  return statusMap[status] || status;
};

const getStatusClass = (status: string) => {
  const classMap: Record<string, string> = {
    'UNPAID': 'status-pending',
    'PAID': 'status-active',
    'CANCELLED': 'status-cancelled',
    'REFUNDING': 'status-warning',
    'REFUNDED': 'status-cancelled'
  };
  return classMap[status] || 'status-pending';
};

const getPaymentMethodText = (method: string) => {
  const methodMap: Record<string, string> = {
    'OFFLINE': '线下支付',
    'ALIPAY': '支付宝',
    'WECHAT': '微信'
  };
  return methodMap[method] || method;
};

const payOptions = [
  { label: '线下支付', value: 'OFFLINE' },
  { label: '支付宝', value: 'ALIPAY' },
  { label: '微信', value: 'WECHAT' },
];

const statusOptions = [
  { label: '未支付', value: 'UNPAID' },
  { label: '已支付', value: 'PAID' },
  { label: '已取消', value: 'CANCELLED' },
  { label: '退款中', value: 'REFUNDING' },
  { label: '已退款', value: 'REFUNDED' },
];

const columns = [
  { colKey: 'id', title: 'ID', width: 80 },
  { colKey: 'visitId', title: '就诊' },
  { colKey: 'amount', title: '金额' },
  { colKey: 'status', title: '状态' },
  { colKey: 'paymentMethod', title: '支付方式' },
  { colKey: 'op', title: '操作', width: 100 },
];

const load = async () => {
  const res = await api.orders({ page: 1, size: 20 });
  if (res.code === 0) list.value = res.data.records || [];
};

const openCreate = () => {
  if (!canEdit.value) return;
  dialogTitle.value = '新增订单';
  editingId.value = null;
  form.visitId = '';
  form.amount = '';
  form.paymentMethod = 'OFFLINE';
  form.status = 'UNPAID';
  dialogVisible.value = true;
};

const openEdit = (row: any) => {
  if (!canEdit.value) return;
  dialogTitle.value = '编辑订单';
  editingId.value = row.id;
  form.visitId = row.visitId || '';
  form.amount = row.amount || '';
  form.paymentMethod = row.paymentMethod || 'OFFLINE';
  form.status = row.status || 'UNPAID';
  dialogVisible.value = true;
};

const loadVisits = async () => {
  try {
    const res = await api.visits({ page: 1, size: 100 }); // 获取所有就诊记录
    if (res.code === 0) {
      visits.value = res.data?.records || [];
    } else {
      MessagePlugin.error(res.message || '获取就诊记录失败');
    }
  } catch (error) {
    console.error('获取就诊记录失败:', error);
    MessagePlugin.error('获取就诊记录失败');
  }
};

const submit = async () => {
  if (!canEdit.value) return;
  const payload = { ...form };
  const res = editingId.value
    ? await api.updateOrder(editingId.value, payload)
    : await api.createOrder(payload);
  if (res.code === 0) {
    MessagePlugin.success('保存成功');
    dialogVisible.value = false;
    load();
  } else {
    MessagePlugin.error(res.message || '保存失败');
  }
};

onMounted(() => {
  load();
  loadVisits();
});
</script>
