<script lang="ts" setup>
import type { VxeGridListeners } from '#/adapter/vxe-table';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import {
  AnalysisOverview,
  type AnalysisOverviewItem,
  Page,
  useVbenDrawer,
  useVbenModal,
} from '@vben/common-ui';
import { SvgCakeIcon } from '@vben/icons';

import { Button, Image, message, Modal as AntdModal, Popover, Space, Switch, Table, Tag } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';
import {
  getOrderInfo,
  getOrderList,
  getVerifyRecentOrderAmounts,
  saleAmountApi,
  updateFreeShipping,
} from '#/views/business/order/product-order/api';
import { simulatePayApi, accrueSalespersonCommissionApi } from '#/views/business/order/api/order-ops';
import ChinaErpSyncLogDrawer from '#/views/business/order/components/china-erp-sync-log-drawer.vue';
import OrderTraceDrawer from '#/views/business/order/components/order-trace-drawer.vue';
import OrderPricePercentAdjustDrawer from '#/views/business/order/components/OrderPricePercentAdjustDrawer.vue';
import { getOrderPriceAdjustConfig } from '#/api/order/priceAdjust';
import type { QuickDiscountOption } from '#/utils/pricePercentAdjust';
import { normalizeQuickOptions } from '#/utils/pricePercentAdjust';
import PrescriptionDetail from '#/views/doctor/doctor-reception/components/PrescriptionDetail.vue';

import DetailModal from './components/detail.vue';
import FormModalDemo from './components/modal.vue';
import ProductOrderExportModal from './components/ProductOrderExportModal.vue';
import Refund from './components/refund.vue';
import { formOptions } from './config/search';
import { gridOptions } from './config/table';

const router = useRouter();

const hasTopTableDropDownActions = ref(false);

function findRegisterOrderListPath(): null | string {
  const routes = router.getRoutes();
  const hit = routes.find(
    (r) =>
      typeof r.path === 'string' &&
      r.path.length > 0 &&
      !r.redirect &&
      /register/i.test(r.path) &&
      /order/i.test(r.path),
  );
  return hit?.path ?? null;
}

function goRegisterOrder(row: Record<string, any>) {
  const orderNo = row.register_order_no;
  if (!orderNo) {
    message.warning('无关联挂号订单号');
    return;
  }
  const path = findRegisterOrderListPath();
  if (!path) {
    message.warning('未找到挂号订单菜单路由，请从左侧菜单进入挂号订单');
    return;
  }
  void router.push({ path, query: { order_no: String(orderNo) } });
}

function formatRegisterAmount(row: Record<string, any>) {
  if (row.register_id == null || row.register_id === '') {
    return '—';
  }
  const n = Number(row.register_price);
  if (!Number.isFinite(n)) {
    return '—';
  }
  return `¥${n.toFixed(2)}`;
}

const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    // eslint-disable-next-line no-use-before-define
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  checkboxAll() {
    // eslint-disable-next-line no-use-before-define
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});
const initTableAjax = () => {
  gridApi.setGridOptions({
    proxyConfig: {
      ajax: {
        // 请求后端接口方法
        query: async ({ page }, formValues) => {
          saleAmount();
          return await getOrderList({
            page: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
  });
};

initTableAjax();
const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: FormModalDemo,
});
const [Modal, modalApi] = useVbenModal({
  connectedComponent: DetailModal,
});
const [RefundModal, RefundModalApi] = useVbenModal({
  connectedComponent: Refund,
});

const [ExportModal, exportModalApi] = useVbenModal({
  connectedComponent: ProductOrderExportModal,
});

const infoModal = (data = {}) => {
  modalApi.setData({
    // 表单值
    values: data,
    gridApi,
  });
  modalApi.open();
};

const wareSend = (data = {}) => {
  formModalApi.setData({
    // 表单值
    values: {
      order_id: data?.id,
      order_no: data?.order_no,
    },
    gridApi,
  });
  formModalApi.open();
};
const expandAll = () => {
  gridApi.grid?.setAllRowExpand(true);
};

const collapseAll = () => {
  gridApi.grid?.setAllRowExpand(false);
};
const overviewItems = ref<AnalysisOverviewItem[]>([]);
const income = ref(0);
const total = ref(0);
const saleAmount = () => {
  saleAmountApi({
    search_time: gridApi.formApi.latestSubmissionValues.search_time,
  }).then((res) => {
    income.value = res.income;
    total.value = res.total;
    overviewItems.value = [
      {
        icon: SvgCakeIcon,
        title: '销售金额',
        totalTitle: '销售金额',
        totalValue: total.value,
        value: total.value,
      },
      {
        icon: 'fluent-emoji:balance-scale',
        title: '我的收益',
        totalTitle: '我的收益',
        totalValue: income.value,
        value: income.value,
      },
    ];
  });
};

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

const [TraceDrawer, traceDrawerApi] = useVbenDrawer({
  connectedComponent: OrderTraceDrawer,
});

const [ChinaErpSyncDrawer, chinaErpSyncDrawerApi] = useVbenDrawer({
  connectedComponent: ChinaErpSyncLogDrawer,
});

const [PercentAdjustDrawer, percentAdjustDrawerApi] = useVbenDrawer({
  connectedComponent: OrderPricePercentAdjustDrawer,
});

const priceAdjustMeta = ref({
  quickOptions: [] as QuickDiscountOption[],
});

async function loadPriceAdjustMeta() {
  const cfg = await getOrderPriceAdjustConfig();
  priceAdjustMeta.value = {
    quickOptions: normalizeQuickOptions(cfg?.order_discount_quick_options),
  };
}

void loadPriceAdjustMeta();

function canRowPercentAdjust(row: Record<string, any>) {
  return (
    Number(row?.is_pay) !== 1 &&
    Number(row?.store?.enable_order_price_percent_adjust) === 1
  );
}

async function openOrderPercentAdjust(row: Record<string, any>) {
  if (!canRowPercentAdjust(row)) return;
  let discount = Number(row.price_discount ?? 100);
  try {
    const detail = await getOrderInfo(row.id);
    discount = Number(detail?.price_discount ?? discount);
  } catch {
    // 列表字段缺失时沿用行内值
  }
  percentAdjustDrawerApi.setData({
    stage: 'post_order',
    priceDiscount: discount,
    price_discount: discount,
    productOrderId: row.id,
    quickOptions: normalizeQuickOptions(priceAdjustMeta.value.quickOptions),
    onSuccess: () => {
      gridApi.reload();
    },
  });
  percentAdjustDrawerApi.open();
}

function openChinaErpSyncLog(row: Record<string, any>) {
  chinaErpSyncDrawerApi.setData({
    order_id: row.id,
    order_no: row.order_no,
    is_sync_erp: row.is_sync_erp,
  });
  chinaErpSyncDrawerApi.open();
}

function openOrderTrace(row: Record<string, any>) {
  traceDrawerApi.setData({
    scene: 'product',
    order_id: row.id,
    order_no: row.order_no,
  });
  traceDrawerApi.open();
}

function handleSimulatePay(row: Record<string, any>) {
  AntdModal.confirm({
    title: '模拟支付',
    content: `确认为订单 ${row.order_no} 模拟易票联支付回调？`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      await simulatePayApi({ order_type: 'product', order_id: row.id });
      message.success('模拟支付成功');
      await gridApi.query();
    },
  });
}

const accruingOrderIds = ref<number[]>([]);

async function handleAccrueSalesperson(row: Record<string, any>) {
  if (accruingOrderIds.value.includes(row.id)) {
    return;
  }
  accruingOrderIds.value.push(row.id);
  try {
    await accrueSalespersonCommissionApi({ order_id: row.id });
    message.success('分成成功');
    await gridApi.query();
  } catch (error: any) {
    message.error(error?.message || '分成失败');
  } finally {
    accruingOrderIds.value = accruingOrderIds.value.filter((id) => id !== row.id);
  }
}

function formatExpressAddress(row: Record<string, any>) {
  if (Number(row.delivery_method) === 1) {
    return row.store?.position || row.store?.name || '到店自提';
  }
  const region = row.address?.region || row.express_region || '';
  const detail = row.address?.detail_address || row.express_address || '';
  return [region, detail].filter(Boolean).join(' ') || '—';
}

function salespersonStatusColor(text: string) {
  if (text === '已分成') return 'success';
  if (text === '未分成') return 'warning';
  if (text === '未支付') return 'default';
  return 'default';
}

function formatCommissionRecordDetail(record: Record<string, any>) {
  const path = record.commission_path_text || '—';
  const rule = record.commission_rule_text || '—';
  if (record.commission_mode_text === '比例分成') {
    return `${path} · ${rule}`;
  }
  return `${path} · ${record.commission_mode_text || '固定单价'} · ${rule}`;
}

const openPrescriptionDetail = (values) => {
  // 打开西药处方模态框逻辑
  PrescriptionDetailModalApi.setData({
    values,
  });
  PrescriptionDetailModalApi.open();
};

/**
 * 打开导出弹窗
 */
const openExportModal = () => {
  exportModalApi.open();
};

const openRefundModal = (id) => {
  RefundModalApi.setData({
    values: {
      order_id: id,
    },
    gridApi,
  });
  RefundModalApi.open();
};

const toggleFreeShipping = async (row: any, checked: boolean) => {
  try {
    const res = await updateFreeShipping({ id: row.id, is_free_shipping: checked ? 1 : 0 });
    row.is_free_shipping = res.is_free_shipping;
    row.trans_expenses = res.trans_expenses;
    row.total_pay_price = res.total_pay_price;
    message.success('更新成功');
  } catch (error: any) {
    message.error(error.message || '更新失败');
  }
};

const verifyOpen = ref(false);
const verifyLoading = ref(false);
const verifyRows = ref<any[]>([]);
const verifyMeta = ref({ minutes: 10, count: 0, since: 0 });
const verifyMismatchOnly = ref(false);

const verifyColumns = [
  { title: '订单ID', dataIndex: 'order_id', key: 'order_id', width: 90 },
  { title: '订单号', dataIndex: 'order_no', key: 'order_no', width: 200, ellipsis: true },
  { title: '药品价(表)', dataIndex: 'items_price', key: 'items_price', width: 100 },
  { title: '药品价(算)', dataIndex: 'expected_items_price', key: 'exp_items', width: 100 },
  { title: '药品', key: 'items_match', width: 80 },
  { title: '应付(表)', dataIndex: 'total_pay_price', key: 'total_pay', width: 100 },
  { title: '应付(算)', dataIndex: 'expected_total_pay_price', key: 'exp_total', width: 100 },
  { title: '应付', key: 'total_match', width: 80 },
  { title: '全OK', key: 'ok', width: 70 },
  { title: '药品差', dataIndex: 'items_diff', key: 'items_diff', width: 80 },
  { title: '应付差', dataIndex: 'total_diff', key: 'total_diff', width: 80 },
];

const fetchOrderAmountVerify = async () => {
  verifyLoading.value = true;
  try {
    const res = await getVerifyRecentOrderAmounts({
      minutes: 10,
      mismatch_only: verifyMismatchOnly.value ? 1 : 0,
    });
    verifyMeta.value = {
      minutes: res.minutes,
      count: res.count,
      since: res.since,
    };
    verifyRows.value = res.orders ?? [];
    verifyOpen.value = true;
  } finally {
    verifyLoading.value = false;
  }
};

const openOrderAmountVerify = () => {
  verifyMismatchOnly.value = false;
  fetchOrderAmountVerify();
};
</script>

<template>
  <Page auto-content-height title="订单管理">
    <FormModal />
    <Modal />
    <AntdModal
      v-model:open="verifyOpen"
      title="近10分钟订单金额校验"
      width="min(1100px, 96vw)"
      :footer="null"
      destroy-on-close
    >
      <Space direction="vertical" style="width: 100%; margin-bottom: 12px">
        <div>
          与明细重算口径同调价/分账；已检 {{ verifyMeta.count }} 条；since={{ verifyMeta.since }}（Unix）
        </div>
        <Space wrap>
          <span>仅显示不一致</span>
          <Switch v-model:checked="verifyMismatchOnly" @update:checked="fetchOrderAmountVerify" />
          <Button :loading="verifyLoading" type="primary" @click="fetchOrderAmountVerify">
            重新检测
          </Button>
        </Space>
      </Space>
      <Table
        :columns="verifyColumns"
        :data-source="verifyRows"
        :loading="verifyLoading"
        :pagination="false"
        :scroll="{ x: 1200 }"
        size="small"
        row-key="order_id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'items_match'">
            <Tag :color="record.items_match ? 'success' : 'error'">
              {{ record.items_match ? '一致' : '否' }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'total_match'">
            <Tag :color="record.total_match ? 'success' : 'error'">
              {{ record.total_match ? '一致' : '否' }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'ok'">
            <Tag :color="record.ok ? 'success' : 'error'">
              {{ record.ok ? '是' : '否' }}
            </Tag>
          </template>
        </template>
      </Table>
    </AntdModal>
    <RefundModal />
    <ExportModal />
    <PrescriptionDetailModal />
    <TraceDrawer />
    <ChinaErpSyncDrawer @synced="() => gridApi.query()" />
    <AnalysisOverview :items="overviewItems" :my-card="false" />
    <Grid>
      <template #toolbar-buttons>
        <TableAction
          :flex="false"
          :actions="[
            // {
            //   label: '校验近10分钟金额',
            //   type: 'default',
            //   icon: 'ix:search-check',
            //   onClick: openOrderAmountVerify.bind(null),
            // },
            {
              label: '导出',
              type: 'primary',
              icon: 'ix:export-check',
              // auth: ['超级西（中成）药', 'sys:user:save'],
              onClick: openExportModal.bind(null),
            },
            {
              label: '展开全部',
              type: 'primary',
              // auth: ['超级菜单', 'sys:user:save'],
              onClick: expandAll.bind(null),
            },
            {
              label: '收起全部',
              type: 'primary',
              // auth: ['超级菜单', 'sys:user:save'],
              onClick: collapseAll.bind(null),
            },
          ]"
          :drop-down-actions="[]"
        >
          <template #more>
            <Button style="margin-left: 16px">
              批量操作
              <Icon icon="ant-design:down-outlined" />
            </Button>
          </template>
        </TableAction>
      </template>
      <template #avatar="{ row }">
        <Image :src="row.user.avatarurl || '/img/user-default-avatar.png'" />
        {{ row.user.nickname }}
        <div>ID：{{ row.user.id }}</div>
      </template>
      <template #order-store="{ row }">
        <div class="leading-snug">
          <div class="mb-1">
            <Tag v-if="row.is_online === 1" color="blue">在线问诊</Tag>
            <Tag v-else-if="row.is_online === 2" color="green">在线复诊（诊所）</Tag>
            <Tag v-else-if="row.is_online === 3" color="green">在线复诊（药店）</Tag>
            <Tag v-else color="default">线下就诊</Tag>
          </div>
          <div class="font-medium">{{ row.order_no }}</div>
          <div class="text-xs text-gray-500">{{ row.store?.name || '—' }}</div>
          <div class="text-xs text-gray-600">下单时间： {{ row.created_at || '—' }}</div>
        </div>
      </template>
      <template #express-info="{ row }">
        <div class="space-y-0.5 text-sm leading-snug">
          <div>
            {{
              row.address?.name ||
              row.express_name ||
              row.patient ||
              row.cancel_remark ||
              '—'
            }}
          </div>
          <div class="text-gray-500">
            {{ row.address?.mobile || row.patient_mobile || '—' }}
          </div>
          <div class="text-xs text-gray-500">{{ formatExpressAddress(row) }}</div>
        </div>
      </template>
      <template #price-info="{ row }">
        <div class="space-y-0.5 text-sm leading-snug">
          <div>
            药品：
            <Button
              v-if="canRowPercentAdjust(row)"
              class="!h-auto !px-0 !py-0"
              type="link"
              @click="openOrderPercentAdjust(row)"
            >
              ¥{{ row.items_price ?? '0.00' }}
            </Button>
            <template v-else>¥{{ row.items_price ?? '0.00' }}</template>
          </div>
          <div>
            支付：
            <Button
              v-if="canRowPercentAdjust(row)"
              class="!h-auto !px-0 !py-0"
              type="link"
              @click="openOrderPercentAdjust(row)"
            >
              ¥{{ row.total_pay_price ?? '0.00' }}
            </Button>
            <template v-else>¥{{ row.total_pay_price ?? '0.00' }}</template>
          </div>
          <div>
            挂号：
            <Button
              v-if="row.register_order_no"
              class="!h-auto !px-0 !py-0"
              type="link"
              @click="goRegisterOrder(row)"
            >
              {{ formatRegisterAmount(row) }}
            </Button>
            <span v-else>{{ formatRegisterAmount(row) }}</span>
          </div>
        </div>
      </template>
      <template #salesperson="{ row }">
        <div v-if="row.salesperson?.id" class="space-y-1 text-sm leading-snug">
<!--          <Tag :color="salespersonStatusColor(row.salesperson.commission_status_text)">-->
<!--            {{ row.salesperson.commission_status_text }}-->
<!--          </Tag>-->
<!--          <div v-if="row.is_pay === 1" class="text-orange-600">-->
<!--            分成：¥{{ row.salesperson.commission_amount || '0.00' }}-->
<!--          </div>-->
          <Popover trigger="click" placement="topLeft">
            <template #content>
              <div class="max-w-xs space-y-2 text-sm">
                <div
                  v-if="!(row.salesperson.commission_records?.length > 0)"
                  class="text-gray-500"
                >
                  暂无分成明细
                </div>
                <div
                  v-for="(record, idx) in row.salesperson.commission_records || []"
                  :key="idx"
                  class="border-b border-gray-100 pb-2 last:border-0 last:pb-0"
                >
                  <div class="font-medium">{{ record.drug_name || '—' }}</div>
                  <div class="text-gray-500">
                    {{ formatCommissionRecordDetail(record) }}
                  </div>
                  <div class="text-orange-600">¥{{ record.commission_amount }}</div>
                </div>
              </div>
            </template>
            <div class="flex cursor-pointer items-center gap-2 hover:text-blue-600">
              <Image
                :src="row.salesperson.avatar || '/img/user-default-avatar.png'"
                :width="28"
                :height="28"
                class="rounded-full object-cover"
              />
              <span>{{ row.salesperson.nick_name || '—' }}({{row.salesperson.commission_status_text}})</span>
            </div>
          </Popover>
          <Button
            v-if="
              row.is_pay === 1 &&
              row.salesperson_id > 0 &&
              !row.salesperson.has_commission
            "
            class="!h-auto !px-0 !py-0"
            type="link"
            size="small"
            :loading="accruingOrderIds.includes(row.id)"
            @click="handleAccrueSalesperson(row)"
          >
            立即分成
          </Button>
        </div>
        <span v-else class="text-sm text-gray-500">
          {{ row.salesperson?.commission_status_text || '无推广员' }}
        </span>
      </template>
      <template #pay-time="{ row }">
        {{ row?.pay_time || '未支付' }}
      </template>
      <template #is-sync-erp="{ row }">
        <template v-if="row.prescription_type === 1">
          <Tag v-if="row.is_sync_erp === 1" color="green">已同步</Tag>
          <Tag v-else color="red">未同步</Tag>
          <Button
            class="!h-auto !px-0 !py-0"
            size="small"
            type="link"
            @click="openChinaErpSyncLog(row)"
          >
            记录
          </Button>
        </template>
        <template v-else>
          <Tag v-if="row.is_sync_erp === 1" color="green">已同步</Tag>
          <Tag v-else color="red">未同步</Tag>
        </template>
      </template>
      <template #is-free-shipping="{ row }">
        <Switch
          :checked="row.is_free_shipping === 1"
          checked-children="包邮"
          un-checked-children="不包邮"
          @change="(checked) => toggleFreeShipping(row, checked)"
        />
      </template>
      <template #is-online="{ row }">
        <Tag v-if="row.is_online === 1" color="blue">在线问诊</Tag>
        <Tag v-else-if="row.is_online === 2" color="green">在线复诊（诊所）</Tag>
        <Tag v-else-if="row.is_online === 3" color="green">在线复诊（药店）</Tag>
        <Tag v-else color="default">线下就诊</Tag>
      </template>
      <template #delivery-method="{ row }">
        <!-- 判断是否为非处方订单-->
        <div v-if="row.order_type === 2">
          <Tag v-if="row.order_type === 1" color="yellow">处方订单</Tag>
          <Tag v-else-if="row.order_type === 2" color="yellow">
            预约购药订单
          </Tag>
          <Tag v-else-if="row.order_type === 3" color="yellow">
            商城处方订单
          </Tag>
        </div>
        <div v-else>
          <Tag v-if="row.prescription_type === 1" color="orange">
            处方订单【中药】
          </Tag>
          <Tag v-else-if="row.prescription_type === 2" color="blue">
            处方订单【西药】
          </Tag>
          <Tag v-else-if="row.prescription_type === 3" color="purple">
            处方订单【保健食品】
          </Tag>
          <Tag v-else-if="row.prescription_type === 4" color="green">
            处方订单【西药】
          </Tag>
          <Tag v-else-if="row.prescription_type === 5" color="pink">
            处方订单【产品服务包】
          </Tag>
          <Tag v-else-if="row.prescription_type === 6" color="cyan">
            处方订单【非药品】
          </Tag>
          <Tag v-else-if="row.prescription_type === 7" color="geekblue">
            处方订单【医疗器械】
          </Tag>
        </div>
        <div class="mt-3">
          <Tag v-if="row.delivery_method === 1" color="blue">【到店自提】</Tag>
          <Tag v-else-if="row.delivery_method === 0" color="green">
            【上门快递】
          </Tag>
        </div>
        <div class="mt-3">
          <Tag v-if="row.status === 0" color="red">待支付</Tag>
          <Tag v-else-if="row.status === 1" color="orange">待发货</Tag>
          <Tag v-else-if="row.status === 2" color="blue">待收货</Tag>
          <Tag v-else-if="row.status === 3" color="purple">待评价</Tag>
          <Tag v-else-if="row.status === 4" color="green">已退款</Tag>
          <Tag v-else-if="row.status === 5" color="pink">退款中</Tag>
          <Tag v-else-if="row.status === 6" color="cyan">已收货</Tag>
          <Tag v-else-if="row.status === 7" color="green">确认收货</Tag>
          <Tag v-else-if="row.status === 8" color="#B22222">拒绝退款</Tag>
          <Tag v-else-if="row.status === 9" color="gray">已取消</Tag>
        </div>
      </template>
      <template #toolbar-tools></template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '详情',
              type: 'link',
              icon: 'marketeq:eye',
              size: 'small',
              // auth: ['order', 'sys:role:detail'],
              onClick: infoModal.bind(null, row),
            },
            {
              label: '溯源',
              type: 'link',
              icon: 'mdi:timeline-text',
              size: 'small',
              onClick: openOrderTrace.bind(null, row),
            },
            {
              label: '处方',
              type: 'link',
              icon: 'marketeq:eye',
              ifShow: row.order_type !== 2 && row.order_type !== 3,
              // auth: ['超级订单', 'sys:user:save'],
              onClick: openPrescriptionDetail.bind(null, row.p_id),
            },
            {
              label: '模拟支付',
              type: 'link',
              icon: 'mdi:cash-check',
              auth: ['Super Admin', 'sys:user:save'],
              ifShow: row.is_pay === 0,
              onClick: handleSimulatePay.bind(null, row),
            },
            {
              label: '发货',
              type: 'link',
              icon: 'ri:send-plane-fill',
              auth: ['Super Admin','Admin', 'sys:user:save'],
              onClick: wareSend.bind(null, row),
              // popConfirm: {
              //   title: '确定发货吗？',
              //   confirm: wareSend.bind(null, row),
              // },
            },
          ]"
          :drop-down-actions="[
            {
              label: '退款',
              type: 'link',
              icon: 'mingcute:refund-dollar-fill',
              // auth: ['超级订单', 'sys:user:save'],
              ifShow: row.is_pay === 1,
              onClick: openRefundModal.bind(null, row.id),
              // popConfirm: {
              //   title: '确定发货吗？',
              //   confirm: wareSend.bind(null, row),
              // },
            },
          ]"
        />
      </template>

      <template #expand-content="{ row }">
        <div
          v-if="row.prescription_type === 2 || row.prescription_type === 5"
          class="product-list mt-5"
        >
          <div
            v-for="(item, index) in row.product_order_items"
            :key="index"
            class="box-card mb-6 rounded-lg p-4"
          >
            <div class="flex items-start">
              <div>
                <div
                  class="mr-6 h-32 w-32 overflow-hidden rounded-lg bg-gray-200 dark:bg-gray-800"
                >
                  <Image
                    :src="item.drug_image"
                    alt=""
                    height="100%"
                    width="100%"
                  />
                </div>
                <div class="ml-3 mt-5 text-sm">
                  <span class="text-gray-500 dark:text-gray-400">商品编号：</span>
                  X00{{ index + 1 }}
                </div>
              </div>
              <div class="flex-grow space-y-2">
                <div class="text-sm">
                  <span class="text-gray-500 dark:text-gray-400">商品名称:</span>
                  {{ item.drug_name }}
                </div>
                <div class="text-sm">
                  <span class="text-gray-500 dark:text-gray-400">商品规格:</span>
                  {{ item.drug ? item.drug.specification : '暂无' }}
                </div>
                <div class="text-sm">
                  <span class="text-gray-500 dark:text-gray-400">商品数量:</span>
                  {{ item.number }}
                </div>
                <div class="text-sm">
                  <span class="text-gray-500 dark:text-gray-400">商品厂家:</span>
                  {{
                    item.drug
                      ? item.drug.source_info != null
                        ? item.drug.source_info.name
                        : item.drug.source
                      : '暂无'
                  }}
                </div>
                <div class="text-sm">
                  <span class="text-gray-500 dark:text-gray-400">商品价格:</span>
                  {{ item.price }} 元
                </div>
              </div>
            </div>
          </div>
        </div>

        <div
          v-if="row.prescription_type === 1"
          class="medication-details mt-5 px-4 pb-4 w-[60%]"
        >
          <span class="mb-3 block font-medium">药品明细：</span>
          <div class="flex flex-wrap gap-3">
            <div
              v-for="(item, index) in row.product_order_items"
              :key="index"
              class="tcm-drug-chip w-[200px] max-w-full flex-shrink-0 rounded-lg border border-gray-200 bg-white p-3 text-sm dark:border-gray-600 dark:bg-gray-900"
            >
              <div class="font-medium">
                【{{ item.drug?.drug_number }}】{{ item.drug_name }}
              </div>
              <div class="mt-1 text-gray-600 dark:text-gray-400">
                数量：*{{ item.number * (item.dosage > 0 ? item.dosage : 1) }}
              </div>
              <div class="mt-1 text-gray-600 dark:text-gray-400">
                供货价：{{
                  item.buy_price != null && item.buy_price !== ''
                    ? `${item.buy_price} 元/g`
                    : '—'
                }}
              </div>
              <div class="mt-1 text-gray-600 dark:text-gray-400">
                售价：{{
                  item.buy_price != null && item.buy_price !== ''
                    ? `${item.price} 元/g`
                    : '—'
                }}
              </div>
            </div>
          </div>
        </div>
        <div v-if="!row.prescription_type"></div>
        <div
          class="order-summary mt-6 flex justify-center space-x-4 rounded-lg bg-gray-100 p-4 dark:bg-gray-800"
        >
          <span class="text-sm">采购价：{{ row.market_price || '0.00' }}</span>
          <span class="text-sm">快递费：{{ row.trans_expenses || '0.00' }}</span>
          <span class="text-sm">诊疗费：{{ row.treatement_price || '0.00' }}</span>
          <span class="text-sm">加工费：{{ row.process_price || '0.00' }}</span>
        </div>
      </template>
    </Grid>
    <PercentAdjustDrawer />
  </Page>
</template>
<style scoped lang="scss">
.tcm-drug-chip {
  box-shadow: 0 1px 2px rgb(0 0 0 / 4%);
}
</style>
