<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import MainLayout from "@/layouts/MainLayout.vue";
import { useUserStore } from "@/stores/UserStore.ts";
import {
  ElCard,
  ElRow,
  ElCol,
  ElImage,
  ElButton,
  // ElBreadcrumb,
  // ElBreadcrumbItem,
  ElCarousel,
  ElCarouselItem,
  ElDivider,
  ElIcon,
  ElMessage,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElRadioGroup,
  ElRadio,
} from "element-plus";
import { ArrowLeft, Plus, Minus } from "@element-plus/icons-vue";
import { getProductDetail } from "@/apis/product";
import type { ProductDetail, ProductSku } from "@/types/product";
import { addCart } from "@/apis/shoppingcart.ts";
import { createOrderDirectly } from "@/apis/order.ts";
import type { OrderCreateDTO } from "@/types/order.ts";

const route = useRoute();
const router = useRouter();

// 商品详情数据
const product = ref<ProductDetail | null>(null);
const loading = ref(true);

// 购买相关
const quantity = ref(1);
const selectedSku = ref<ProductSku | null>(null);

// 获取用户信息
const userStore = useUserStore();

// 订单对话框相关
const orderDialogVisible = ref(false);
const orderFormRef = ref();
const orderForm = ref({
  receiverName: "",
  receiverPhone: "",
  receiverAddress: "",
  payType: 1, // 默认微信支付
});

const orderFormRules = {
  receiverName: [
    { required: true, message: "请输入收货人姓名", trigger: "blur" },
  ],
  receiverPhone: [
    { required: true, message: "请输入收货人手机号", trigger: "blur" },
  ],
  receiverAddress: [
    { required: true, message: "请输入收货地址", trigger: "blur" },
  ],
};

// 获取商品详情
const fetchProductDetail = async () => {
  const productId = route.params.id as string;
  if (!productId) {
    ElMessage.error("商品ID无效");
    router.push("/product/product");
    return;
  }

  try {
    const response = await getProductDetail(Number(productId));
    if (response.code === 200) {
      product.value = response.data;

      // 默认选择第一个SKU
      if (response.data.skuList && response.data.skuList.length > 0) {
        selectedSku.value = response.data.skuList[0];
      }
    } else {
      ElMessage.error(response.message || "获取商品详情失败");
      router.push("/product");
    }
  } catch (error) {
    ElMessage.error("获取商品详情失败");
    console.error("获取商品详情失败:", error);
    router.push("/product");
  } finally {
    loading.value = false;
  }
};

// 增加数量
const increaseQuantity = () => {
  if (
    product.value &&
    quantity.value < (selectedSku.value?.stock || product.value.stock || 0)
  ) {
    quantity.value++;
  }
};

// 减少数量
const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--;
  }
};

// 添加到购物车
const addToCart = async () => {
  if (!product.value) {
    ElMessage.warning("商品信息加载中...");
    return;
  }

  if (!selectedSku.value) {
    ElMessage.warning("请选择商品规格");
    return;
  }

  // 检查用户是否已登录
  if (!userStore.userInfo) {
    ElMessage.warning("请先登录");
    router.push("/user/login");
    return;
  }

  try {
    const response = await addCart({
      userId: userStore.userInfo.id,
      productId: product.value.id,
      skuId: selectedSku.value.id,
      count: quantity.value,
    });

    if (response.code === 200) {
      ElMessage.success(`已将 ${product.value.name} 添加到购物车`);
    } else {
      ElMessage.error(response.message || "添加到购物车失败");
    }
  } catch (error) {
    ElMessage.error("添加到购物车失败");
    console.error("添加到购物车失败:", error);
  }
};

// 立即购买
const buyNow = () => {
  if (!product.value) {
    ElMessage.warning("商品信息加载中...");
    return;
  }

  if (!selectedSku.value) {
    ElMessage.warning("请选择商品规格");
    return;
  }

  // 检查用户是否已登录
  if (!userStore.userInfo) {
    ElMessage.warning("请先登录");
    router.push("/user/login");
    return;
  }

  // 显示订单对话框
  orderDialogVisible.value = true;

  // 初始化表单数据（如果用户有默认地址可以在这里填充）
  orderForm.value = {
    receiverName: "",
    receiverPhone: "",
    receiverAddress: "",
    payType: 1,
  };
};

// 提交订单
const submitOrder = async () => {
  if (!userStore.userInfo) {
    ElMessage.error("用户未登录");
    return;
  }

  if (!product.value || !selectedSku.value) {
    ElMessage.error("商品信息不完整");
    return;
  }

  try {
    await orderFormRef.value.validate();

    const orderData: OrderCreateDTO = {
      userId: userStore.userInfo.id,
      receiverName: orderForm.value.receiverName,
      receiverPhone: orderForm.value.receiverPhone,
      receiverAddress: orderForm.value.receiverAddress,
      payType: orderForm.value.payType,
    };

    // 使用直接购买接口
    const response = await createOrderDirectly(
      product.value.id,
      selectedSku.value.id,
      orderData,
    );

    if (response.code === 200) {
      ElMessage.success("订单创建成功");
      orderDialogVisible.value = false;

      // 跳转到订单页面
      router.push(`/order/content?orderId=${response.data.orderId}`);
    } else {
      ElMessage.error(response.message || "订单创建失败");
    }
  } catch (error) {
    console.error("创建订单失败:", error);
    ElMessage.error("创建订单失败");
  }
};

// 选择SKU
const selectSku = (sku: ProductSku) => {
  selectedSku.value = sku;
};

// 返回商品列表
const goBack = () => {
  router.push("/product");
};

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

<template>
  <MainLayout>
    <div class="product-detail-page">
      <div class="container mx-auto px-4 py-8">
        <!-- 返回按钮 -->
        <div class="mb-6">
          <el-button @click="goBack" type="primary" link>
            <el-icon><ArrowLeft /></el-icon>
            返回商品列表
          </el-button>
        </div>

        <el-card v-loading="loading" class="product-card">
          <div v-if="product">
            <el-row :gutter="30">
              <!-- 商品图片 -->
              <el-col :span="24" :md="12">
                <div class="product-images">
                  <!-- 主图轮播 -->
                  <el-carousel
                    height="400px"
                    indicator-position="outside"
                    arrow="always"
                  >
                    <el-carousel-item v-if="product.mainImage">
                      <el-image
                        :src="product.mainImage"
                        class="w-full h-full object-contain"
                        fit="contain"
                      />
                    </el-carousel-item>
                    <el-carousel-item
                      v-for="(image, index) in product.subImages?.split(',')"
                      :key="index"
                      v-show="image"
                    >
                      <el-image
                        :src="image"
                        class="w-full h-full object-contain"
                        fit="contain"
                      />
                    </el-carousel-item>
                  </el-carousel>
                </div>
              </el-col>

              <!-- 商品信息 -->
              <el-col :span="24" :md="12">
                <div class="product-info">
                  <h1 class="product-title text-2xl font-bold mb-4">
                    {{ product.name }}
                  </h1>
                  <p class="product-subtitle text-gray-600 mb-6">
                    {{ product.subtitle }}
                  </p>

                  <div class="price-section mb-6">
                    <div class="text-3xl text-red-600 font-bold">
                      ¥{{ selectedSku?.price || product.price }}
                    </div>
                    <div class="text-gray-500 line-through mt-1">
                      原价: ¥{{ product.price }}
                    </div>
                  </div>

                  <el-divider />

                  <!-- SKU选择 -->
                  <div
                    v-if="product.skuList && product.skuList.length > 0"
                    class="mb-6"
                  >
                    <div class="mb-3">
                      <span class="font-medium">规格:</span>
                    </div>
                    <div class="flex flex-wrap gap-3">
                      <el-button
                        v-for="sku in product.skuList"
                        :key="sku.id"
                        :type="selectedSku?.id === sku.id ? 'primary' : 'info'"
                        plain
                        @click="selectSku(sku)"
                      >
                        {{ sku.skuName }}
                      </el-button>
                    </div>
                  </div>

                  <!-- 数量选择 -->
                  <div class="quantity-section mb-6">
                    <div class="mb-3">
                      <span class="font-medium">数量:</span>
                    </div>
                    <div class="flex items-center">
                      <el-button
                        :disabled="quantity <= 1"
                        :icon="Minus"
                        @click="decreaseQuantity"
                      />
                      <div class="mx-3 w-12 text-center">{{ quantity }}</div>
                      <el-button
                        :disabled="
                          quantity >= (selectedSku?.stock || product.stock || 0)
                        "
                        :icon="Plus"
                        @click="increaseQuantity"
                      />
                      <div class="ml-4 text-gray-500">
                        剩余库存: {{ selectedSku?.stock || product.stock }}
                      </div>
                    </div>
                  </div>

                  <!-- 操作按钮 -->
                  <div class="action-buttons flex flex-wrap gap-4">
                    <el-button
                      type="primary"
                      size="large"
                      @click="addToCart"
                      class="flex-1 min-w-[150px]"
                    >
                      加入购物车
                    </el-button>
                    <el-button
                      type="danger"
                      size="large"
                      @click="buyNow"
                      class="flex-1 min-w-[150px]"
                    >
                      立即购买
                    </el-button>
                  </div>
                </div>
              </el-col>
            </el-row>

            <!-- 商品详情 -->
            <el-divider class="my-8" />

            <div class="product-description">
              <h2 class="text-xl font-bold mb-4">商品详情</h2>
              <div class="description-content p-4 bg-gray-50 rounded">
                <div
                  v-html="product.description || '暂无商品详情'"
                  class="prose max-w-none"
                ></div>
              </div>
            </div>
          </div>

          <div v-else-if="!loading" class="text-center py-12">
            <div class="text-gray-500">商品不存在或加载失败</div>
            <el-button @click="goBack" type="primary" class="mt-4"
              >返回商品列表</el-button
            >
          </div>
        </el-card>
      </div>
    </div>

    <!-- 订单确认对话框 -->
    <el-dialog
      v-model="orderDialogVisible"
      title="确认订单信息"
      width="500px"
      :before-close="
        () => {
          orderDialogVisible = false;
        }
      "
    >
      <el-form
        ref="orderFormRef"
        :model="orderForm"
        :rules="orderFormRules"
        label-width="100px"
      >
        <el-form-item label="收货人" prop="receiverName">
          <el-input
            v-model="orderForm.receiverName"
            placeholder="请输入收货人姓名"
          />
        </el-form-item>

        <el-form-item label="手机号" prop="receiverPhone">
          <el-input
            v-model="orderForm.receiverPhone"
            placeholder="请输入收货人手机号"
          />
        </el-form-item>

        <el-form-item label="收货地址" prop="receiverAddress">
          <el-input
            v-model="orderForm.receiverAddress"
            type="textarea"
            placeholder="请输入详细收货地址"
          />
        </el-form-item>

        <el-form-item label="支付方式" prop="payType">
          <el-radio-group v-model="orderForm.payType">
            <el-radio :label="1">微信支付</el-radio>
            <el-radio :label="2">支付宝</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="商品信息">
          <div v-if="product && selectedSku" class="product-summary">
            <div class="flex justify-between items-center">
              <div>
                <div>{{ product.name }} - {{ selectedSku.skuName }}</div>
                <div>数量: {{ quantity }}</div>
              </div>
              <div class="font-bold">
                ¥{{ (selectedSku.price * quantity).toFixed(2) }}
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="orderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOrder">提交订单</el-button>
        </div>
      </template>
    </el-dialog>
  </MainLayout>
</template>

<style scoped>
.product-detail-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.product-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-title {
  color: #333;
}

.product-subtitle {
  font-size: 16px;
}

.price-section {
  padding: 15px;
  background: #fff8f8;
  border-radius: 8px;
}

.quantity-section {
  padding: 15px;
  background: #f9f9f9;
  border-radius: 8px;
}

.action-buttons {
  margin-top: 30px;
}

:deep(.el-carousel__arrow) {
  background-color: rgba(255, 255, 255, 0.8);
  color: #333;
}

:deep(.el-carousel__arrow:hover) {
  background-color: rgba(255, 255, 255, 0.9);
}

:deep(.el-carousel__indicator:hover button) {
  background-color: #409eff;
}

:deep(.el-carousel__indicator.is-active button) {
  background-color: #409eff;
}

:deep(.el-divider--horizontal) {
  margin: 20px 0;
}

.description-content {
  min-height: 200px;
}

.product-summary {
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  background-color: #fafafa;
}
</style>
