<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue';

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

import {
  Button,
  Card,
  Empty,
  Image,
  Input,
  Pagination,
  Space,
  Spin,
  Tabs,
  Tag,
} from 'ant-design-vue';

import { getDeliveryWarehouseOrderList } from '#/views/system/delivery-warehouse-order/api';
import PrescriptionDetail from '#/views/doctor/doctor-reception/components/PrescriptionDetail.vue';

import DetailModalDemo from './components/detail-modal.vue';
import FormModalDemo from './components/modal.vue';

defineOptions({ name: 'DeliveryWarehouseOrderIndex' });

/** Tab：待发货1 / 待收货2 / 确认收货7（仅7） */
type StatusTab = '1' | '2' | '7';

const statusTab = ref<StatusTab>('1');
const orderNo = ref('');
const loading = ref(false);
const list = ref<Record<string, any>[]>([]);
const pager = reactive({
  currentPage: 1,
  pageSize: 12,
  total: 0,
});

const statusMeta: Record<number, { text: string; color: string }> = {
  0: { text: '待支付', color: 'default' },
  1: { text: '待发货', color: 'orange' },
  2: { text: '待收货', color: 'blue' },
  3: { text: '待评价', color: 'cyan' },
  4: { text: '已退款', color: 'red' },
  5: { text: '退款中', color: 'volcano' },
  6: { text: '已收货', color: 'green' },
  7: { text: '确认收货', color: 'green' },
  8: { text: '拒绝退款', color: 'gold' },
  9: { text: '已取消', color: 'default' },
};

const tabLabel = computed(() => {
  if (statusTab.value === '1') return '待发货';
  if (statusTab.value === '2') return '待收货';
  return '确认收货';
});

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: FormModalDemo,
});

const [DetailModal, detailModalApi] = useVbenModal({
  connectedComponent: DetailModalDemo,
});

/** 复用医生端处方详情弹窗，按 p_id 打开 */
const [PrescriptionDetailModal, PrescriptionDetailModalApi] = useVbenModal({
  connectedComponent: PrescriptionDetail,
});

/**
 * 加载当前 Tab 订单卡片列表
 */
async function loadList() {
  loading.value = true;
  try {
    const res = await getDeliveryWarehouseOrderList({
      page: pager.currentPage,
      pageSize: pager.pageSize,
      status: Number(statusTab.value),
      order_no: orderNo.value?.trim() || undefined,
    });
    list.value = res?.items ?? res?.list ?? [];
    pager.total = Number(res?.total ?? res?.pager?.total ?? 0);
  } finally {
    loading.value = false;
  }
}

function handleTabChange(key: string | number) {
  statusTab.value = String(key) as StatusTab;
  pager.currentPage = 1;
  void loadList();
}

function handleSearch() {
  pager.currentPage = 1;
  void loadList();
}

/** 列表刷新回调（发货成功后用） */
const gridApiLike = {
  reload: () => loadList(),
  query: () => loadList(),
};

/** 打开发货弹窗 */
function wareSend(row: Record<string, any>) {
  formModalApi.setData({
    values: {
      order_id: row?.id,
      order_no: row?.order_no,
    },
    gridApi: gridApiLike,
  });
  formModalApi.open();
}

/**
 * 打开处方详情：与商品订单一致，values 传处方主键 p_id
 * 无处方或商城/非处方单不打开
 */
function openPrescriptionDetail(row: Record<string, any>) {
  const pId = Number(row?.p_id ?? 0);
  if (!pId) {
    return;
  }
  PrescriptionDetailModalApi.setData({ values: pId });
  PrescriptionDetailModalApi.open();
}

/** 是否展示「查看处方」：有 p_id，且排除商城类 order_type */
function canViewPrescription(row: Record<string, any>) {
  const pId = Number(row?.p_id ?? 0);
  const orderType = Number(row?.order_type ?? 0);
  return pId > 0 && orderType !== 2 && orderType !== 3;
}

/**
 * 打开详情；scrollToLogistics=true 时详情加载后滚到物流区块
 * 待发货时传入 onShip，详情内可直接打开发货弹窗
 */
function openDetail(row: Record<string, any>, scrollToLogistics = false) {
  detailModalApi.setData({
    id: row?.id,
    scrollToLogistics,
    onShip:
      Number(row?.warehouse_is_send ?? 0) === 0 || Number(row?.status) === 1
        ? () => {
          detailModalApi.close();
          wareSend(row);
        }
        : undefined,
  });
  detailModalApi.open();
}

/** 本仓商品行（图/名/规格/数量） */
function productRows(row: Record<string, any>) {
  return Array.isArray(row.products) ? row.products : [];
}

/** 数量展示：有剂量时显示 number×dosage */
function qtyText(p: Record<string, any>) {
  const n = p.number ?? '-';
  if (p.dosage != null && p.dosage !== '' && Number(p.dosage) !== 1) {
    return `${n}`;
  }
  return String(n);
}

function addressText(row: Record<string, any>) {
  const region = row.express_region || '';
  const addr = row.express_address || '';
  return `${region}${addr}`.trim() || '—';
}

onMounted(() => {
  void loadList();
});
</script>

<template>
  <Page auto-content-height class="bg-[#f7f8fa] dark:bg-[#0a0a0a] transition-colors duration-300" title="我的订单">
    <FormModal/>
    <DetailModal/>
    <PrescriptionDetailModal/>

    <div class="flex flex-col gap-6 p-2 md:p-4">
      <!-- 顶部操作栏 -->
      <div class="flex flex-col gap-4 rounded-2xl bg-white dark:bg-[#141414] px-6 py-4 shadow-sm dark:shadow-none dark:border dark:border-[#303030] md:flex-row md:items-center md:justify-between transition-colors duration-300">
        <Tabs :active-key="statusTab" :tab-bar-style="{ margin: 0, border: 'none' }" @change="handleTabChange" size="large">
          <Tabs.TabPane key="1" tab="待发货"/>
          <Tabs.TabPane key="2" tab="待收货"/>
          <Tabs.TabPane key="7" tab="确认收货"/>
        </Tabs>

        <Input.Search @search="handleSearch" allow-clear class="w-full md:w-80" enter-button placeholder="请输入订单号快捷查询" size="large" v-model:value="orderNo"/>
      </div>

      <Spin :spinning="loading">
        <div
          v-if="list.length"
          class="grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-3"
        >
          <Card :body-style="{ padding: 0 }" :key="row.id" class="overflow-hidden rounded-2xl border-transparent dark:border-[#303030] bg-white dark:bg-[#141414] shadow-sm dark:shadow-none transition-all hover:-translate-y-1 hover:shadow-md dark:hover:border-gray-500" v-for="row in list">

            <!-- 卡片 Header -->
            <div class="flex items-center justify-between border-b border-gray-100 dark:border-[#2a2a2a] px-5 py-4 transition-colors duration-300">
              <div class="flex items-center gap-2">
                <span class="text-sm text-gray-500 dark:text-gray-400">订单号</span>
                <span class="text-base font-semibold text-gray-800 dark:text-gray-200">{{ row.order_no || '—' }}</span>
              </div>
              <Tag :color="statusMeta[row.status]?.color || 'default'" class="m-0 rounded-full border-none px-3 py-1 font-medium shadow-sm dark:shadow-none">
                {{ statusMeta[row.status]?.text || row.status }}
              </Tag>
            </div>

            <!-- 商品展示区 -->
            <div class="bg-gray-50/60 dark:bg-[#1a1a1a] px-5 py-4 transition-colors duration-300">
              <div v-if="productRows(row).length" class="flex flex-col gap-4">
                <div
                  v-for="p in productRows(row)"
                  :key="p.id"
                  class="flex items-start gap-3"
                >
                  <Image :height="68" :src="p.drug?.image || p.drug_image || ''" :width="68" class="shrink-0 rounded-xl border border-gray-100 dark:border-transparent bg-white dark:bg-[#2a2a2a] object-cover p-1 shadow-sm dark:shadow-none" fallback="/img/empty.png"/>
                  <div class="min-w-0 flex-1 pt-1">
                    <div class="line-clamp-2 text-sm font-medium text-gray-800 dark:text-gray-200 transition-colors hover:text-blue-600 dark:hover:text-blue-400 cursor-pointer">
                      {{ p.drug_name || p.drug?.drug_name || '-' }}
                    </div>
                    <div class="mt-2 flex items-center justify-between">
                      <span class="rounded bg-white dark:bg-[#2a2a2a] px-2 py-0.5 text-xs text-gray-500 dark:text-gray-400 shadow-sm dark:shadow-none border border-gray-100 dark:border-transparent">
                        {{ p.drug?.specification || '默认规格' }}
                      </span>
                      <span class="text-base font-bold text-gray-800 dark:text-gray-200">x{{ qtyText(p) }}</span>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="text-sm text-gray-400 dark:text-gray-600 py-2">— 该订单暂无商品明细 —</div>
            </div>

            <!-- 配送信息区 -->
            <div class="px-5 py-4 text-sm space-y-3 transition-colors duration-300">
              <div class="flex items-start">
                <span class="w-16 shrink-0 text-gray-400 dark:text-gray-500">收件人</span>
                <div class="flex-1 text-gray-800 dark:text-gray-200">
                  <span class="font-medium mr-2">{{ row.express_name || '—' }}</span>
                  <span class="text-gray-500 dark:text-gray-400">{{ row.express_mobile || '' }}</span>
                  <div class="mt-1 text-gray-500 dark:text-gray-400 line-clamp-2">{{ addressText(row) }}</div>
                </div>
              </div>
              <div class="flex items-center">
                <span class="w-16 shrink-0 text-gray-400 dark:text-gray-500">物流</span>
                <span
                  class="flex-1 truncate"
                  :class="row.logistics_summary === '未发货' ? 'text-gray-400 dark:text-gray-500' : 'text-blue-500 dark:text-blue-400 cursor-pointer hover:underline'"
                >
                  {{ row.logistics_summary || '未发货' }}
                </span>
              </div>
            </div>

            <!-- 底部操作区 (已修复 v-if 报错问题) -->
            <div class="flex items-center justify-between border-t border-gray-50 dark:border-[#2a2a2a] px-5 py-3 transition-colors duration-300">
              <span class="text-xs text-gray-400 dark:text-gray-500">{{ row.created_at || '' }}</span>
              <Space>
                <Button @click="openDetail(row, false)" shape="round" size="middle">
                  订单详情
                </Button>
                <Button
                  v-if="canViewPrescription(row)"
                  shape="round"
                  size="middle"
                  @click="openPrescriptionDetail(row)"
                >
                  查看处方
                </Button>
                <Button
                  v-if="Number(row.is_send) === 1 || Number(row.status) >= 2 || !!row.waybill_no"
                  shape="round"
                  size="middle"
                  @click="openDetail(row, true)"
                >
                  查看物流
                </Button>
                <Button
                  v-if="Number(row.warehouse_is_send ?? 0) === 0"
                  class="shadow-md shadow-blue-500/20 dark:shadow-none"
                  shape="round"
                  size="middle"
                  type="primary"
                  @click="wareSend(row)"
                >
                  立即发货
                </Button>
              </Space>
            </div>
          </Card>
        </div>

        <Empty :description="`当前暂无${tabLabel}订单`" :image="Empty.PRESENTED_IMAGE_SIMPLE" class="my-20" v-else/>
      </Spin>

      <!-- 分页区域 -->
      <div v-if="pager.total > 0" class="flex justify-end pb-8">
        <Pagination :page-size-options="['12', '24', '48']" :total="pager.total" @change="loadList" @show-size-change="loadList" show-quick-jumper show-size-changer v-model:current="pager.currentPage" v-model:page-size="pager.pageSize"/>
      </div>
    </div>
  </Page>
</template>

<style scoped>
:deep(.ant-tabs-nav::before) {
  border-bottom: none !important;
}
:deep(.ant-tabs-tab) {
  @apply dark:text-gray-400;
}
:deep(.ant-tabs-tab-active) {
  @apply dark:!text-blue-400;
}
:deep(.ant-card-body) {
  @apply dark:bg-[#141414];
}
</style>
