<script lang="ts" setup>
/**
 * 药师工作台 - 审方列表
 * 顶部统一搜索 + 列表/卡片切换（localStorage）+ 多列布局
 */
import type { VxeGridListeners } from '#/adapter/vxe-table';

import { computed, ref, watch } from 'vue';

import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';

import { Segmented, Tabs, Tag, message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';
import {
  VisitTypeTag,
  WxUserPatientCell,
  WxUserPatientDrawer,
} from '#/components/wx-user-patient';
import PrescriptionDetail from '#/views/doctor/doctor-reception/components/PrescriptionDetail.vue';
import DoctorCardModal from '#/views/doctor/doctor/components/DoctorCardModal.vue';

import { getPrescriptionListApi, passApi } from './api';
import AuditPrescriptionCardList from './components/AuditPrescriptionCardList.vue';
import DoctorAvatarCell from './components/DoctorAvatarCell.vue';
import MedicineTypeTag from './components/MedicineTypeTag.vue';
import PrescriptionSource from './components/source.vue';
import RejectionReason from './components/modal.vue';
import TimeCell from './components/TimeCell.vue';
import { formOptions } from './config/search';
import { gridOptions as baseGridOptions } from './config/table';
import {
  readAuditViewMode,
  writeAuditViewMode,
  type AuditPrescriptionViewMode,
} from './utils/viewModeStorage';

const hasTopTableDropDownActions = ref(false);
const viewMode = ref<AuditPrescriptionViewMode>(readAuditViewMode());
const passingId = ref<number | null>(null);
const cardListRef = ref<InstanceType<typeof AuditPrescriptionCardList> | null>(
  null,
);
/** 列表与卡片共用的搜索条件 */
const searchValues = ref<Record<string, any>>({});
/** 审核状态 Tab：0待审核 / 1已通过 / 2已拒绝 */
const statusTab = ref('0');

const mergedSearchValues = computed(() => ({
  ...searchValues.value,
  status: Number(statusTab.value),
}));

const canAudit = computed(() => Number(statusTab.value) === 0);

watch(viewMode, (mode) => {
  writeAuditViewMode(mode);
});

/**
 * 条件变更后刷新列表视图（卡片靠 formValues watch，避免与父级重复请求）
 * 列表用 reload 回到第 1 页，避免停在旧页码看不到新 status 数据
 */
function reloadListFromPageOne() {
  if (viewMode.value !== 'list') return;
  gridApi.reload();
}

/** 顶部统一搜索表单：卡片模式只改 searchValues，由 CardList 的 formValues watch 拉数 */
const [SearchForm] = useVbenForm({
  ...formOptions,
  handleSubmit: async (values) => {
    searchValues.value = { ...(values || {}) };
    reloadListFromPageOne();
  },
  handleReset: async () => {
    searchValues.value = {};
    reloadListFromPageOne();
  },
});

const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  checkboxAll() {
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    ...baseGridOptions,
    proxyConfig: {
      ajax: {
        /** 始终合并顶部统一搜索条件与状态 Tab */
        query: async ({ page }) => {
          return await getPrescriptionListApi({
            page: page.currentPage,
            pageSize: page.pageSize,
            ...mergedSearchValues.value,
          });
        },
      },
    },
  },
  gridEvents,
});

watch(viewMode, (mode, prev) => {
  if (mode === 'list' && prev === 'card') {
    gridApi.query();
  }
});

/**
 * 切状态 Tab：列表主动 query；卡片只改 statusTab → mergedSearchValues，
 * 由 CardList watch(formValues) 单次 reload，避免 flush:pre 时读到旧 props 再发一次旧 status
 */
watch(statusTab, () => {
  reloadListFromPageOne();
});

function onStatusTabChange(key: string | number) {
  statusTab.value = String(key);
}

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

const [RejectionReasonModal, RejectionReasonModalApi] = useVbenModal({
  connectedComponent: RejectionReason,
});

const [PrescriptionSourceModal, PrescriptionSourceModalApi] = useVbenModal({
  connectedComponent: PrescriptionSource,
});

const [DoctorCardModals, DoctorCardModalApi] = useVbenModal({
  connectedComponent: DoctorCardModal,
});

const [PatientDrawer, PatientDrawerApi] = useVbenDrawer({
  connectedComponent: WxUserPatientDrawer,
});

function refreshCurrentView() {
  if (viewMode.value === 'list') {
    // commitProxy('query') 会保留当前页与搜索条件
    gridApi.query();
  } else {
    // 卡片：保当前页重拉，不回第 1 页
    cardListRef.value?.refreshKeepPage?.();
  }
}

function openPrescriptionDetail(rowOrId: number | Record<string, any>) {
  const id = typeof rowOrId === 'number' ? rowOrId : rowOrId.id;
  PrescriptionDetailModalApi.setData({
    values: id,
    auditMode: true,
    onAudited: refreshCurrentView,
  });
  PrescriptionDetailModalApi.open();
}

function openPrescriptionSourceModal(id: number) {
  PrescriptionSourceModalApi.setData({ id });
  PrescriptionSourceModalApi.open();
}

async function pass(id: number) {
  if (passingId.value) return;
  passingId.value = id;
  try {
    await passApi({ id });
    message.success('通过成功');
    refreshCurrentView();
  } catch (e) {
    console.error(e);
  } finally {
    passingId.value = null;
  }
}

function reject(id: number) {
  RejectionReasonModalApi.setData({
    values: id,
    gridApi,
    onSuccess: refreshCurrentView,
  });
  RejectionReasonModalApi.open();
}

function showDoctorCard(row: Record<string, any>) {
  const doctor = row.doctor_info ?? row.doctorInfo ?? row.doctor;
  if (!doctor?.id && !row.su_id && !doctor?.su_id) {
    message.warning('该处方无关联医生');
    return;
  }
  DoctorCardModalApi.setData({
    id: doctor?.id,
    su_id: row.su_id ?? doctor?.su_id,
    readonly: true,
  });
  DoctorCardModalApi.open();
}

function openPatient(payload: { upId: number; patientName: string }) {
  if (!payload?.upId) {
    message.warning('缺少就诊人信息');
    return;
  }
  PatientDrawerApi.setData({
    upId: payload.upId,
    patientName: payload.patientName,
  });
  PatientDrawerApi.open();
}

function onViewModeChange(mode: string | number) {
  viewMode.value = mode === 'card' ? 'card' : 'list';
}
</script>

<template>
  <Page auto-content-height title="审方">
    <PrescriptionDetailModal />
    <PrescriptionSourceModal />
    <RejectionReasonModal />
    <DoctorCardModals />
    <PatientDrawer />
    <div
      class="mb-3 rounded-lg border border-gray-100 bg-white p-3 dark:border-slate-700 dark:bg-slate-900"
    >
      <SearchForm />
    </div>
    <div class="mb-3">
      <Tabs :active-key="statusTab" @change="onStatusTabChange">
        <Tabs.TabPane key="0" tab="待审核" />
        <Tabs.TabPane key="1" tab="已通过" />
        <Tabs.TabPane key="2" tab="已拒绝" />
      </Tabs>
    </div>
    <div class="mb-3 flex items-center justify-between gap-3">
      <Segmented
        :value="viewMode"
        :options="[
          { label: '列表', value: 'list' },
          { label: '卡片', value: 'card' },
        ]"
        @change="onViewModeChange"
      />
    </div>
    <Grid v-if="viewMode === 'list'">
      <template #toolbar-actions>
        <TableAction :actions="[]" :drop-down-actions="[]" />
      </template>
      <template #prescription_no="{ row }">
        <div class="space-y-1">
          <div class="font-medium leading-tight">
            {{ row.prescription_no || '—' }}
          </div>
          <MedicineTypeTag :prescription-type="row.prescription_type" />
        </div>
      </template>
      <template #store="{ row }">
        <span>{{ row.store?.name || '—' }}</span>
      </template>
      <template #doctor="{ row }">
        <DoctorAvatarCell :row="row" @open="showDoctorCard" />
      </template>
      <template #patient="{ row }">
        <WxUserPatientCell :row="row" @open="openPatient" />
      </template>
      <template #is_online="{ row }">
        <VisitTypeTag :is-online="row.is_online" />
      </template>
      <template #time="{ row }">
        <TimeCell :row="row" />
      </template>
      <template #status="{ row }">
        <Tag v-if="row.status === 0" color="red">待审核</Tag>
        <Tag v-else-if="row.status === 1" color="green">已通过</Tag>
        <Tag v-else-if="row.status === 2" color="red">已拒绝</Tag>
        <Tag v-else color="default">—</Tag>
      </template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '查看处方',
              type: 'link',
              onClick: openPrescriptionDetail.bind(null, row),
            },
            {
              label: '处方溯源',
              type: 'link',
              onClick: openPrescriptionSourceModal.bind(null, row.id),
            },
            ...(canAudit
              ? [
                  {
                    label: '通过审核',
                    type: 'link' as const,
                    loading: passingId === row.id,
                    onClick: pass.bind(null, row.id),
                  },
                  {
                    label: '拒绝审核',
                    type: 'link' as const,
                    onClick: reject.bind(null, row.id),
                  },
                ]
              : []),
          ]"
          :drop-down-actions="[]"
        />
      </template>
    </Grid>
    <div v-else class="audit-card-wrap">
      <AuditPrescriptionCardList
        ref="cardListRef"
        :form-values="mergedSearchValues"
        :can-audit="canAudit"
        @view-detail="openPrescriptionDetail"
        @view-source="openPrescriptionSourceModal"
        @reject="reject"
        @open-doctor="showDoctorCard"
        @open-patient="openPatient"
      />
    </div>
  </Page>
</template>

<style scoped>
.audit-card-wrap {
  height: calc(100% - 160px);
  min-height: 420px;
}
</style>
