<template>
  <MainLayout>
    <div class="shopping-cart-page">
      <el-card class="cart-card">
        <template #header>
          <div class="cart-header">
            <span>购物车</span>
            <el-button
              type="danger"
              :disabled="!hasSelectedItems"
              @click="handleClearSelected"
            >
              删除选中商品
            </el-button>
          </div>
        </template>

        <div v-if="cartItems.length === 0" class="empty-cart">
          <el-empty description="购物车为空" />
        </div>

        <div v-else>
          <!-- 全选栏 -->
          <div class="select-all">
            <el-checkbox v-model="selectAll" @change="handleSelectAllChange">
              全选
            </el-checkbox>
            <div class="cart-summary">
              <span>已选 {{ selectedCount }} 件商品</span>
              <span class="total-price"
                >合计：¥{{ totalPrice.toFixed(2) }}</span
              >
              <el-button
                type="primary"
                :disabled="selectedCount === 0"
                @click="handleCheckout"
              >
                结算
              </el-button>
            </div>
          </div>

          <!-- 购物车商品列表 -->
          <div class="cart-items">
            <el-table :data="cartItems" style="width: 100%" row-key="id">
              <el-table-column
                class-name="col-checkbox"
                width="60"
                prop="checked"
              >
                <template #default="scope">
                  <el-checkbox
                    v-model="scope.row.checked"
                    :true-value="1"
                    :false-value="0"
                    @change="
                      (val: boolean | string | number) =>
                        handleItemCheckChange(scope.row, val)
                    "
                  />
                </template>
              </el-table-column>

              <el-table-column
                prop="productImage"
                label="商品"
                class-name="col-product"
                min-width="280"
              >
                <template #default="scope">
                  <div class="product-info">
                    <el-image
                      :src="scope.row.productImage"
                      class="product-image"
                      fit="cover"
                    />
                    <div class="product-details">
                      <div class="product-name">
                        {{ scope.row.productName }}
                      </div>
                      <div class="product-sku">{{ scope.row.skuName }}</div>
                    </div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="price" label="单价" min-width="100">
                <template #default="scope"> ¥{{ scope.row.price }} </template>
              </el-table-column>

              <el-table-column prop="count" label="数量" min-width="120">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.count"
                    :min="1"
                    :max="999"
                    @change="
                      (val: number | undefined) =>
                        handleCountChange(scope.row, val)
                    "
                  />
                </template>
              </el-table-column>

              <el-table-column prop="subtotal" label="小计" min-width="120">
                <template #default="scope">
                  ¥{{ (scope.row.price * scope.row.count).toFixed(2) }}
                </template>
              </el-table-column>

              <el-table-column label="操作" min-width="80">
                <template #default="scope">
                  <el-button
                    type="danger"
                    link
                    @click="handleDeleteItem(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 结算对话框 -->
    <el-dialog
      v-model="checkoutDialogVisible"
      title="确认订单信息"
      width="500px"
    >
      <el-form
        ref="checkoutFormRef"
        :model="checkoutForm"
        :rules="checkoutRules"
        label-width="80px"
      >
        <el-form-item label="收货人" prop="receiverName">
          <el-input v-model="checkoutForm.receiverName" />
        </el-form-item>

        <el-form-item label="联系电话" prop="receiverPhone">
          <el-input v-model="checkoutForm.receiverPhone" />
        </el-form-item>

        <el-form-item label="收货地址" prop="receiverAddress">
          <el-input v-model="checkoutForm.receiverAddress" type="textarea" />
        </el-form-item>

        <el-form-item label="支付方式" prop="payType">
          <el-select
            v-model="checkoutForm.payType"
            placeholder="请选择支付方式"
          >
            <el-option label="微信支付" :value="1" />
            <el-option label="支付宝" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="商品总数">
          <span>{{ selectedCount }} 件</span>
        </el-form-item>

        <el-form-item label="订单总额">
          <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="checkoutDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitOrder"
            :loading="isSubmitting"
          >
            提交订单
          </el-button>
        </span>
      </template>
    </el-dialog>
  </MainLayout>
</template>

<script setup lang="ts">
import MainLayout from "@/layouts/MainLayout.vue";
import { ref, computed, onMounted } from "vue";
import { useUserStore } from "@/stores/UserStore";
import {
  getUserCartList,
  updateCartCount,
  updateCartChecked,
  deleteCart,
} from "@/apis/shoppingcart";
import { createOrder } from "@/apis/order";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { useRouter } from "vue-router";

interface CartItem {
  id: number;
  userId: number;
  productId: number;
  skuId: number;
  count: number;
  checked: number; // 0-未勾选 1-已勾选
  productName: string;
  productImage: string;
  skuName: string;
  price: number;
  specJson: string;
}

const userStore = useUserStore();
const router = useRouter();
const cartItems = ref<CartItem[]>([]);

// 结算相关
const checkoutDialogVisible = ref(false);
const checkoutFormRef = ref<FormInstance>();
const isSubmitting = ref(false);

const checkoutForm = ref({
  receiverName: "",
  receiverPhone: "",
  receiverAddress: "",
  payType: 1, // 默认微信支付
});

const checkoutRules = {
  receiverName: [
    { required: true, message: "请输入收货人姓名", trigger: "blur" },
  ],
  receiverPhone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  receiverAddress: [
    { required: true, message: "请输入收货地址", trigger: "blur" },
  ],
  payType: [{ required: true, message: "请选择支付方式", trigger: "change" }],
};

// 计算属性
const selectAll = computed({
  get: () =>
    cartItems.value.length > 0 &&
    cartItems.value.every((item) => item.checked === 1),
  set: (val) => {
    cartItems.value.forEach((item) => {
      item.checked = val ? 1 : 0;
    });
  },
});

const selectedItems = computed(() => {
  return cartItems.value.filter((item) => item.checked === 1);
});

const hasSelectedItems = computed(() => {
  return selectedItems.value.length > 0;
});

const selectedCount = computed(() => {
  return selectedItems.value.reduce((total, item) => total + item.count, 0);
});

const totalPrice = computed(() => {
  return selectedItems.value.reduce(
    (total, item) => total + item.price * item.count,
    0,
  );
});

// 获取购物车列表
const loadCartItems = async () => {
  if (!userStore.userInfo) {
    ElMessage.warning("请先登录");
    return;
  }

  try {
    const res = await getUserCartList(userStore.userInfo.id);
    if (res.code === 200) {
      cartItems.value = res.data.map((item) => ({
        ...item,
        checked: 0, // 默认不选中
      }));
    } else {
      ElMessage.error(res.message || "获取购物车列表失败");
    }
  } catch (err) {
    console.error(err);
    ElMessage.error("获取购物车列表失败");
  }
};

// 处理全选变化
const handleSelectAllChange = async (val: boolean) => {
  if (!userStore.userInfo) return;

  // 更新所有项目的选中状态
  for (const item of cartItems.value) {
    try {
      await updateCartChecked({
        id: item.id,
        userId: userStore.userInfo.id,
        productId: item.productId,
        skuId: item.skuId,
        checked: val ? 1 : 0,
      });
      item.checked = val ? 1 : 0;
    } catch (err) {
      console.error(err);
      ElMessage.error("更新选中状态失败");
    }
  }

  ElMessage.success(val ? "已全选" : "已取消全选");
};

// 处理单项选中变化
const handleItemCheckChange = async (
  item: CartItem,
  val: boolean | string | number,
) => {
  if (!userStore.userInfo) return;

  try {
    await updateCartChecked({
      id: item.id,
      userId: userStore.userInfo.id,
      productId: item.productId,
      skuId: item.skuId,
      checked: val ? 1 : 0,
    });

    item.checked = val ? 1 : 0;
  } catch (err) {
    console.error(err);
    ElMessage.error("更新选中状态失败");
    // 恢复原状态
    item.checked = !val ? 1 : 0;
  }
};

// 处理数量变化
const handleCountChange = async (item: CartItem, val: number | undefined) => {
  if (!userStore.userInfo || val === undefined) return;

  const oldCount = item.count; // 保存原始数量
  try {
    await updateCartCount({
      id: item.id,
      userId: userStore.userInfo.id,
      productId: item.productId,
      skuId: item.skuId,
      count: val,
    });

    item.count = val;
    ElMessage.success("数量更新成功");
  } catch (err) {
    console.error(err);
    ElMessage.error("更新数量失败");
    // 恢复原数量
    item.count = oldCount;
  }
};

// 处理删除单个项目
const handleDeleteItem = async (item: CartItem) => {
  if (!userStore.userInfo) return;

  ElMessageBox.confirm("确定要删除该商品吗？", "提示", {
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await deleteCart(item.id, userStore.userInfo!.id);
        if (res.code === 200) {
          ElMessage.success("删除成功");
          // 从列表中移除
          cartItems.value = cartItems.value.filter(
            (cartItem) => cartItem.id !== item.id,
          );
        } else {
          ElMessage.error(res.message || "删除失败");
        }
      } catch (err) {
        console.error(err);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 处理清空选中项
const handleClearSelected = async () => {
  if (!userStore.userInfo) return;

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedCount.value} 件商品吗？`,
    "提示",
    {
      type: "warning",
    },
  )
    .then(async () => {
      try {
        // 删除所有选中项
        const deletePromises = selectedItems.value.map((item) =>
          deleteCart(item.id, userStore.userInfo!.id),
        );

        await Promise.all(deletePromises);

        ElMessage.success("删除成功");
        // 从列表中移除
        cartItems.value = cartItems.value.filter((item) => item.checked !== 1);
      } catch (err) {
        console.error(err);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 处理结算
const handleCheckout = () => {
  if (!userStore.userInfo) {
    ElMessage.warning("请先登录");
    return;
  }

  if (selectedItems.value.length === 0) {
    ElMessage.warning("请选择要结算的商品");
    return;
  }

  // 初始化表单数据
  checkoutForm.value = {
    receiverName: "",
    receiverPhone: "",
    receiverAddress: "",
    payType: 1,
  };

  checkoutDialogVisible.value = true;
};

// 提交订单
const submitOrder = async () => {
  if (!userStore.userInfo) {
    ElMessage.warning("请先登录");
    return;
  }

  if (!checkoutFormRef.value) return;

  await checkoutFormRef.value.validate(async (valid) => {
    if (!valid) return;

    isSubmitting.value = true;

    try {
      const orderData = {
        userId: userStore.userInfo!.id,
        receiverName: checkoutForm.value.receiverName,
        receiverPhone: checkoutForm.value.receiverPhone,
        receiverAddress: checkoutForm.value.receiverAddress,
        payType: checkoutForm.value.payType,
      };

      const res = await createOrder(orderData);

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

        // 从购物车中移除已下单的商品
        cartItems.value = cartItems.value.filter((item) => item.checked !== 1);

        // 跳转到订单页面
        router.push("/order/content");
      } else {
        ElMessage.error(res.message || "订单创建失败");
      }
    } catch (err) {
      console.error(err);
      ElMessage.error("订单创建失败");
    } finally {
      isSubmitting.value = false;
    }
  });
};

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

<style scoped>
.shopping-cart-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-cart {
  text-align: center;
  padding: 40px 0;
}

.select-all {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.cart-summary {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #ff4444;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}

.product-details {
  flex: 1;
}

.product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.product-sku {
  color: #999;
  font-size: 12px;
}

.cart-items {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
