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

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

import { Button, Descriptions, Image, Space, Tabs, Tag, Timeline } from 'ant-design-vue';

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

defineOptions({
  name: 'DeliveryWarehouseOrderDetailModal',
});

const data = ref<Record<string, any>>({});
const scrollToLogistics = ref(false);
const logisticsAnchorRef = ref<HTMLElement | null>(null);
/** 待发货时由列表传入，点击后关详情并打开发货弹窗 */
const onShipFn = ref<null | (() => void)>(null);

const canShip = computed(() => {
  const packages = Array.isArray(data.value.packages) ? data.value.packages : [];
  const mineUnsent = packages.some((p: any) => Number(p.is_send) === 0);
  const legacy =
    Number(data.value.warehouse_is_send ?? 0) === 0 &&
    Number(data.value.status) === 1;
  return (mineUnsent || legacy) && typeof onShipFn.value === 'function';
});

/** 详情内是否可查看处方：有 p_id 且非商城类订单 */
const canViewPrescription = computed(() => {
  const pId = Number(data.value.p_id ?? 0);
  const orderType = Number(data.value.order_type ?? 0);
  return pId > 0 && orderType !== 2 && orderType !== 3;
});

/** 顶部操作栏：有发货或查看处方任一即可显示 */
const showToolbar = computed(
  () => canShip.value || canViewPrescription.value,
);
/** 仅使用仓侧详情返回的本仓 packages，避免平台物流接口带出他仓商品 */
const packageTabs = computed(() => {
  return Array.isArray(data.value.packages) ? data.value.packages : [];
});
const activePkg = ref('0');

const statusMap: 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 deliveryMethodMap: Record<number, string> = {
  0: '快递邮寄',
  1: '到店自取',
};

/**
 * 拉取仓侧订单详情（含本仓药品 + 本仓包裹物流）
 */
async function loadDetail(id: number | string) {
  data.value = (await getDeliveryWarehouseOrderDetail(id)) || {};
  activePkg.value = '0';
  if (scrollToLogistics.value) {
    await nextTick();
    logisticsAnchorRef.value?.scrollIntoView({
      behavior: 'smooth',
      block: 'start',
    });
  }
}

function getColor(status: any) {
  switch (status) {
    case '揽收': {
      return 'orange';
    }
    case '派件': {
      return 'blue';
    }
    case '签收': {
      return 'green';
    }
    default: {
      return '';
    }
  }
}

const expressNoRow = () =>
  data.value.express_no || data.value.expressNo || {};

function handleShip() {
  const fn = onShipFn.value;
  if (typeof fn === 'function') {
    fn();
  }
}

/** 详情内打开处方详情弹窗 */
function openPrescriptionDetail() {
  const pId = Number(data.value.p_id ?? 0);
  if (!pId) {
    return;
  }
  PrescriptionDetailModalApi.setData({ values: pId });
  PrescriptionDetailModalApi.open();
}

/** 复用医生端处方详情，详情内自建避免与列表页耦合 */
const [PrescriptionDetailModal, PrescriptionDetailModalApi] = useVbenModal({
  connectedComponent: PrescriptionDetail,
});

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  showConfirmButton: false,
  onCancel() {
    modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      data.value = {};
      scrollToLogistics.value = false;
      onShipFn.value = null;
      return;
    }
    const payload = modalApi.getData<Record<string, any>>() || {};
    scrollToLogistics.value = !!payload.scrollToLogistics;
    onShipFn.value =
      typeof payload.onShip === 'function' ? payload.onShip : null;
    const id = payload.id || payload.values?.id;
    if (id) {
      loadDetail(id);
    }
  },
});
</script>

<template>
  <Modal title="订单详情" class="w-[720px]">
    <PrescriptionDetailModal />
    <div class="wh-order-detail space-y-5">
      <div v-if="showToolbar" class="flex justify-end">
        <Space>
          <Button v-if="canViewPrescription" @click="openPrescriptionDetail">
            查看处方
          </Button>
          <Button v-if="canShip" type="primary" @click="handleShip">发货</Button>
        </Space>
      </div>
      <section>
        <h3 class="section-title">收货人信息</h3>
        <Descriptions
          :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }"
          bordered
          size="small"
        >
          <Descriptions.Item label="收货人">
            {{ data.express_name || '-' }}
          </Descriptions.Item>
          <Descriptions.Item label="联系电话">
            {{ data.express_mobile || '-' }}
          </Descriptions.Item>
          <Descriptions.Item label="收货地区" :span="2">
            {{ data.express_region || '-' }}
          </Descriptions.Item>
          <Descriptions.Item label="详细地址" :span="2">
            {{ data.express_address || '-' }}
          </Descriptions.Item>
        </Descriptions>
      </section>

      <section>
        <h3 class="section-title">订单信息</h3>
        <Descriptions
          :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }"
          bordered
          size="small"
        >
          <Descriptions.Item label="订单号">
            {{ data.order_no || '-' }}
          </Descriptions.Item>
          <Descriptions.Item label="订单状态">
            <Tag :color="statusMap[data.status]?.color || 'default'">
              {{ statusMap[data.status]?.text || data.status || '-' }}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="邮寄方式">
            {{
              deliveryMethodMap[data.delivery_method] ??
              data.delivery_method ??
              '-'
            }}
          </Descriptions.Item>
          <Descriptions.Item label="下单时间">
            {{ data.created_at || '-' }}
          </Descriptions.Item>
          <Descriptions.Item label="发货时间">
            {{ data.send_time || '-' }}
          </Descriptions.Item>
        </Descriptions>
      </section>

      <section>
        <h3 class="section-title">药品信息（本仓）</h3>
        <div
          v-if="Array.isArray(data.products) && data.products.length"
          class="product-list"
        >
          <div
            v-for="item in data.products"
            :key="item.id"
            class="product-row"
          >
            <div class="product-cover">
              <Image
                :src="item.drug?.image || item.drug_image || '/img/empty.png'"
                alt=""
                height="64"
                width="64"
              />
            </div>
            <div class="product-meta">
              <div class="product-name">{{ item.drug_name || '-' }}</div>
              <div class="product-sub">
                规格：{{ item.drug?.specification || '-' }}
              </div>
              <div class="product-sub">
                数量：{{ item.number ?? '-' }}
                <span v-if="item.dosage != null && item.dosage !== ''">
                  ｜剂量：{{ item.dosage }}
                </span>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="empty-tip">暂无本仓药品</div>
      </section>

      <section ref="logisticsAnchorRef">
        <h3 class="section-title">物流信息</h3>
        <Tabs
          v-if="packageTabs.length"
          v-model:active-key="activePkg"
          type="card"
        >
          <Tabs.TabPane
            v-for="(pkg, idx) in packageTabs"
            :key="String(idx)"
            :tab="`包裹${pkg.package_no || idx + 1}（${pkg.warehouse_name || '本仓'}）`"
          >
            <template v-if="Number(pkg.is_send) === 1 && pkg.express">
              <Descriptions
                :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }"
                bordered
                size="small"
              >
                <Descriptions.Item label="物流公司">
                  {{ pkg.express.express_company_name || '-' }}
                </Descriptions.Item>
                <Descriptions.Item label="运单号">
                  {{ pkg.express.express_no || '-' }}
                </Descriptions.Item>
                <Descriptions.Item label="最新状态">
                  {{ pkg.express.state_txt || '-' }}
                </Descriptions.Item>
              </Descriptions>
              <div
                v-if="
                  Array.isArray(pkg.express.detail) && pkg.express.detail.length
                "
                class="mt-4"
              >
                <Timeline>
                  <Timeline.Item
                    v-for="(detail, dIdx) in pkg.express.detail"
                    :key="dIdx"
                  >
                    <Tag :color="getColor(detail.status)">{{
                      detail.status
                    }}</Tag>
                    <p>{{ detail.detail_at }}</p>
                    <p>{{ detail.detail }}</p>
                  </Timeline.Item>
                </Timeline>
              </div>
              <div v-else class="empty-tip mt-3">暂无物流轨迹</div>
            </template>
            <div v-else class="empty-tip">本包裹尚未发货</div>
          </Tabs.TabPane>
        </Tabs>
        <template
          v-else-if="
            Number(data.is_send) === 1 ||
            Number(data.status) >= 2 ||
            expressNoRow().express_no
          "
        >
          <Descriptions
            :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }"
            bordered
            size="small"
          >
            <Descriptions.Item label="物流公司">
              {{ expressNoRow().express_company_name || '-' }}
            </Descriptions.Item>
            <Descriptions.Item label="运单号">
              {{ expressNoRow().express_no || '-' }}
            </Descriptions.Item>
          </Descriptions>
        </template>
        <div v-else class="empty-tip">暂无物流</div>
      </section>
    </div>
  </Modal>
</template>

<style scoped>
.section-title {
  margin-bottom: 10px;
  font-size: 15px;
  font-weight: 600;
  color: hsl(var(--foreground));
}
.product-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.product-row {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px;
  border: 1px solid hsl(var(--border));
  border-radius: 8px;
  background: hsl(var(--card));
}
.product-cover {
  width: 64px;
  height: 64px;
  overflow: hidden;
  border-radius: 6px;
  background: hsl(var(--muted));
  flex-shrink: 0;
}
.product-meta {
  min-width: 0;
  flex: 1;
}
.product-name {
  font-size: 14px;
  font-weight: 500;
  color: hsl(var(--foreground));
}
.product-sub {
  margin-top: 2px;
  font-size: 12px;
  color: hsl(var(--muted-foreground));
}
.empty-tip {
  font-size: 13px;
  color: hsl(var(--muted-foreground));
}
</style>
