<template>
  <div class="customer-orders">
    <h1 class="page-title">我的订单</h1>
    
    <!-- 订单列表 -->
    <div v-if="orders.length > 0" class="order-list">
      <div v-for="order in orders" :key="order.id" class="order-card" @click="showDetail(order)">
        <div class="order-header">
          <span class="order-no">订单号：{{ order.orderNo || order.id }}</span>
          <span class="order-date">{{ formatDate(order.createTime) }}</span>
        </div>
        <div class="order-body">
          <div class="order-info">
            <div class="info-row">
              <span class="label">订单金额：</span>
              <span class="amount">¥{{ order.amount?.toFixed(2) || '0.00' }}</span>
            </div>
            <div class="info-row" v-if="order.remark">
              <span class="label">备注：</span>
              <span class="remark">{{ order.remark }}</span>
            </div>
          </div>
        </div>
        <div class="order-footer">
          <div class="order-status">
            <span class="status" :class="order.status">{{ getStatusText(order.status) }}</span>
          </div>
          <t-button 
            v-if="order.status === 'UNPAID'" 
            size="small" 
            theme="primary"
            @click.stop="openPay(order)"
          >
            立即支付
          </t-button>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-else class="empty-state">
      <div class="empty-icon">💊</div>
      <p>暂无订单记录</p>
      <p class="tip">医生开处方后，您可以在这里查看和购买</p>
    </div>
    
    <!-- 订单详情弹窗 -->
    <t-dialog v-model:visible="detailVisible" header="订单详情" width="600" :footer="false">
      <div v-if="selectedOrder" class="order-detail">
        <div class="detail-header">
          <div class="detail-no">
            <span class="label">订单编号：</span>
            <span class="value">{{ selectedOrder.orderNo || selectedOrder.id }}</span>
          </div>
          <div class="detail-status">
            <span class="status" :class="selectedOrder.status">{{ getStatusText(selectedOrder.status) }}</span>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>药品明细</h4>
          <div v-if="orderItems.length > 0" class="items-list">
            <div v-for="(item, idx) in orderItems" :key="idx" class="item-row">
              <span class="item-name">{{ item.drugName || '药品' }}</span>
              <span class="item-spec">{{ item.specification || '' }}</span>
              <span class="item-quantity">x{{ item.quantity }}</span>
              <span class="item-price">¥{{ item.subtotal?.toFixed(2) || '0.00' }}</span>
            </div>
          </div>
          <div v-else class="no-items">
            <p>暂无药品明细</p>
          </div>
        </div>
        
        <div class="detail-total">
          <span class="label">订单金额：</span>
          <span class="amount">¥{{ selectedOrder.amount?.toFixed(2) || '0.00' }}</span>
        </div>
        
        <div class="detail-actions" v-if="selectedOrder.status === 'UNPAID'">
          <t-button theme="primary" block size="large" @click="payOrder">立即支付</t-button>
        </div>
      </div>
    </t-dialog>
    
    <!-- 支付弹窗 -->
    <t-dialog v-model:visible="payVisible" header="选择支付方式" width="400" :on-confirm="confirmPay">
      <div class="pay-methods">
        <div 
          v-for="method in payMethods" 
          :key="method.value"
          class="pay-method"
          :class="{ active: selectedPayMethod === method.value }"
          @click="selectedPayMethod = method.value"
        >
          <span class="method-icon">{{ method.icon }}</span>
          <span class="method-name">{{ method.label }}</span>
        </div>
      </div>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { api } from '../../api';

const orders = ref<any[]>([]);
const detailVisible = ref(false);
const payVisible = ref(false);
const selectedOrder = ref<any>(null);
const orderItems = ref<any[]>([]);
const selectedPayMethod = ref('WECHAT');

const payMethods = [
  { label: '微信支付', value: 'WECHAT', icon: '💚' },
  { label: '支付宝', value: 'ALIPAY', icon: '💙' },
  { label: '线下支付', value: 'OFFLINE', icon: '💰' },
];

const loadOrders = async () => {
  try {
    const res = await api.orders({ page: 1, size: 50 });
    if (res.code === 0) {
      orders.value = res.data?.records || [];
    }
  } catch (error) {
    console.error('加载订单失败:', error);
  }
};

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    'UNPAID': '待支付',
    'PAID': '已支付',
    'CANCELLED': '已取消',
    'REFUNDING': '退款中',
    'REFUNDED': '已退款'
  };
  return map[status] || status;
};

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

const showDetail = async (order: any) => {
  selectedOrder.value = order;
  detailVisible.value = true;
  
  // 加载订单详情（包含处方明细）
  try {
    const res = await api.getOrderDetail(order.id);
    if (res.code === 0) {
      orderItems.value = res.data?.items || [];
    }
  } catch (error) {
    console.error('加载订单详情失败:', error);
    orderItems.value = [];
  }
};

const openPay = (order: any) => {
  selectedOrder.value = order;
  selectedPayMethod.value = 'WECHAT';
  payVisible.value = true;
};

const confirmPay = async () => {
  if (!selectedOrder.value) return;
  await payOrder();
};

const payOrder = async () => {
  if (!selectedOrder.value) return;
  
  try {
    const res = await api.payOrder(selectedOrder.value.id, selectedPayMethod.value);
    if (res.code === 0) {
      MessagePlugin.success('支付成功');
      payVisible.value = false;
      detailVisible.value = false;
      loadOrders(); // 刷新订单列表
    } else {
      MessagePlugin.error(res.message || '支付失败');
    }
  } catch (error) {
    console.error('支付失败:', error);
    MessagePlugin.error('支付失败');
  }
};

onMounted(() => {
  loadOrders();
});
</script>

<style scoped>
.customer-orders {
  padding-bottom: 40px;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 32px;
}

/* 订单列表 */
.order-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.order-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.order-header {
  padding: 12px 20px;
  background: #f9fafb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f3f4f6;
}

.order-no {
  font-size: 14px;
  color: #6b7280;
  font-family: monospace;
}

.order-date {
  font-size: 13px;
  color: #9ca3af;
}

.order-body {
  padding: 16px 20px;
}

.order-info .info-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.order-info .label {
  font-size: 14px;
  color: #6b7280;
  min-width: 80px;
}

.order-info .amount {
  font-size: 20px;
  font-weight: 700;
  color: #dc2626;
}

.order-info .remark {
  font-size: 14px;
  color: #4b5563;
}

.order-footer {
  padding: 12px 20px;
  background: #f9fafb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f3f4f6;
}

.status {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 500;
}

.status.UNPAID {
  background: #fef3c7;
  color: #92400e;
}

.status.PAID {
  background: #dbeafe;
  color: #1e40af;
}

.status.CANCELLED,
.status.REFUNDED {
  background: #f3f4f6;
  color: #6b7280;
}

.status.REFUNDING {
  background: #fee2e2;
  color: #991b1b;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 80px 20px;
  background: white;
  border-radius: 16px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state p {
  font-size: 16px;
  color: #6b7280;
  margin-bottom: 8px;
}

.empty-state .tip {
  font-size: 14px;
  color: #9ca3af;
}

/* 订单详情 */
.order-detail {
  padding: 8px 0;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  margin-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.detail-no .label {
  font-size: 14px;
  color: #6b7280;
}

.detail-no .value {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  font-family: monospace;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  font-size: 15px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 12px;
}

.items-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.item-row {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f9fafb;
  border-radius: 8px;
}

.item-name {
  flex: 1;
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
}

.item-spec {
  font-size: 13px;
  color: #6b7280;
}

.item-quantity {
  font-size: 14px;
  color: #6b7280;
  min-width: 40px;
  text-align: center;
}

.item-price {
  font-size: 14px;
  font-weight: 600;
  color: #dc2626;
  min-width: 80px;
  text-align: right;
}

.no-items {
  text-align: center;
  padding: 20px;
  color: #9ca3af;
}

.detail-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-top: 1px solid #e5e7eb;
  margin-bottom: 20px;
}

.detail-total .label {
  font-size: 15px;
  color: #1f2937;
  font-weight: 600;
}

.detail-total .amount {
  font-size: 24px;
  font-weight: 700;
  color: #dc2626;
}

.detail-actions {
  padding-top: 8px;
}

/* 支付方式 */
.pay-methods {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.pay-method {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.pay-method:hover {
  border-color: #0d9488;
}

.pay-method.active {
  border-color: #0d9488;
  background: #f0fdf4;
}

.method-icon {
  font-size: 24px;
}

.method-name {
  font-size: 15px;
  font-weight: 500;
  color: #1f2937;
}

/* 响应式 */
@media (max-width: 640px) {
  .order-header {
    flex-direction: column;
    gap: 4px;
    align-items: flex-start;
  }
  
  .item-row {
    flex-wrap: wrap;
  }
  
  .item-spec {
    width: 100%;
    order: 3;
  }
}
</style>
