<template>
  <div class="booth-container">
    <el-card shadow="hover">
      <!-- 操作栏 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="View" @click="handleViewProducts">查看推荐商品</el-button>
        </el-col>
      </el-row>

      <!-- 商品展示区域 -->
      <div class="product-display-area">
        <div class="product-grid">
          <div
            v-for="(product, index) 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>
        
        <!-- 导航箭头 -->
        <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="暂无商品，请点击查看推荐商品添加" />
    </el-card>

    <!-- 已选商品对话框 -->
    <el-dialog
      v-model="dialog.visible"
      title="已选商品"
      width="1000px"
      append-to-body
      @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="500">
        <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-column label="排序(值越大排越前)" align="center" width="200">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.sort"
              :min="0"
              :max="999"
              controls-position="right"
              style="width: 100%"
              @change="handleSortChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <el-button link type="danger" icon="Delete" @click="handleDeleteProduct(scope.row.id)">删除</el-button>
          </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="filteredProducts.length > 0"
        v-model:page="newProductPagination.pageNum"
        v-model:limit="newProductPagination.pageSize"
        :total="filteredProducts.length"
        @pagination="() => {}"
      />

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

<script setup name="IndustrialBooth" lang="ts">
import { ref, reactive, computed, watch, nextTick, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Close, Picture, ArrowLeft, ArrowRight, View, Plus, Upload } from '@element-plus/icons-vue';

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

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

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

// 可选商品列表（模拟数据）
const availableProducts = ref([
  {
    id: '002169823',
    name: '江润双色塑钢培训椅',
    imageUrl: 'https://via.placeholder.com/200x200/87CEEB/FFFFFF?text=培训椅',
    price: '299.00'
  },
  {
    id: '002169822',
    name: '江润培训桌700*550*750mm',
    imageUrl: 'https://via.placeholder.com/200x200/000000/FFFFFF?text=培训桌',
    price: '799.00'
  },
  {
    id: '002169821',
    name: '江润六边形折叠培训桌 800*500*750mm (直径 1.6m)',
    imageUrl: 'https://via.placeholder.com/200x200/FFFFFF/000000?text=折叠桌',
    price: '699.00'
  },
  {
    id: '002169820',
    name: '梦洁200*230cm锦玉梦韵四件套',
    imageUrl: 'https://via.placeholder.com/200x200/4169E1/FFFFFF?text=四件套',
    price: '1299.00'
  },
  {
    id: '002169819',
    name: '洁丽雅纯棉四件套2*2.3M',
    imageUrl: 'https://via.placeholder.com/200x200/FFFFFF/000000?text=纯棉',
    price: '249.00'
  },
  {
    id: '002169818',
    name: '润实验台2000*750*800mm',
    imageUrl: 'https://via.placeholder.com/200x200/808080/FFFFFF?text=实验台',
    price: '3699.00'
  },
  {
    id: '002169817',
    name: '工业级安全防护手套 防割防滑',
    imageUrl: 'https://via.placeholder.com/200x200/FF6347/FFFFFF?text=手套',
    price: '45.00'
  },
  {
    id: '002169816',
    name: '专业级电钻套装 多功能工具箱',
    imageUrl: 'https://via.placeholder.com/200x200/FFD700/000000?text=电钻',
    price: '599.00'
  }
]);

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

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

// 已选商品分页
const selectedProductPagination = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0
});

// 当前显示的商品索引
const currentIndex = ref(0);
const pageSize = ref(5); // 每页显示5个商品

// 模拟数据 - 已选商品列表
const selectedProducts = ref([
  {
    id: '000294732',
    name: 'VICTOR/胜利 温度校验仪VC02+不支持第三方检定1台',
    imageUrl: 'https://via.placeholder.com/200x200/FFD700/000000?text=VC02+',
    price: '1997.00',
    sort: 9
  },
  {
    id: '000130005',
    name: 'CJ/超佳聚氨酯泡沫胶填缝剂 A2料 750mL(900g) 1罐',
    imageUrl: 'https://via.placeholder.com/200x200/DC143C/FFFFFF?text=CJ',
    price: '26.00',
    sort: 8
  },
  {
    id: '000371498',
    name: 'STANLEY/史丹利公制T形球头内六角扳手 94-288-23 4mm 1支',
    imageUrl: 'https://via.placeholder.com/200x200/FFD700/000000?text=STANLEY',
    price: '26.00',
    sort: 7
  },
  {
    id: '000207453',
    name: 'AIRTAC/亚德客 4V200系列电磁阀 4V21008B 两位五通 DIN插座式接口 Rc1/4 DC24V 1个',
    imageUrl: 'https://via.placeholder.com/200x200/808080/FFFFFF?text=AIRTAC',
    price: '77.00',
    sort: 6
  },
  {
    id: '000359317',
    name: 'CNFB/桥防 246系利铝青钢防爆克丝钳 T8246-1006-AL 8" 1把',
    imageUrl: 'https://via.placeholder.com/200x200/DC143C/FFFFFF?text=CNFB',
    price: '410.00',
    sort: 5
  },
  {
    id: '000123456',
    name: 'DELIXI/德力西 DZ47sLE小型漏保护断路器 DZ47sLE 2P C 32A',
    imageUrl: 'https://via.placeholder.com/200x200/FFFFFF/000000?text=DELIXI',
    price: '38.00',
    sort: 4
  },
  {
    id: '000789012',
    name: '工业级安全帽 白色 ABS材质 1顶',
    imageUrl: 'https://via.placeholder.com/200x200/FFFFFF/000000?text=安全帽',
    price: '45.00',
    sort: 3
  }
]);

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

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

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

// 是否有下一页
const hasNext = computed(() => {
  const totalPages = Math.ceil(sortedProducts.value.length / pageSize.value);
  return currentIndex.value < totalPages - 1;
});

// 查看推荐商品
const handleViewProducts = () => {
  dialog.visible = true;
};

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

// 新增商品
const handleAddProduct = () => {
  selectDialog.visible = true;
  selectedProductIds.value = [];
  searchKeyword.value = '';
  newProductPagination.pageNum = 1;
  // 等待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;
  // 这里可以调用搜索接口
  ElMessage.success('搜索功能开发中...');
};

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


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

  // 添加选中的商品到已选列表
  selectedProductIds.value.forEach((id) => {
    const product = availableProducts.value.find((p) => p.id === id);
    if (product && !selectedProducts.value.find((p) => p.id === id)) {
      selectedProducts.value.push({
        ...product,
        sort: Math.max(...selectedProducts.value.map((p) => p.sort), 0) + 1
      });
    }
  });

  ElMessage.success(`成功添加 ${selectedProductIds.value.length} 个商品`);
  handleSelectDialogClose();
};

// 过滤后的可选商品列表（不分页，用于搜索）
const filteredProducts = computed(() => {
  let products = [...availableProducts.value];
  
  // 根据搜索关键词过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    products = products.filter(
      (p) =>
        p.id.toLowerCase().includes(keyword) ||
        p.name.toLowerCase().includes(keyword)
    );
  }

  return products;
});

// 分页后的可选商品列表
const filteredAvailableProducts = computed(() => {
  const start = (newProductPagination.pageNum - 1) * newProductPagination.pageSize;
  const end = start + newProductPagination.pageSize;
  return filteredProducts.value.slice(start, end);
});

// 更新分页总数
watch(
  () => filteredProducts.value.length,
  (newTotal) => {
    newProductPagination.total = newTotal;
  },
  { immediate: true }
);


// 导入商品
const handleImportProduct = () => {
  ElMessage.info('导入商品功能开发中...');
};

// 删除商品
const handleDeleteProduct = (id: string) => {
  ElMessageBox.confirm('是否确认删除该商品？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      const index = selectedProducts.value.findIndex((item) => item.id === id);
      if (index !== -1) {
        selectedProducts.value.splice(index, 1);
        ElMessage.success('删除成功');
        // 如果当前页没有商品了，回到上一页
        if (displayProducts.value.length === 0 && currentIndex.value > 0) {
          currentIndex.value--;
        }
      }
    })
    .catch(() => {});
};

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

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

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

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

// 移除商品（从展示区域移除）
const handleRemoveProduct = (id: string) => {
  ElMessageBox.confirm('是否确认从展示区域移除该商品？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      const index = selectedProducts.value.findIndex((item) => item.id === id);
      if (index !== -1) {
        selectedProducts.value.splice(index, 1);
        ElMessage.success('移除成功');
        // 如果当前页没有商品了，回到上一页
        if (displayProducts.value.length === 0 && currentIndex.value > 0) {
          currentIndex.value--;
        }
      }
    })
    .catch(() => {});
};

onMounted(() => {
  // 初始化
});
</script>

<style scoped lang="scss">
.booth-container {
  height: 100%;
}

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

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

.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;
}

</style>
