<script lang="ts" setup>
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';
import {
  Alert,
  Avatar,
  Button,
  Card,
  Col,
  Descriptions,
  Empty,
  Form,
  Image,
  Input,
  message,
  Row,
  Select,
  Spin,
  Table,
  Tabs,
  Tag,
  Divider
} from 'ant-design-vue';

import AvatarUpload from '#/components/form/components/avatar.vue';
import DoctorQrCodePreview from '#/components/modal/DoctorQrCodePreview.vue';
import PrescriptionDetail from '#/views/doctor/doctor-reception/components/PrescriptionDetail.vue';
import OrderDetail from '#/views/business/order/product-order/components/detail.vue';
import { openPcWindowsApi, updateDoctor } from '../api';
import {
  getDoctorCardApi,
  getDoctorCardOrdersApi,
  getDoctorCardPatientsApi,
  getDoctorCardPrescriptionsApi,
  updateDoctorCredentialsApi,
  updateDoctorServiceUserApi,
  updateDoctorSignatureByAdminApi,
} from '../api/card';
import { canEditDoctorServiceUser } from '#/views/system/admin/_shared/platform-admin-role';
import { resolveAvatarUrl } from '#/views/system/store-input/utils/inputUser';

const gridApi = ref<any>();
const doctorId = ref(0);
const suId = ref(0);
const hideStoresTab = ref(false);
const loading = ref(false);
const activeTab = ref('overview');
const cardData = ref<any>(null);

const overviewForm = ref({
  avatar: '',
  name: '',
  mobile: '',
  good_at: '',
  intro: '',
});

const serviceUserForm = ref({
  avatar: '',
  mobile: '',
  nickname: '',
});

const userStore = useUserStore();
const canEditProfile = computed(() =>
  canEditDoctorServiceUser(userStore.userInfo),
);

const savingServiceUser = ref(false);

const credentialsForm = ref({
  card_up: '',
  card_down: '',
  sign_type: 1,
  sign_image: '',
  qualification: '',
  practicing: '',
  title: '',
});

const savingOverview = ref(false);
const savingCredentials = ref(false);

const prescriptionLoading = ref(false);
const prescriptionList = ref<any[]>([]);
const prescriptionPage = ref(1);
const prescriptionTotal = ref(0);

const patientLoading = ref(false);
const patientList = ref<any[]>([]);
const patientPage = ref(1);
const patientTotal = ref(0);

const orderLoading = ref(false);
const orderList = ref<any[]>([]);
const orderPage = ref(1);
const orderTotal = ref(0);

const stats = computed(() => cardData.value?.stats_summary ?? {});

function serviceUserStatusText(status?: number) {
  const map: Record<number, string> = {
    [-1]: '已停用',
    0: '待激活',
    1: '待审核',
    2: '已认证',
    3: '已拒绝',
  };
  return map[Number(status)] ?? '未知';
}

function serviceUserRoleText(role?: number) {
  const map: Record<number, string> = {
    1: '医生',
    2: '药师',
    3: '导医',
    4: '客服',
  };
  return map[Number(role)] ?? '-';
}

const [QrCodeModal, QrCodeModalApi] = useVbenModal({
  connectedComponent: DoctorQrCodePreview,
});

const [PrescriptionDetailModal, PrescriptionDetailModalApi] = useVbenModal({
  connectedComponent: PrescriptionDetail,
});

const [OrderDetailDrawer, OrderDetailModalApi] = useVbenModal({
  connectedComponent: OrderDetail,
});

/** 获取当前医生标识，列表类接口复用 */
function getCardIdentity() {
  return {
    id: doctorId.value || undefined,
    suId: suId.value || undefined,
  };
}

async function loadCard() {
  if (!doctorId.value && !suId.value) return;
  loading.value = true;
  try {
    const { id, suId: querySuId } = getCardIdentity();
    const res = await getDoctorCardApi(id, querySuId);
    cardData.value = res;
    doctorId.value = res?.doctor_info?.id ?? doctorId.value;
    suId.value = res?.doctor_info?.su_id ?? suId.value;
    overviewForm.value = {
      avatar: res?.doctor_info?.avatar ?? '',
      name: res?.doctor_info?.name ?? '',
      mobile: res?.doctor_info?.mobile ?? '',
      good_at: res?.doctor_info?.good_at ?? '',
      intro: res?.doctor_info?.intro ?? '',
    };
    serviceUserForm.value = {
      avatar: res?.doctor_info?.avatar ?? '',
      mobile: res?.service_user?.mobile ?? '',
      nickname: res?.service_user?.nickname ?? '',
    };
    credentialsForm.value = {
      card_up: res?.identity?.card_up ?? '',
      card_down: res?.identity?.card_down ?? '',
      sign_type: res?.identity?.sign_type ?? 1,
      sign_image: res?.identity?.sign_image ?? '',
      qualification: res?.practicing?.qualification ?? '',
      practicing: res?.practicing?.practicing ?? '',
      title: res?.practicing?.title ?? '',
    };
  } finally {
    loading.value = false;
  }
}

async function saveOverview() {
  if (!canEditProfile.value) return;
  savingOverview.value = true;
  try {
    const res = await updateDoctor({
      id: doctorId.value,
      su_id: suId.value,
      ...overviewForm.value,
    });
    if (res?.sync && !res.sync.admin_found) {
      message.warning('资料已保存，但该医生未开通 PC 后台，管理员头像未同步');
    } else {
      message.success('保存成功');
    }
    await loadCard();
    gridApi.value?.reload?.();
  } finally {
    savingOverview.value = false;
  }
}

async function saveServiceUser() {
  if (!canEditProfile.value || !suId.value) return;
  savingServiceUser.value = true;
  try {
    const res = await updateDoctorServiceUserApi({
      su_id: suId.value,
      mobile: serviceUserForm.value.mobile,
      nickname: serviceUserForm.value.nickname,
      avatar: serviceUserForm.value.avatar,
    });
    if (res?.sync && !res.sync.admin_found) {
      message.warning('账号资料已保存，但该医生未开通 PC 后台，管理员头像未同步');
    } else {
      message.success('微信平台账号保存成功');
    }
    await loadCard();
    gridApi.value?.reload?.();
  } finally {
    savingServiceUser.value = false;
  }
}

async function saveCredentials() {
  if (!canEditProfile.value) return;
  savingCredentials.value = true;
  try {
    await updateDoctorCredentialsApi({
      id: doctorId.value,
      ...credentialsForm.value,
    });
    if (credentialsForm.value.sign_image) {
      await updateDoctorSignatureByAdminApi({
        id: doctorId.value,
        sign_image: credentialsForm.value.sign_image,
      });
    }
    message.success('证书资料保存成功');
    await loadCard();
  } finally {
    savingCredentials.value = false;
  }
}

async function loadPrescriptions(page = 1) {
  prescriptionLoading.value = true;
  try {
    const { id, suId: querySuId } = getCardIdentity();
    const res = await getDoctorCardPrescriptionsApi(id, querySuId, {
      page,
      pageSize: 10,
    });
    prescriptionList.value = res.items ?? [];
    prescriptionPage.value = res.page ?? 1;
    prescriptionTotal.value = res.total ?? 0;
  } finally {
    prescriptionLoading.value = false;
  }
}

async function loadPatients(page = 1) {
  patientLoading.value = true;
  try {
    const { id, suId: querySuId } = getCardIdentity();
    const res = await getDoctorCardPatientsApi(id, querySuId, {
      page,
      pageSize: 10,
    });
    patientList.value = res.items ?? [];
    patientPage.value = res.page ?? 1;
    patientTotal.value = res.total ?? 0;
  } finally {
    patientLoading.value = false;
  }
}

async function loadOrders(page = 1) {
  orderLoading.value = true;
  try {
    const { id, suId: querySuId } = getCardIdentity();
    const res = await getDoctorCardOrdersApi(id, querySuId, {
      page,
      pageSize: 10,
    });
    orderList.value = res.items ?? [];
    orderPage.value = res.page ?? 1;
    orderTotal.value = res.total ?? 0;
  } finally {
    orderLoading.value = false;
  }
}

function onTabChange(key: string) {
  activeTab.value = key;
  if (key === 'prescriptions' && prescriptionList.value.length === 0) {
    loadPrescriptions();
  }
  if (key === 'patients' && patientList.value.length === 0) {
    loadPatients();
  }
  if (key === 'orders' && orderList.value.length === 0) {
    loadOrders();
  }
}

function openPrescriptionDetail(prescriptionId: number) {
  PrescriptionDetailModalApi.setData({ values: prescriptionId });
  PrescriptionDetailModalApi.open();
}

function openOrderDetail(orderId: number) {
  OrderDetailModalApi.setData({ id: orderId });
  OrderDetailModalApi.open();
}

function openStoreQr(storeId: number) {
  QrCodeModalApi.setData({
    values: { doctor_id: suId.value, store_id: storeId },
  });
  QrCodeModalApi.open();
}

function openPcWindows() {
  openPcWindowsApi(doctorId.value).then(() => {
    message.success('开通成功');
    loadCard();
    gridApi.value?.reload?.();
  });
}

const prescriptionColumns = [
  { title: '处方号', dataIndex: 'prescription_no', key: 'prescription_no' },
  { title: '患者', dataIndex: ['user_patient', 'name'], key: 'patient' },
  { title: '诊所', dataIndex: ['store', 'name'], key: 'store' },
  { title: '金额(元)', dataIndex: 'total_pay_price', key: 'amount' },
  { title: '开具时间', dataIndex: 'created_at', key: 'created_at' },
  { title: '操作', key: 'action', width: 80 },
];

const patientColumns = [
  { title: '姓名', dataIndex: 'name', key: 'name' },
  { title: '性别', dataIndex: 'sex', key: 'sex' },
  { title: '手机号', dataIndex: 'mobile', key: 'mobile' },
];

const orderColumns = [
  { title: '订单ID', dataIndex: 'id', key: 'id' },
  { title: '处方号', dataIndex: ['prescription', 'prescription_no'], key: 'pno' },
  { title: '患者', dataIndex: ['user_patient', 'name'], key: 'patient' },
  { title: '金额(元)', dataIndex: 'total_price', key: 'total_price' },
  { title: '支付状态', dataIndex: 'is_pay', key: 'is_pay' },
  { title: '操作', key: 'action', width: 80 },
];

const [Modal, modalApi] = useVbenModal({
  closeOnClickModal: false,
  fullscreenButton: true,
  draggable: true,
  class: 'w-[900px] xl:w-[1100px]',
  footer: false,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<Record<string, any>>();
      gridApi.value = data?.gridApi;
      doctorId.value = data?.id ?? data?.values?.id ?? 0;
      suId.value = data?.su_id ?? data?.values?.su_id ?? 0;
      hideStoresTab.value = !!data?.hideStoresTab;
      activeTab.value = 'overview';
      prescriptionList.value = [];
      patientList.value = [];
      orderList.value = [];
      loadCard();
    }
  },
});
</script>

<template>
  <Modal :title="cardData?.doctor_info?.name ? `医生档案 · ${cardData.doctor_info.name}` : '医生档案'">
    <Spin :spinning="loading">

      <!-- 顶部核心数据区：图文结合 + 暗色自适应 -->
      <div v-if="cardData" class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6 px-1">
        <!-- 接诊数 -->
        <div class="relative overflow-hidden flex flex-col p-5 bg-blue-50 dark:bg-blue-900/20 border border-blue-100 dark:border-blue-800/50 rounded-xl shadow-sm group hover:shadow-md transition-all">
          <div class="flex justify-between items-start relative z-10">
            <div>
              <span class="text-blue-600/80 dark:text-blue-300/80 text-sm font-semibold">累计接诊</span>
              <div class="text-2xl font-bold text-blue-900 dark:text-blue-100 mt-2">
                {{ stats.reception_count ?? 0 }} <span class="text-xs font-normal text-blue-700/60 dark:text-blue-300/60">次</span>
              </div>
            </div>
            <div class="p-2 bg-blue-100 dark:bg-blue-800/50 rounded-lg text-blue-500 dark:text-blue-300">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" /></svg>
            </div>
          </div>
        </div>

        <!-- 拒诊数 -->
        <div class="relative overflow-hidden flex flex-col p-5 bg-rose-50 dark:bg-rose-900/20 border border-rose-100 dark:border-rose-800/50 rounded-xl shadow-sm group hover:shadow-md transition-all">
          <div class="flex justify-between items-start relative z-10">
            <div>
              <span class="text-rose-600/80 dark:text-rose-300/80 text-sm font-semibold">拒诊数量</span>
              <div class="text-2xl font-bold text-rose-900 dark:text-rose-100 mt-2">
                {{ stats.refused_count ?? 0 }} <span class="text-xs font-normal text-rose-700/60 dark:text-rose-300/60">次</span>
              </div>
            </div>
            <div class="p-2 bg-rose-100 dark:bg-rose-800/50 rounded-lg text-rose-500 dark:text-rose-300">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" /></svg>
            </div>
          </div>
        </div>

        <!-- 处方数 -->
        <div class="relative overflow-hidden flex flex-col p-5 bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-100 dark:border-emerald-800/50 rounded-xl shadow-sm group hover:shadow-md transition-all">
          <div class="flex justify-between items-start relative z-10">
            <div>
              <span class="text-emerald-600/80 dark:text-emerald-300/80 text-sm font-semibold">处方总数</span>
              <div class="text-2xl font-bold text-emerald-900 dark:text-emerald-100 mt-2">
                {{ stats.prescription_count ?? 0 }} <span class="text-xs font-normal text-emerald-700/60 dark:text-emerald-300/60">张</span>
              </div>
            </div>
            <div class="p-2 bg-emerald-100 dark:bg-emerald-800/50 rounded-lg text-emerald-500 dark:text-emerald-300">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>
            </div>
          </div>
        </div>

        <!-- 处方金额 -->
        <div class="relative overflow-hidden flex flex-col p-5 bg-purple-50 dark:bg-purple-900/20 border border-purple-100 dark:border-purple-800/50 rounded-xl shadow-sm group hover:shadow-md transition-all">
          <div class="flex justify-between items-start relative z-10">
            <div>
              <span class="text-purple-600/80 dark:text-purple-300/80 text-sm font-semibold">处方总额</span>
              <div class="text-2xl font-bold text-purple-900 dark:text-purple-100 mt-2">
                <span class="text-lg">¥</span> {{ Number(stats.prescription_amount ?? 0).toFixed(2) }}
              </div>
            </div>
            <div class="p-2 bg-purple-100 dark:bg-purple-800/50 rounded-lg text-purple-500 dark:text-purple-300">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
            </div>
          </div>
        </div>
      </div>

      <Divider class="!my-4 dark:border-slate-700/60" />

      <!-- 主体内容区 -->
      <Tabs
        :active-key="activeTab"
        @change="onTabChange"
        tab-position="left"
        class="min-h-[480px] custom-vertical-tabs"
      >
        <Tabs.TabPane key="overview" tab="概览信息">
          <div class="pl-6">
            <div class="flex justify-between items-end mb-4">
              <h3 class="text-base font-semibold text-gray-800 dark:text-slate-200">基本资料</h3>
            </div>

            <div class="bg-gray-50 dark:bg-[#1f242e] p-5 rounded-lg border border-gray-100 dark:border-slate-700 mb-6 transition-colors">
              <Row :gutter="32">
                <Col :span="6" class="flex flex-col items-center border-r border-gray-200 dark:border-slate-700">
                  <div class="text-gray-500 dark:text-slate-400 mb-3 text-sm">医生头像</div>
                  <AvatarUpload
                    v-if="canEditProfile"
                    v-model:value="overviewForm.avatar"
                    class="shadow-sm rounded-full overflow-hidden"
                  />
                  <Avatar v-else :src="resolveAvatarUrl(overviewForm.avatar)" :size="80" />
                </Col>
                <Col :span="18">
                  <Form layout="vertical" class="grid grid-cols-2 gap-x-6">
                    <Form.Item label="医生姓名" class="mb-4">
                      <Input v-model:value="overviewForm.name" :disabled="!canEditProfile" placeholder="请输入姓名" size="large" />
                    </Form.Item>
                    <Form.Item label="手机号码" class="mb-4">
                      <Input v-model:value="overviewForm.mobile" :disabled="!canEditProfile" placeholder="请输入手机号码" size="large" />
                    </Form.Item>
                    <Form.Item label="专业擅长" class="col-span-2 mb-4">
                      <Input.TextArea v-model:value="overviewForm.good_at" :disabled="!canEditProfile" :rows="2" placeholder="填写医生擅长的领域..." />
                    </Form.Item>
                    <Form.Item label="个人简介" class="col-span-2 mb-4">
                      <Input.TextArea v-model:value="overviewForm.intro" :disabled="!canEditProfile" :rows="3" placeholder="填写医生简介..." />
                    </Form.Item>
                    <div v-if="canEditProfile" class="col-span-2 text-right mt-2">
                      <Button type="primary" size="large" :loading="savingOverview" @click="saveOverview">
                        保存基本信息
                      </Button>
                    </div>
                  </Form>
                </Col>
              </Row>
            </div>

            <h3 class="text-base font-semibold text-gray-800 dark:text-slate-200 mb-4 mt-8">
              微信平台账号 (service_user)
            </h3>
            <div class="bg-gray-50 dark:bg-[#1f242e] p-5 rounded-lg border border-gray-100 dark:border-slate-700 mb-6 transition-colors">
              <Row :gutter="32">
                <Col :span="6" class="flex flex-col items-center border-r border-gray-200 dark:border-slate-700">
                  <div class="text-gray-500 dark:text-slate-400 mb-3 text-sm">账号头像</div>
                  <AvatarUpload
                    v-if="canEditProfile"
                    v-model:value="serviceUserForm.avatar"
                    class="shadow-sm rounded-full overflow-hidden"
                  />
                  <Avatar v-else :src="resolveAvatarUrl(serviceUserForm.avatar)" :size="80" />
                </Col>
                <Col :span="18">
                  <Form v-if="canEditProfile" layout="vertical" class="grid grid-cols-2 gap-x-6">
                    <Form.Item label="登录手机号" class="mb-4">
                      <Input v-model:value="serviceUserForm.mobile" placeholder="service_user.mobile" size="large" />
                    </Form.Item>
                    <Form.Item label="昵称" class="mb-4">
                      <Input v-model:value="serviceUserForm.nickname" placeholder="service_user.nickname" size="large" />
                    </Form.Item>
                    <Form.Item label="账号状态" class="mb-4">
                      <Tag :color="cardData?.service_user?.status === 2 ? 'success' : 'default'">
                        {{ serviceUserStatusText(cardData?.service_user?.status) }}
                      </Tag>
                    </Form.Item>
                    <Form.Item label="账号角色" class="mb-4">
                      <span>{{ serviceUserRoleText(cardData?.service_user?.role) }}</span>
                    </Form.Item>
                    <div class="col-span-2 text-right mt-2">
                      <Button type="primary" size="large" :loading="savingServiceUser" @click="saveServiceUser">
                        保存微信平台账号
                      </Button>
                    </div>
                  </Form>
                  <Descriptions v-else bordered :column="2" size="middle">
                    <Descriptions.Item label="登录手机号">{{ serviceUserForm.mobile || '-' }}</Descriptions.Item>
                    <Descriptions.Item label="昵称">{{ serviceUserForm.nickname || '-' }}</Descriptions.Item>
                    <Descriptions.Item label="账号状态">
                      <Tag :color="cardData?.service_user?.status === 2 ? 'success' : 'default'">
                        {{ serviceUserStatusText(cardData?.service_user?.status) }}
                      </Tag>
                    </Descriptions.Item>
                    <Descriptions.Item label="账号角色">
                      {{ serviceUserRoleText(cardData?.service_user?.role) }}
                    </Descriptions.Item>
                    <Descriptions.Item label="su_id">{{ cardData?.service_user?.id ?? suId }}</Descriptions.Item>
                  </Descriptions>
                </Col>
              </Row>
            </div>

            <h3 class="text-base font-semibold text-gray-800 dark:text-slate-200 mb-4 mt-8">系统档案 (只读)</h3>
            <Descriptions bordered :column="3" size="middle" class="bg-white dark:bg-[#18181c] shadow-sm rounded-lg overflow-hidden border-gray-200 dark:border-slate-700">
              <Descriptions.Item label="医生ID">{{ cardData?.doctor_info?.id }}</Descriptions.Item>
              <Descriptions.Item label="微信平台ID">{{ cardData?.doctor_info?.su_id }}</Descriptions.Item>
              <Descriptions.Item label="审核状态">
                <Tag v-if="cardData?.service_user?.status === 2" color="success" class="!mr-0">已认证通过</Tag>
                <Tag v-else color="default" class="!mr-0">{{ cardData?.service_user?.status || '未审核' }}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="所属科室">{{ cardData?.doctor_info?.depart?.name ?? '-' }}</Descriptions.Item>
              <Descriptions.Item label="执业职称">{{ cardData?.doctor_info?.title?.name ?? '-' }}</Descriptions.Item>
              <Descriptions.Item label="诊疗科目">{{ cardData?.doctor_info?.subjects?.name ?? '-' }}</Descriptions.Item>
            </Descriptions>
          </div>
        </Tabs.TabPane>

        <Tabs.TabPane key="credentials" tab="证书与签名">
          <div class="pl-6">
            <div class="flex justify-between items-center mb-5">
              <div>
                <h3 class="text-base font-semibold text-gray-800 dark:text-slate-200">资质证书管理</h3>
                <p class="text-sm text-gray-500 dark:text-slate-400 mt-1">请上传清晰、无遮挡的证件扫描件或照片</p>
              </div>
              <Button v-if="canEditProfile" type="primary" :loading="savingCredentials" @click="saveCredentials">
                保存全部资质
              </Button>
            </div>

            <Form layout="vertical">
              <!-- 通过比例控制让上传区域更像“证件” -->
              <div class="grid grid-cols-2 lg:grid-cols-3 gap-6 bg-gray-50 dark:bg-[#1f242e] p-5 rounded-lg border border-gray-100 dark:border-slate-700">
                <Form.Item label="身份证 (正面)" class="mb-0 bg-white dark:bg-[#18181c] p-4 rounded-md shadow-sm border border-gray-100 dark:border-slate-700/60 text-center">
                  <div class="aspect-[1.6/1] w-full flex items-center justify-center">
                    <AvatarUpload v-model:value="credentialsForm.card_up" />
                  </div>
                </Form.Item>
                <Form.Item label="身份证 (反面)" class="mb-0 bg-white dark:bg-[#18181c] p-4 rounded-md shadow-sm border border-gray-100 dark:border-slate-700/60 text-center">
                  <div class="aspect-[1.6/1] w-full flex items-center justify-center">
                    <AvatarUpload v-model:value="credentialsForm.card_down" />
                  </div>
                </Form.Item>
                <Form.Item label="执业资格证书" class="mb-0 bg-white dark:bg-[#18181c] p-4 rounded-md shadow-sm border border-gray-100 dark:border-slate-700/60 text-center">
                  <div class="aspect-[1.6/1] w-full flex items-center justify-center">
                    <AvatarUpload v-model:value="credentialsForm.qualification" />
                  </div>
                </Form.Item>
                <Form.Item label="执业证书" class="mb-0 bg-white dark:bg-[#18181c] p-4 rounded-md shadow-sm border border-gray-100 dark:border-slate-700/60 text-center">
                  <div class="aspect-[1.6/1] w-full flex items-center justify-center">
                    <AvatarUpload v-model:value="credentialsForm.practicing" />
                  </div>
                </Form.Item>
                <Form.Item label="职称证书" class="mb-0 bg-white dark:bg-[#18181c] p-4 rounded-md shadow-sm border border-gray-100 dark:border-slate-700/60 text-center">
                  <div class="aspect-[1.6/1] w-full flex items-center justify-center">
                    <AvatarUpload v-model:value="credentialsForm.title" />
                  </div>
                </Form.Item>
                <div class="flex flex-col gap-4">
                  <Form.Item label="医生签名图 (透明底)" class="mb-0 bg-white dark:bg-[#18181c] p-4 rounded-md shadow-sm border border-gray-100 dark:border-slate-700/60 flex-1 text-center">
                    <AvatarUpload v-model:value="credentialsForm.sign_image" />
                  </Form.Item>
                  <Form.Item label="签名验证类型" class="mb-0 bg-white dark:bg-[#18181c] p-3 rounded-md shadow-sm border border-gray-100 dark:border-slate-700/60">
                    <Select v-model:value="credentialsForm.sign_type" size="large" :options="[
                      { label: '电子认证签名', value: 1 },
                      { label: '手写扫描签名', value: 2 },
                    ]" />
                  </Form.Item>
                </div>
              </div>
            </Form>
          </div>
        </Tabs.TabPane>

        <Tabs.TabPane v-if="!hideStoresTab" key="stores" tab="关联诊所">
          <div class="pl-6 h-full">
            <Empty v-if="!cardData?.stores?.length" description="暂无绑定的诊所记录" class="mt-20" />
            <div v-else class="grid grid-cols-2 gap-5">
              <Card
                v-for="item in cardData.stores"
                :key="item.store_id"
                :title="item.store?.name ?? `诊所编号 #${item.store_id}`"
                class="shadow-sm border-gray-200 dark:border-slate-700 hover:shadow-md transition-shadow dark:bg-[#18181c]"
                :head-style="{ borderBottom: '1px solid var(--ant-color-split)' }"
              >
                <div class="text-sm text-gray-600 dark:text-slate-400 space-y-3 mb-4">
                  <p class="flex items-start">
                    <svg class="w-4 h-4 mr-2 mt-0.5 text-gray-400 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" /><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" /></svg>
                    <span>{{ item.store?.province }}{{ item.store?.city }}{{ item.store?.position }}</span>
                  </p>
                  <p class="flex items-center">
                    <svg class="w-4 h-4 mr-2 text-gray-400 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" /></svg>
                    <span>{{ item.store?.contact }} ({{ item.store?.mobile }})</span>
                  </p>
                </div>

                <div class="flex items-center justify-between border-t border-gray-100 dark:border-slate-700/60 pt-4 mt-4">
                  <div v-if="item.qr_code" class="border dark:border-slate-600 p-1 rounded bg-white">
                    <Image :src="item.qr_code" :width="56" :height="56" class="rounded-sm" />
                  </div>
                  <span v-else class="text-gray-400 text-xs">暂无专属海报</span>
                  <Button type="primary" ghost size="small" @click="openStoreQr(item.store_id)">查看分享海报</Button>
                </div>
              </Card>
            </div>
          </div>
        </Tabs.TabPane>

        <Tabs.TabPane key="admin" tab="后台账号">
          <div class="pl-6 max-w-2xl">
            <template v-if="cardData?.admin">
              <div class="bg-white dark:bg-[#1f242e] border border-gray-200 dark:border-slate-700 rounded-lg p-6 flex items-center gap-6 shadow-sm">
                <Avatar :src="cardData.admin.avatar" :size="84" class="border-2 border-blue-50 dark:border-blue-900 shadow-sm" />
                <div class="flex-1">
                  <h3 class="text-xl font-bold text-gray-800 dark:text-slate-100 mb-1">{{ cardData.admin.nick_name }}</h3>
                  <p class="text-gray-500 dark:text-slate-400 mb-4 flex items-center gap-2">
                    <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z" /></svg>
                    {{ cardData.admin.phone }}
                  </p>
                  <Tag color="processing">PC 端权限已开通</Tag>
                </div>
              </div>
            </template>
            <template v-else>
              <div class="bg-orange-50 dark:bg-orange-950/30 border border-orange-100 dark:border-orange-900/50 rounded-lg p-8 text-center mt-10">
                <div class="text-orange-400 text-5xl mb-4">🖥️</div>
                <h3 class="text-lg font-semibold text-gray-800 dark:text-slate-200 mb-2">未开通 PC 端管理权限</h3>
                <p class="text-gray-500 dark:text-slate-400 mb-6 text-sm">开通后，医生可使用电脑端登录系统进行高级管理操作，如查看完整报表等。</p>
                <Button type="primary" size="large" @click="openPcWindows">立即开通后台账号</Button>
              </div>
            </template>
          </div>
        </Tabs.TabPane>

        <Tabs.TabPane key="service" tab="服务配置">
          <div class="pl-6">
            <h3 class="text-base font-semibold text-gray-800 dark:text-slate-200 mb-4">出诊与挂号服务</h3>
            <Descriptions v-if="cardData?.service" bordered :column="2" class="bg-white dark:bg-[#18181c] shadow-sm rounded-lg overflow-hidden border-gray-200 dark:border-slate-700">
              <Descriptions.Item label="当前挂号状态">
                <Tag :color="cardData.service.register_status === 1 ? 'success' : 'default'">
                  {{ cardData.service.status_text }}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="挂号服务费(元)">
                <span class="text-lg font-bold text-orange-500 dark:text-orange-400">¥ {{ cardData.service.register_price }}</span>
              </Descriptions.Item>
              <Descriptions.Item label="每日号源上限">
                <span class="font-medium text-gray-800 dark:text-slate-300">{{ cardData.service.register_num }} 个</span>
              </Descriptions.Item>
            </Descriptions>
            <Empty v-else description="暂未配置任何服务项" class="mt-20" />
          </div>
        </Tabs.TabPane>

        <Tabs.TabPane key="prescriptions" tab="处方记录">
          <div class="pl-6 h-full">
            <Table
              :columns="prescriptionColumns"
              :data-source="prescriptionList"
              :loading="prescriptionLoading"
              :pagination="{
                current: prescriptionPage,
                total: prescriptionTotal,
                pageSize: 10,
                onChange: loadPrescriptions,
                showTotal: (total) => `共 ${total} 条数据`
              }"
              row-key="id"
              size="middle"
              class="border border-gray-100 dark:border-slate-700 rounded-lg shadow-sm"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'prescription_no'">
                  <Button type="link" size="small" @click="openPrescriptionDetail(record.id)">
                    {{ record.prescription_no }}
                  </Button>
                </template>
                <template v-if="column.key === 'action'">
                  <Button type="link" size="small" @click="openPrescriptionDetail(record.id)">查看</Button>
                </template>
              </template>
            </Table>
          </div>
        </Tabs.TabPane>

        <Tabs.TabPane key="patients" tab="患者列表">
          <div class="pl-6 h-full">
            <Table
              :columns="patientColumns"
              :data-source="patientList"
              :loading="patientLoading"
              :pagination="{
                current: patientPage,
                total: patientTotal,
                pageSize: 10,
                onChange: loadPatients,
                showTotal: (total) => `共 ${total} 名患者`
              }"
              row-key="id"
              size="middle"
              class="border border-gray-100 dark:border-slate-700 rounded-lg shadow-sm"
            />
          </div>
        </Tabs.TabPane>

        <Tabs.TabPane key="orders" tab="相关订单">
          <div class="pl-6 h-full">
            <Table
              :columns="orderColumns"
              :data-source="orderList"
              :loading="orderLoading"
              :pagination="{
                current: orderPage,
                total: orderTotal,
                pageSize: 10,
                onChange: loadOrders,
                showTotal: (total) => `共 ${total} 笔订单`
              }"
              row-key="id"
              size="middle"
              class="border border-gray-100 dark:border-slate-700 rounded-lg shadow-sm"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'id'">
                  <Button type="link" size="small" @click="openOrderDetail(record.id)">
                    {{ record.id }}
                  </Button>
                </template>
                <template v-if="column.key === 'is_pay'">
                  <Tag :color="record.is_pay ? 'success' : 'default'">
                    {{ record.is_pay ? '已支付' : '待支付' }}
                  </Tag>
                </template>
                <template v-if="column.key === 'total_price'">
                  <span class="font-medium text-gray-700 dark:text-slate-300">¥ {{ record.total_price }}</span>
                </template>
                <template v-if="column.key === 'action'">
                  <Button type="link" size="small" @click="openOrderDetail(record.id)">查看</Button>
                </template>
              </template>
            </Table>
          </div>
        </Tabs.TabPane>
      </Tabs>
    </Spin>
  </Modal>
  <QrCodeModal />
  <PrescriptionDetailModal />
  <OrderDetailDrawer />
</template>

<style scoped>
/* 使用 CSS 变量自适应暗黑模式的 Tabs 高亮，替代硬编码颜色 */
:deep(.custom-vertical-tabs .ant-tabs-nav) {
  width: 140px;
}
:deep(.custom-vertical-tabs .ant-tabs-tab) {
  padding: 12px 16px;
  margin-bottom: 4px;
  border-radius: 6px;
  transition: all 0.3s;
}
:deep(.custom-vertical-tabs .ant-tabs-tab-active) {
  background-color: var(--ant-primary-color-active-deprecated-f-12, rgba(22, 119, 255, 0.08));
}
</style>
