<script setup lang="ts">
import { ref } from 'vue';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { Tag, Button, message, Image } from 'ant-design-vue';
import { useVbenDrawer } from '@vben/common-ui';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getPatientOrders } from '../api/index.ts';
import PriceAdjustModal from './PriceAdjustModal.vue';
import OrderPricePercentAdjustDrawer from '#/views/business/order/components/OrderPricePercentAdjustDrawer.vue';
import { getOrderPriceAdjustConfig, adjustOrderPercent } from '#/api/order/priceAdjust';
import type { QuickDiscountOption } from '#/utils/pricePercentAdjust';
import { normalizeQuickOptions } from '#/utils/pricePercentAdjust';

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

interface Product {
  id: number;
  drug_id: number;
  drug_name: string;
  price: number;
  number: number;
  type: number;
  is_chinese_medicine: boolean;
  min_adjust_price: number | null;
  can_adjust: boolean;
  can_percent_adjust?: boolean;
  drug_image?: string;
  specification?: string;
  source_name?: string;
}

interface Order {
  id: number;
  order_no: string;
  prescription_type: number;
  items_price: number;
  total_pay_price: number;
  trans_expenses?: number;
  status: number;
  is_pay: number;
  created_at: string;
  price_discount?: number;
  price_discount_label?: string | null;
  products: Product[];
}

const [DrawerComponent, drawerApi] = useVbenDrawer({
  class: 'w-[1000px]',
  onCancel() {
    drawerApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = drawerApi.getData<{ registerId: number }>();
      if (data?.registerId) {
        registerId.value = data.registerId;
        fetchOrders();
      }
    } else {
      gridApi.setGridOptions({ data: [] });
      registerId.value = null;
    }
  },
});

const [PriceAdjustDrawerComponent, priceAdjustDrawerApi] = useVbenDrawer({
  connectedComponent: PriceAdjustModal,
});

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

const priceAdjustMeta = ref({
  scope: 'sale_only' as 'both' | 'sale_only',
  quickOptions: [] as QuickDiscountOption[],
});

const registerId = ref<number | null>(null);

const gridOptions: VxeGridProps<Order> = {
  checkboxConfig: {
    highlight: true,
    labelField: '',
  },
  columnConfig: {
    useKey: true,
  },
  rowConfig: {
    useKey: true,
  },
  columns: [
    { type: 'expand', width: 80, slots: { content: 'expand-content' } },
    { type: 'seq', width: 60, title: '序号' },
    { field: 'order_no', title: '订单号', width: 180 },
    {
      field: 'prescription_type',
      title: '处方类型',
      width: 100,
      slots: { default: 'prescription_type' },
    },
    {
      field: 'items_price',
      title: '商品总价',
      width: 120,
      slots: { default: 'items_price' },
    },
    {
      field: 'total_pay_price',
      title: '支付总价',
      width: 120,
      slots: { default: 'total_pay_price' },
    },
    {
      field: 'trans_expenses',
      title: '邮费',
      width: 100,
      slots: { default: 'trans_expenses' },
    },
    {
      field: 'is_pay',
      title: '支付状态',
      width: 100,
      slots: { default: 'is_pay' },
    },
    { field: 'created_at', title: '订单生成时间', width: 180 },
    {
      type: 'html',
      title: '操作',
      width: 120,
      slots: { default: 'action' },
    },
  ],
  data: [],
  expandConfig: {},
  pagerConfig: {
    enabled: false,
  },
  height: 'auto',
  border: false,
  showOverflow: false,
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
  showSearchForm: false,
});

const getPrescriptionTypeText = (type: number): string => {
  const typeMap: Record<number, string> = {
    1: '中药',
    2: '西药',
    3: '颗粒药',
  };
  return typeMap[type] || '未知';
};

const getPrescriptionTypeColor = (type: number): string => {
  const colorMap: Record<number, string> = {
    1: 'orange',
    2: 'blue',
    3: 'purple',
  };
  return colorMap[type] || 'default';
};

const handleAdjustPrice = (product: Product, orderId: number) => {
  priceAdjustDrawerApi.setData({
    productOrderId: orderId,
    productOrderItemId: product.id,
    drugId: product.drug_id,
    drugName: product.drug_name,
    currentPrice: product.price,
    minAdjustPrice: product.min_adjust_price || 0,
    registerId: registerId.value,
    onSuccess: () => {
      fetchOrders();
    },
  });
  priceAdjustDrawerApi.open();
};

const handleOrderPercentAdjust = (order: Order) => {
  const discount = Number(order.price_discount ?? 100);
  percentAdjustDrawerApi.setData({
    stage: 'post_order',
    priceDiscount: discount,
    price_discount: discount,
    productOrderId: order.id,
    registerId: registerId.value,
    quickOptions: normalizeQuickOptions(priceAdjustMeta.value.quickOptions),
    onSuccess: () => fetchOrders(),
  });
  percentAdjustDrawerApi.open();
};

function clearOrderPriceDiscount(order: Order) {
  adjustOrderPercent({
    product_order_id: order.id,
    price_discount: 100,
    register_id: registerId.value || 0,
  })
    .then(() => {
      message.success('已清除价格浮动');
      fetchOrders();
    })
    .catch((e: any) => message.error(e?.message || '操作失败'));
}

const fetchOrders = async () => {
  if (!registerId.value) {
    return;
  }
  gridApi.setLoading(true);
  try {
    const cfg = await getOrderPriceAdjustConfig();
    priceAdjustMeta.value = {
      scope: cfg?.order_price_adjust_scope === 'both' ? 'both' : 'sale_only',
      quickOptions: normalizeQuickOptions(cfg?.order_discount_quick_options),
    };
    const res = await getPatientOrders(registerId.value);
    const orderList: Order[] = res?.result || res?.data || res || [];
    gridApi.setGridOptions({ data: orderList });
  } catch (error) {
    console.error('获取订单列表失败:', error);
    message.error('获取订单列表失败');
  } finally {
    gridApi.setLoading(false);
  }
};
</script>

<template>
  <DrawerComponent title="患者订单列表" class="order-list-drawer w-[60%]">
    <Grid>
      <!-- 处方类型 -->
      <template #prescription_type="{ row }">
        <Tag :color="getPrescriptionTypeColor(row.prescription_type)">
          {{ getPrescriptionTypeText(row.prescription_type) }}
        </Tag>
      </template>
      
      <!-- 商品总价 -->
      <template #items_price="{ row }">
        ￥{{ Number(row.items_price || 0).toFixed(2) }}
      </template>
      
      <!-- 支付总价 -->
      <template #total_pay_price="{ row }">
        ￥{{ Number(row.total_pay_price || 0).toFixed(2) }}
      </template>
      
      <!-- 邮费 -->
      <template #trans_expenses="{ row }">
        ￥{{ Number(row.trans_expenses || 0).toFixed(2) }}
      </template>
      
      <!-- 支付状态 -->
      <template #is_pay="{ row }">
        <Tag :color="row.is_pay === 1 ? 'green' : 'red'">
          {{ row.is_pay === 1 ? '已支付' : '未支付' }}
        </Tag>
      </template>
      
      <!-- 操作 -->
      <template #action="{ row }">
        <div v-if="row.price_discount_label" class="text-xs text-gray-500 mb-1">
          浮动：{{ row.price_discount_label }}
        </div>
        <Button
          v-if="row.is_pay !== 1 && row.price_discount && row.price_discount !== 100 && row.products?.some((p: Product) => p.can_percent_adjust)"
          type="link"
          size="small"
          @click="clearOrderPriceDiscount(row)"
        >
          清除浮动
        </Button>
        <span v-if="row.is_pay === 1 || !row.products?.some((p: Product) => p.can_percent_adjust)" style="color: #999">共 {{ row.products?.length || 0 }} 个商品</span>
      </template>
      
      <!-- 展开内容：商品列表 -->
      <template #expand-content="{ row }">
        <div
          v-if="row.prescription_type === 2 || row.prescription_type === 5 || row.products?.some((p: Product) => p.can_percent_adjust)"
          class="product-list mt-5"
        >
          <div
            v-for="(product, index) in row.products"
            :key="product.id || 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="product.drug_image || '/img/empty.png'"
                    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>
                  {{ product.drug_name }}
                </div>
                <div class="text-sm">
                  <span class="text-gray-500 dark:text-gray-400">商品规格:</span>
                  {{ product.specification || '暂无' }}
                </div>
                <div class="text-sm">
                  <span class="text-gray-500 dark:text-gray-400">商品数量:</span>
                  {{ product.number }}
                </div>
                <div class="text-sm">
                  <span class="text-gray-500 dark:text-gray-400">商品厂家:</span>
                  {{ product.source_name || '暂无' }}
                </div>
                <div class="text-sm">
                  <span class="text-gray-500 dark:text-gray-400">商品价格:</span>
                  <span class="ml-1">￥{{ Number(product.price || 0).toFixed(4) }}</span>
                </div>
                <div
                  v-if="!product.is_chinese_medicine && product.can_adjust && row.is_pay !== 1"
                  class="text-sm mt-2"
                >
                  <Button type="link" size="small" @click="handleAdjustPrice(product, row.id)">
                    调整价格
                  </Button>
                  <span class="text-gray-500 dark:text-gray-400 ml-2">
                    (最低调整金额: ￥{{ Number(product.min_adjust_price || 0).toFixed(2) }})
                  </span>
                </div>
                <div v-if="product.is_chinese_medicine && !product.can_percent_adjust" class="text-sm">
                  <span class="text-gray-500 dark:text-gray-400">备注:</span>
                  <span style="color: #999">中药不可调整</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div
          v-if="row.prescription_type === 1"
          class="medication-details mt-5 p-10"
        >
          <span class="mb-2 font-medium">药品明细：</span>
          <ul class="custom-list pl-6">
            <li
              v-for="(product, index) in row.products"
              :key="product.id || index"
              class="custom-list-item"
            >
              【{{ product.drug_id }}】 {{ product.drug_name }} （* {{ product.number }}）
            </li>
          </ul>
        </div>
      </template>
    </Grid>
    <PriceAdjustDrawerComponent />
    <PercentAdjustDrawer />
  </DrawerComponent>
</template>

<style scoped>
.order-list-drawer {
  padding: 16px;
}

.product-list {
  padding: 8px 0;
}

.product-item {
  background-color: #fafafa;
  border: 1px solid #e8e8e8;
}

.product-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.product-row {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.product-label {
  min-width: 120px;
  color: #666;
  font-weight: 500;
}

.product-value {
  flex: 1;
  color: #333;
}

.dark .product-item {
  background-color: #1f1f1f;
  border-color: #434343;
}

.dark .product-label {
  color: #999;
}

.dark .product-value {
  color: #e5e5e5;
}

.custom-list {
  list-style-type: none;
  padding-left: 0;
}

.custom-list-item {
  background-color: rgba(64, 158, 255, 0.04);
  border-radius: 4px;
  margin-bottom: 8px;
  padding: 8px 12px;
  font-size: 14px;
  transition: background-color 0.3s;
}

.custom-list-item:hover {
  background-color: rgba(64, 158, 255, 0.1);
}

.custom-list-item::before {
  content: '';
  display: inline-block;
  width: 6px;
  height: 6px;
  background-color: #409eff;
  border-radius: 50%;
  margin-right: 8px;
  vertical-align: middle;
}
</style>
