<template>
  <div class="booth-page">
    <div class="booth-container">
      <!-- 操作栏（独立卡片） -->
      <div class="action-card">
        <el-button type="primary" icon="View" @click="handleViewProducts">查看推荐商品</el-button>
      </div>

      <!-- 商品展示区域（独立卡片） -->
      <div class="content-card" @mouseenter="stopAutoPlay" @mouseleave="startAutoPlay">
        <div class="product-display-area">
          <div class="carousel-viewport">
            <transition name="slide-fade" mode="out-in">
              <div class="product-grid" :key="currentPage">
                <div
                  v-for="product in displayProducts"
                  :key="product.id"
                  class="product-card"
                >
                  <el-icon class="delete-icon" @click="handleRemoveProduct(product.id)">
                    <Close />
                  </el-icon>
                  <div class="product-image">
                    <el-image
                      :src="product.imageUrl"
                      fit="cover"
                      lazy
                      class="image"
                    >
                      <template #error>
                        <div class="image-slot">
                          <el-icon><Picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                  </div>
                  <div class="product-info">
                    <p class="product-name">{{ product.name }}</p>
                    <p class="product-price">¥{{ product.price }}</p>
                  </div>
                </div>
              </div>
            </transition>
          </div>
        
          <!-- 导航箭头 -->
          <el-icon
            v-if="hasPrev"
            class="nav-arrow nav-arrow-left"
            @click="handlePrev"
          >
            <ArrowLeft />
          </el-icon>
          <el-icon
            v-if="hasNext"
            class="nav-arrow nav-arrow-right"
            @click="handleNext"
          >
            <ArrowRight />
          </el-icon>
        </div>

        <!-- 空状态 -->
        <el-empty v-if="displayProducts.length === 0" description="暂无商品，请点击查看推荐商品添加" />
      </div>
    </div>

    <!-- 已选商品对话框 -->
    <el-dialog
      v-model="dialog.visible"
      title="已选商品"
      width="900px"
      append-to-body
      destroy-on-close
      @close="handleDialogClose"
    >
      <!-- 操作按钮 -->
      <div class="dialog-actions mb-[10px]">
        <el-button type="primary" plain icon="Plus" @click="handleAddProduct">新增商品</el-button>
        <el-button type="primary" plain icon="Upload" @click="handleImportProduct">导入商品</el-button>
      </div>

      <!-- 商品表格 -->
      <el-table :data="selectedProducts" border max-height="450" style="width: 100%">
        <el-table-column label="商品编号" align="center" prop="id" width="100" />
        <el-table-column label="商品图片" align="center" width="80">
          <template #default="scope">
            <el-image
              :src="scope.row.imageUrl"
              fit="cover"
              style="width: 50px; height: 50px; border-radius: 4px"
              lazy
            >
              <template #error>
                <div class="image-slot-small">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="name" :show-overflow-tooltip="true" min-width="180" />
        <el-table-column label="价格" align="center" width="90">
          <template #default="scope">
            <span class="price-text">¥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" width="100">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.sort"
              :min="0"
              :max="999"
              controls-position="right"
              size="small"
              style="width: 80px"
              @change="handleSortChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="70">
          <template #default="scope">
            <span class="action-link danger" @click="handleDeleteProduct(scope.row.id)">删除</span>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleConfirm">确认</el-button>
          <el-button @click="handleDialogClose">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择轮播商品对话框 -->
    <el-dialog
      v-model="selectDialog.visible"
      title="选择轮播商品"
      width="1200px"
      append-to-body
      @close="handleSelectDialogClose"
    >
      <!-- 搜索栏 -->
      <div class="search-bar mb-[10px]">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入商品编号名称输入搜索"
          clearable
          style="width: 400px"
          @keyup.enter="handleSearchProducts"
        >
          <template #append>
            <el-button icon="Search" @click="handleSearchProducts">搜索</el-button>
          </template>
        </el-input>
      </div>

      <!-- 商品表格 -->
      <el-table
        ref="newProductTableRef"
        :data="filteredAvailableProducts"
        border
        max-height="500"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="轮播商品编号" align="center" prop="id" width="150" />
        <el-table-column label="轮播商品图片" align="center" width="120">
          <template #default="scope">
            <el-image
              :src="scope.row.imageUrl"
              fit="cover"
              style="width: 80px; height: 80px; border-radius: 4px"
              lazy
            >
              <template #error>
                <div class="image-slot-small">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="轮播商品名称" align="center" prop="name" :show-overflow-tooltip="true" min-width="300" />
        <el-table-column label="价格" align="center" prop="price" width="120">
          <template #default="scope">
            <span class="price-text">¥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="newProductPagination.total > 0"
        v-model:page="newProductPagination.pageNum"
        v-model:limit="newProductPagination.pageSize"
        :total="newProductPagination.total"
        @pagination="loadAvailableProducts"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleConfirmSelect">确认</el-button>
          <el-button @click="handleSelectDialogClose">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入商品对话框 -->
    <el-dialog
      v-model="importDialog.visible"
      title="导入商品(商品编号逗号隔开)"
      width="600px"
      append-to-body
      destroy-on-close
      @close="handleImportDialogClose"
    >
      <el-form label-width="80px">
        <el-form-item label="商品编号:">
          <el-input
            v-model="importProductIds"
            type="textarea"
            :rows="6"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleConfirmImport">确 认</el-button>
          <el-button @click="handleImportDialogClose">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="IndustrialBooth" lang="ts">
import { ref, reactive, computed, watch, nextTick, onMounted, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Close, Picture, ArrowLeft, ArrowRight } from '@element-plus/icons-vue';
import { listProduct } from '@/api/product/base';
import { listRecommend, listRecommendLink, addRecommendLink, delRecommendLink } from '@/api/product/recommend';

// 推荐位编号（工业装修-轮播展位商品）
const recommendNo = 'industrial_booth';
const recommendId = ref<number | null>(null);
const loading = ref(false);

// 对话框
const dialog = reactive({
  visible: false
});

// 选择商品对话框
const selectDialog = reactive({
  visible: false
});

// 导入商品对话框
const importDialog = reactive({
  visible: false
});

// 导入商品编号
const importProductIds = ref('');

// 搜索关键词
const searchKeyword = ref('');

// 可选商品列表（从接口获取）
const availableProducts = ref<any[]>([]);

// 选中的商品ID列表（用于新增商品标签页）
const selectedProductIds = ref<string[]>([]);

// 新增商品分页
const newProductPagination = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0
});

// 当前页码（从0开始）
const currentPage = ref(0);
const pageSize = 5; // 每页显示5个商品

// 自动轮播定时器
let autoPlayTimer: ReturnType<typeof setInterval> | null = null;
const autoPlayInterval = 3000; // 3秒切换一次

// 已选商品列表（从接口获取）
const selectedProducts = ref<any[]>([]);

// 获取可选商品列表
const loadAvailableProducts = async () => {
  try {
    const params: any = {
      pageNum: newProductPagination.pageNum,
      pageSize: newProductPagination.pageSize
    };
    if (searchKeyword.value) {
      params.itemName = searchKeyword.value;
    }
    const res: any = await listProduct(params);
    // 字段映射
    availableProducts.value = (res.rows || []).map((item: any) => ({
      id: item.id,
      productNo: item.productNo,
      name: item.itemName,
      imageUrl: item.productImageUrl || item.productImage,
      price: item.minSellingPrice || item.memberPrice || '0.00'
    }));
    newProductPagination.total = res.total || 0;
  } catch (error) {
    console.error('获取商品列表失败', error);
    availableProducts.value = [];
  }
};

// 获取推荐位ID
const loadRecommendId = async () => {
  try {
    const res: any = await listRecommend({ recommendNo, pageSize: 1 });
    if (res.rows && res.rows.length > 0) {
      recommendId.value = res.rows[0].id;
    }
  } catch (error) {
    console.error('获取推荐位失败', error);
  }
};

// 获取已选商品列表（通过推荐关联）
const loadSelectedProducts = async () => {
  loading.value = true;
  try {
    if (!recommendId.value) {
      await loadRecommendId();
    }
    if (!recommendId.value) {
      selectedProducts.value = [];
      return;
    }
    // 先获取推荐关联的商品ID列表
    const linkRes: any = await listRecommendLink({ recommendId: recommendId.value, pageSize: 100 });
    const links = linkRes.rows || [];
    if (links.length === 0) {
      selectedProducts.value = [];
      return;
    }
    // 获取商品详情
    const productIds = links.map((link: any) => link.productId);
    const productRes: any = await listProduct({ ids: productIds.join(','), pageSize: 100 });
    const productMap = new Map((productRes.rows || []).map((p: any) => [p.id, p]));
    // 组装数据
    selectedProducts.value = links.map((link: any, index: number) => {
      const product: any = productMap.get(link.productId) || {};
      return {
        id: product.id || link.productId,
        linkId: link.id, // 关联ID，用于删除
        productNo: product.productNo,
        name: product.itemName || `商品${link.productId}`,
        imageUrl: product.productImageUrl || product.productImage,
        price: product.minSellingPrice || product.memberPrice || '0.00',
        sort: links.length - index // 默认排序
      };
    });
  } catch (error) {
    console.error('获取已选商品失败', error);
    selectedProducts.value = [];
  } finally {
    loading.value = false;
  }
};

// 计算当前显示的商品（按排序值降序排列）
const sortedProducts = computed(() => {
  return [...selectedProducts.value].sort((a, b) => b.sort - a.sort);
});

// 总页数
const totalPages = computed(() => {
  return Math.ceil(sortedProducts.value.length / pageSize);
});

// 当前页显示的商品
const displayProducts = computed(() => {
  const start = currentPage.value * pageSize;
  const end = start + pageSize;
  return sortedProducts.value.slice(start, end);
});

// 是否有上一页
const hasPrev = computed(() => {
  return currentPage.value > 0;
});

// 是否有下一页
const hasNext = computed(() => {
  return currentPage.value < totalPages.value - 1;
});

// 查看推荐商品
const handleViewProducts = async () => {
  dialog.visible = true;
  // 每次打开都重新加载数据
  await loadSelectedProducts();
};

// 对话框关闭
const handleDialogClose = () => {
  dialog.visible = false;
};

// 新增商品
const handleAddProduct = () => {
  selectDialog.visible = true;
  selectedProductIds.value = [];
  searchKeyword.value = '';
  newProductPagination.pageNum = 1;
  // 加载可选商品列表
  loadAvailableProducts();
  // 等待DOM更新后，清除表格选中状态
  nextTick(() => {
    if (newProductTableRef.value) {
      newProductTableRef.value.clearSelection();
    }
  });
};

// 选择商品对话框关闭
const handleSelectDialogClose = () => {
  selectDialog.visible = false;
  selectedProductIds.value = [];
  searchKeyword.value = '';
  // 清除表格选中状态
  if (newProductTableRef.value) {
    newProductTableRef.value.clearSelection();
  }
};

// 搜索商品
const handleSearchProducts = () => {
  newProductPagination.pageNum = 1;
  loadAvailableProducts();
};

// 表格选择变化
const newProductTableRef = ref();
const handleSelectionChange = (selection: any[]) => {
  selectedProductIds.value = selection.map((item) => item.id);
};


// 确认选择商品
const handleConfirmSelect = async () => {
  if (selectedProductIds.value.length === 0) {
    ElMessage.warning('请至少选择一个商品');
    return;
  }

  try {
    if (!recommendId.value) {
      await loadRecommendId();
    }
    if (!recommendId.value) {
      ElMessage.error('推荐位不存在，请先创建');
      return;
    }
    // 批量添加推荐关联，统计实际添加数量
    let addedCount = 0;
    let skippedCount = 0;
    for (const productId of selectedProductIds.value) {
      // 检查是否已存在
      if (selectedProducts.value.find((p) => String(p.id) === String(productId))) {
        skippedCount++;
      } else {
        await addRecommendLink({ recommendId: recommendId.value, productId });
        addedCount++;
      }
    }
    if (addedCount > 0) {
      ElMessage.success(`成功添加 ${addedCount} 个商品${skippedCount > 0 ? `，${skippedCount} 个已存在被跳过` : ''}`);
    } else {
      ElMessage.warning('所选商品均已存在');
    }
    handleSelectDialogClose();
    // 刷新已选列表
    await loadSelectedProducts();
  } catch (error) {
    ElMessage.error('添加失败');
  }
};

// 分页后的可选商品列表（过滤掉已选的商品）
const filteredAvailableProducts = computed(() => {
  const selectedIds = selectedProducts.value.map((p) => String(p.id));
  return availableProducts.value.filter((item) => !selectedIds.includes(String(item.id)));
});

// 分页变化
watch(
  () => [newProductPagination.pageNum, newProductPagination.pageSize],
  () => {
    if (selectDialog.visible) {
      loadAvailableProducts();
    }
  }
);


// 导入商品
const handleImportProduct = () => {
  importDialog.visible = true;
  importProductIds.value = '';
};

// 导入对话框关闭
const handleImportDialogClose = () => {
  importDialog.visible = false;
  importProductIds.value = '';
};

// 确认导入商品
const handleConfirmImport = () => {
  if (!importProductIds.value.trim()) {
    ElMessage.warning('请输入商品编号');
    return;
  }

  // 解析商品编号（逗号隔开）
  const ids = importProductIds.value
    .split(/[,，]/)
    .map((id) => id.trim())
    .filter((id) => id);

  if (ids.length === 0) {
    ElMessage.warning('请输入有效的商品编号');
    return;
  }

  // 模拟导入逻辑（实际应调用接口查询商品信息）
  let addedCount = 0;
  ids.forEach((id) => {
    // 检查是否已存在
    if (!selectedProducts.value.find((p) => p.id === id)) {
      // 模拟添加商品（实际应从接口获取商品信息）
      selectedProducts.value.push({
        id: id,
        name: `商品${id}`,
        imageUrl: `https://via.placeholder.com/200x200/409EFF/FFFFFF?text=${id}`,
        price: '0.00',
        sort: Math.max(...selectedProducts.value.map((p) => p.sort), 0) + 1
      });
      addedCount++;
    }
  });

  if (addedCount > 0) {
    ElMessage.success(`成功导入 ${addedCount} 个商品`);
  } else {
    ElMessage.warning('所有商品编号已存在');
  }
  handleImportDialogClose();
};

// 删除商品
const handleDeleteProduct = (id: string) => {
  const product = selectedProducts.value.find((item) => String(item.id) === String(id));
  ElMessageBox.confirm('是否确认删除该商品？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        if (product?.linkId) {
          await delRecommendLink(product.linkId);
        }
        const index = selectedProducts.value.findIndex((item) => String(item.id) === String(id));
        if (index !== -1) {
          selectedProducts.value.splice(index, 1);
        }
        ElMessage.success('删除成功');
        // 调整页码确保不越界
        if (currentPage.value >= totalPages.value && currentPage.value > 0) {
          currentPage.value = totalPages.value - 1;
        }
      } catch (error) {
        ElMessage.error('删除失败');
      }
    })
    .catch(() => {});
};

// 排序改变
const handleSortChange = (row: any) => {
  // 排序值改变后，重新计算显示的商品
  console.log('排序值改变:', row);
};

// 确认
const handleConfirm = () => {
  ElMessage.success('保存成功');
  dialog.visible = false;
};

// 上一页
const handlePrev = () => {
  if (hasPrev.value) {
    currentPage.value--;
  }
};

// 下一页
const handleNext = () => {
  if (hasNext.value) {
    currentPage.value++;
  }
};

// 移除商品（从展示区域移除）
const handleRemoveProduct = (id: string) => {
  const product = selectedProducts.value.find((item) => String(item.id) === String(id));
  ElMessageBox.confirm('是否确认从展示区域移除该商品？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        if (product?.linkId) {
          await delRecommendLink(product.linkId);
        }
        const index = selectedProducts.value.findIndex((item) => String(item.id) === String(id));
        if (index !== -1) {
          selectedProducts.value.splice(index, 1);
        }
        ElMessage.success('移除成功');
        // 调整页码确保不越界
        if (currentPage.value >= totalPages.value && currentPage.value > 0) {
          currentPage.value = totalPages.value - 1;
        }
      } catch (error) {
        ElMessage.error('移除失败');
      }
    })
    .catch(() => {});
};

// 开始自动轮播
const startAutoPlay = () => {
  stopAutoPlay();
  if (totalPages.value <= 1) return;
  
  autoPlayTimer = setInterval(() => {
    if (totalPages.value <= 1) {
      stopAutoPlay();
      return;
    }
    // 循环播放：1 -> 2 -> 1 -> 2
    if (currentPage.value >= totalPages.value - 1) {
      currentPage.value = 0;
    } else {
      currentPage.value++;
    }
  }, autoPlayInterval);
};

// 停止自动轮播
const stopAutoPlay = () => {
  if (autoPlayTimer) {
    clearInterval(autoPlayTimer);
    autoPlayTimer = null;
  }
};

onMounted(() => {
  // 加载已选商品
  loadSelectedProducts();
  // 启动自动轮播
  startAutoPlay();
});

onUnmounted(() => {
  // 清理定时器
  stopAutoPlay();
});
</script>

<style scoped lang="scss">
.booth-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px;
}

.booth-container {
  max-width: 1200px;
  margin: 0 auto;
}

.action-card {
  background: #fff;
  border-radius: 4px;
  padding: 15px 20px;
  margin-bottom: 12px;
}

.content-card {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

.product-display-area {
  position: relative;
  min-height: 400px;
  padding: 20px 0;
}

.carousel-viewport {
  margin: 0 40px;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
}

// 滑动过渡动画
.slide-fade-enter-active {
  transition: all 0.4s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s ease-in;
}

.slide-fade-enter-from {
  transform: translateX(30px);
  opacity: 0;
}

.slide-fade-leave-to {
  transform: translateX(-30px);
  opacity: 0;
}

.product-card {
  position: relative;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }

  .delete-icon {
    position: absolute;
    top: 8px;
    right: 8px;
    font-size: 18px;
    color: #909399;
    cursor: pointer;
    z-index: 10;
    background: rgba(255, 255, 255, 0.8);
    border-radius: 50%;
    padding: 4px;
    transition: all 0.3s;

    &:hover {
      color: #f56c6c;
      background: rgba(255, 255, 255, 1);
    }
  }

  .product-image {
    width: 100%;
    height: 180px;
    margin-bottom: 12px;
    background: #f5f7fa;
    border-radius: 4px;
    overflow: hidden;

    .image {
      width: 100%;
      height: 100%;
    }

    .image-slot {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      background: #f5f7fa;
      color: #909399;
      font-size: 40px;
    }
  }

  .product-info {
    .product-name {
      margin: 0 0 8px 0;
      font-size: 13px;
      color: #303133;
      line-height: 1.5;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      min-height: 39px;
    }

    .product-price {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #f56c6c;
    }
  }
}

.nav-arrow {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  font-size: 32px;
  color: #909399;
  cursor: pointer;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  padding: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: all 0.3s;
  z-index: 10;

  &:hover {
    color: #409eff;
    background: #fff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  }

  &.nav-arrow-left {
    left: 10px;
  }

  &.nav-arrow-right {
    right: 10px;
  }
}

.dialog-actions {
  display: flex;
  gap: 10px;
}

.image-slot-small {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.price-text {
  color: #f56c6c;
  font-weight: 600;
}

.search-bar {
  display: flex;
  align-items: center;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

.action-link {
  cursor: pointer;
  font-size: 14px;
  
  &.danger {
    color: #f56c6c;
    
    &:hover {
      color: #f78989;
    }
  }
}
</style>
