<template>
  <el-dialog title="确认支付" v-model="showPayDialog" width="30%">
    <p>总金额：¥{{ totalPrice.toFixed(2) }}</p>
    <template #footer>
      <el-button @click="showPayDialog = false">取消</el-button>
      <el-button type="primary" @click="confirmPay">确认支付</el-button>
    </template>
  </el-dialog>

  <div class="shopping-cart">
    <h1>购物车</h1>

    <!-- 空购物车提示 -->
    <div v-if="cartItems.length === 0">
      <p>购物车为空</p>
    </div>

    <div v-else>
 <div class="food-item" v-for="item in cartItems" :key="item.id">
  <div class="food-item-left">
    <img :src="item.imageUrl" class="food-image" />
    <div class="food-info">
      <h3>{{ item.name }}</h3>
      <p>¥{{ item.price.toFixed(2) }}</p>
      <div class="quantity-control">
        <span>数量：</span>
        <el-input-number
          v-model="item.quantity"
          :min="1"
          @change="updateQuantity(item.id, item.quantity)"
          size="small"
        />
      </div>
    </div>
  </div>
  <el-button type="danger" @click="removeFromCart(item.id)">取消</el-button>
</div>
<el-form label-position="top" class="order-remark" style="margin: 20px 0">
  <el-form-item label="订单备注">
    <el-input
      v-model="orderRemark"
      type="textarea"
      placeholder="请输入订单备注，如：不要香菜、少盐等"
      :rows="3"
    />
  </el-form-item>
</el-form>
     <div class="cart-footer">
  <div class="left-items">
    <p>总价：¥{{ totalPrice.toFixed(2) }}</p>
    <el-button type="warning" @click="clearCart">清空购物车</el-button>
  </div>
  <el-button type="success" class="pay-button" @click="showPayDialog = true">支付</el-button>
</div>
  </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed,onMounted } from 'vue';
import { useCartStore } from '@/userStores/cart'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '@/userStores/user'
const orderRemark = ref('')
const userStore = useUserStore()
const cartStore = useCartStore()
const cartItems = computed(() => cartStore.cartItems)
const totalPrice = computed(() => cartStore.totalPrice)

// 支付弹窗控制
const showPayDialog = ref(false)
// 数量更新
const updateQuantity = (id: number, quantity: number) => {
  cartStore.updateQuantity(id, quantity)
}

// 删除某项
const removeFromCart = (id: number) => {
  cartStore.removeFromCart(id)
  ElMessage.success('已移除该菜品')
}

// 清空
const clearCart = () => {
  cartStore.clearCart()
  ElMessage.success('购物车已清空')
}
import { watch } from 'vue'
watch(showPayDialog, (val) => {
  console.log('showPayDialog 已更改为:', val)
})
// 确认支付函数
const confirmPay = async () => {
  try {
    // 先调用已有的 createOrder 方法，生成订单
    const orderId = await createOrder()
    if (!orderId) {
      // 如果订单创建失败，不继续支付
      return
    }

    // 发起支付宝支付请求
    const payResponse = await axios.post('/api/user/alipay/pay', {
      outTradeNo: orderId,
      subject: '顾客订单',
      totalAmount: totalPrice.value.toFixed(2)
    }, {
      responseType: 'blob'
    })

    // 打开支付宝支付页
    const blob = new Blob([payResponse.data], { type: 'text/html' })
    const url = URL.createObjectURL(blob)
    window.open(url, '_blank')

    // 清空购物车、关闭弹窗
    cartStore.clearCart()
    showPayDialog.value = false
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败，请稍后再试')
  }
}

const createOrder = async () => {
  try {
    // 获取用户 ID 和门店 ID
    const customerId = userStore.getUserId
    const restaurantId = parseInt(localStorage.getItem('selectedStoreId') || '0', 10)

    if (!restaurantId) {
      ElMessage.error('门店信息无效，请重新选择门店')
      return
    }

    // 构造订单项
    const orderItems = cartItems.value.map(item => ({
      dishId: item.id,
      number: item.quantity,
    }))

    // 构造订单请求数据
 const orderRequest = {
  order: {
    accountId: customerId,
    branchId: restaurantId,
    orderRemarks: orderRemark.value,
    orderMoney: totalPrice.value,
    orderStatus: 0
  },
  items: orderItems
}

    const response = await axios.post('/api/user/orders/create', orderRequest)//ok
    const orderId = response.data.orderId
    ElMessage.success('订单已生成，订单号：' + orderId)

    return orderId
  } catch (error) {
    console.error('订单生成失败:', error)
    ElMessage.error('生成订单失败')
  }
};

</script>

<style scoped>
.shopping-cart {
  width: 60%;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.food-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  border-bottom: 1px solid #eee;
  padding-bottom: 12px;
}

.food-item-left {
  display: flex;
  align-items: center;
}

.food-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 16px;
  border-radius: 8px;
}

.food-info {
  display: flex;
  flex-direction: column;
}

.quantity-control {
  margin-top: 8px;
}

.add-item {
  margin-top: 20px;
}

button {
  padding: 8px 16px;
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.cart-footer {
  display: flex;
  justify-content: space-between; /* 两端对齐 */
  margin-top: 24px;
}

.left-items {
  display: flex;
  gap: 16px; /* 子元素之间的间距 */
  align-items: center; /* 垂直居中对齐 */
}

.pay-button {
  margin-left: auto; /* 推到最右边 */
}
button:hover {
  background-color: #0056b3;
}
/* 按钮统一改为背景色 #fcc0a，文字黑色 */
.el-button {
  background-color: #fccc0a !important;
  border-color: #fccc0a !important;
  color: #000 !important;
}

/* 按钮悬停和激活态稍微深一点（可选） */
.el-button:hover, .el-button:focus {
  background-color: #e6b208 !important;
  border-color: #e6b208 !important;
}

/* 对话框和购物车容器背景改为淡黄色 */
.el-dialog, .shopping-cart {
  background-color: #fff8e1 !important;
}
</style>