<template>
  <div class="fresh-page">
    <div class="fresh-container">
      <!-- 标题区域（独立卡片） -->
      <div class="section-header-card" @click="handleEditHeader">
        <div class="header-left">
          <span class="section-title">{{ headerConfig.title }}</span>
          <span class="section-subtitle">{{ headerConfig.subtitle }}</span>
        </div>
        <div class="header-right">
          <span class="more-link" @click.stop="handleLinkClick">{{ headerConfig.linkText }} ></span>
        </div>
      </div>

      <!-- 商品列表区域 -->
      <div class="product-grid">
        <div v-for="item in productList" :key="item.id" class="product-item">
          <el-icon class="close-icon" @click.stop="handleRemoveProduct(item.id)"><CircleClose /></el-icon>
          <div class="sort-icon" @click.stop="handleSort(item.id)">
            <span class="arrow-down">↓</span>
            <span class="arrow-up">↑</span>
          </div>
          <div class="product-image">
            <el-image :src="item.imageUrl" fit="contain">
              <template #error>
                <div class="image-placeholder"><el-icon><Picture /></el-icon></div>
              </template>
            </el-image>
          </div>
          <div class="product-info">
            <p class="product-name">{{ item.name }}</p>
            <p class="product-desc">{{ item.description }}</p>
            <p class="product-price">¥{{ item.price }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 排序对话框 -->
    <el-dialog v-model="sortDialog.visible" title="排序商品" width="400px" append-to-body>
      <el-form label-width="60px">
        <el-form-item label="排序">
          <el-input-number v-model="sortDialog.sortValue" :min="0" controls-position="right" style="width: 200px" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="saveSortConfig">确 认</el-button>
        <el-button @click="sortDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 编辑标题对话框 -->
    <el-dialog v-model="headerDialog.visible" title="编辑标题" width="600px" append-to-body>
      <el-form :model="headerForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标题名称" required>
              <el-input v-model="headerForm.title" placeholder="请输入标题名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="副标题" required>
              <el-input v-model="headerForm.subtitle" placeholder="请输入副标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="链接文字">
              <el-input v-model="headerForm.linkText" placeholder="请输入链接文字" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="链接">
              <el-input v-model="headerForm.linkUrl" placeholder="请输入链接地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="背景色">
              <el-color-picker v-model="headerForm.bgColor" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字体颜色">
              <el-color-picker v-model="headerForm.textColor" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="saveHeaderConfig">确 认</el-button>
        <el-button @click="headerDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Fresh" lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Picture, CircleClose } from '@element-plus/icons-vue';
import { getDecorationSectionByType, addDecorationSection, updateDecorationSection } from '@/api/decoration/section';
import { listProduct } from '@/api/product/base';
import { listRecommend, listRecommendLink, addRecommendLink, delRecommendLink } from '@/api/product/recommend';

// 标题配置
const headerConfig = ref({
  id: null as number | null,
  title: '新鲜好物',
  subtitle: '寻觅世间好物',
  linkText: '更多',
  linkUrl: '',
  bgColor: '#ffffff',
  textColor: '#303133'
});

const headerDialog = reactive({ visible: false });
const headerForm = reactive({
  id: null as number | null,
  title: '',
  subtitle: '',
  linkText: '',
  linkUrl: '',
  bgColor: '#ffffff',
  textColor: '#303133'
});

// 加载标题配置
const loadHeaderConfig = async () => {
  try {
    const res = await getDecorationSectionByType('fresh');
    if (res.rows && res.rows.length > 0) {
      const data = res.rows[0];
      headerConfig.value = {
        id: data.id,
        title: data.title || '新鲜好物',
        subtitle: data.subtitle || '寻觅世间好物',
        linkText: data.linkText || '更多',
        linkUrl: data.linkUrl || '',
        bgColor: data.bgColor || '#ffffff',
        textColor: data.textColor || '#303133'
      };
    }
  } catch (error) {
    console.error('加载标题配置失败', error);
  }
};

const handleEditHeader = () => {
  Object.assign(headerForm, headerConfig.value);
  headerDialog.visible = true;
};

const saveHeaderConfig = async () => {
  try {
    const data = {
      ...headerForm,
      sectionType: 'fresh'
    };
    if (headerForm.id) {
      await updateDecorationSection(data);
    } else {
      await addDecorationSection(data);
    }
    await loadHeaderConfig();
    headerDialog.visible = false;
    ElMessage.success('标题配置已保存');
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

const handleLinkClick = () => {
  if (headerConfig.value.linkUrl) {
    window.open(headerConfig.value.linkUrl, '_blank');
  }
};

// 推荐位编号
const recommendNo = 'decoration_fresh';
const recommendId = ref<number | null>(null);

// 商品列表
const productList = ref<any[]>([]);

// 获取推荐位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 loadProductList = async () => {
  try {
    if (!recommendId.value) {
      await loadRecommendId();
    }
    if (!recommendId.value) {
      productList.value = [];
      return;
    }
    // 获取推荐关联
    const linkRes: any = await listRecommendLink({ recommendId: recommendId.value, pageSize: 100 });
    const links = linkRes.rows || [];
    if (links.length === 0) {
      productList.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]));
    // 组装数据
    productList.value = links.map((link: any) => {
      const product: any = productMap.get(link.productId) || {};
      return {
        id: product.id || link.productId,
        linkId: link.id,
        name: product.itemName || `商品${link.productId}`,
        description: product.remark || '',
        price: product.minSellingPrice || product.memberPrice || '0.00',
        imageUrl: product.productImageUrl || product.productImage
      };
    });
  } catch (error) {
    console.error('加载商品列表失败', error);
    productList.value = [];
  }
};

// 移除商品
const handleRemoveProduct = (id: number) => {
  const product = productList.value.find((item) => item.id === id);
  ElMessageBox.confirm('是否确认移除该商品？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        if (product?.linkId) {
          await delRecommendLink(product.linkId);
        }
        await loadProductList();
        ElMessage.success('已移除');
      } catch (error) {
        ElMessage.error('移除失败');
      }
    })
    .catch(() => {});
};

// 排序对话框
const sortDialog = reactive({ visible: false, productId: 0, sortValue: 0 });
const handleSort = (id: number) => {
  sortDialog.productId = id;
  sortDialog.sortValue = 0;
  sortDialog.visible = true;
};
const saveSortConfig = () => {
  sortDialog.visible = false;
  ElMessage.success('排序已保存');
};

// 选择商品对话框
const selectDialog = reactive({
  visible: false,
  keyword: '',
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const availableProducts = ref<any[]>([]);
const selectedProductIds = ref<number[]>([]);
const productTableRef = ref();

// 加载可选商品
const loadAvailableProducts = async () => {
  try {
    const params: any = { pageNum: selectDialog.pageNum, pageSize: selectDialog.pageSize };
    if (selectDialog.keyword) params.itemName = selectDialog.keyword;
    const res: any = await listProduct(params);
    availableProducts.value = (res.rows || []).map((item: any) => ({
      id: item.id,
      name: item.itemName,
      imageUrl: item.productImageUrl || item.productImage,
      price: item.minSellingPrice || item.memberPrice || '0.00'
    }));
    selectDialog.total = res.total || 0;
  } catch (error) {
    console.error('加载商品失败', error);
    availableProducts.value = [];
  }
};

// 过滤已选商品
const filteredAvailableProducts = computed(() => {
  const selectedIds = productList.value.map((p) => String(p.id));
  return availableProducts.value.filter((item) => !selectedIds.includes(String(item.id)));
});

// 新增商品
const handleAddProduct = () => {
  selectDialog.keyword = '';
  selectDialog.pageNum = 1;
  selectDialog.visible = true;
  selectedProductIds.value = [];
  loadAvailableProducts();
  nextTick(() => { productTableRef.value?.clearSelection(); });
};

// 选择变化
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;
    for (const productId of selectedProductIds.value) {
      if (!productList.value.find((p) => String(p.id) === String(productId))) {
        await addRecommendLink({ recommendId: recommendId.value, productId });
        addedCount++;
      }
    }
    if (addedCount > 0) {
      ElMessage.success(`成功添加 ${addedCount} 个商品`);
    } else {
      ElMessage.warning('所选商品均已存在');
    }
    selectDialog.visible = false;
    await loadProductList();
  } catch (error) {
    ElMessage.error('添加失败');
  }
};

onMounted(() => {
  loadHeaderConfig();
  loadProductList();
});
</script>

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

.fresh-container {
  max-width: 1100px;
  margin: 0 auto;
}

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

.section-header-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 12px;
  cursor: pointer;

  &:hover { background: #fafafa; }

  .header-left {
    display: flex;
    align-items: baseline;
    gap: 12px;

    .section-title { font-size: 16px; font-weight: 600; color: #333; }
    .section-subtitle { font-size: 12px; color: #999; }
  }

  .header-right {
    .more-link { font-size: 12px; color: #666; cursor: pointer; &:hover { color: #333; } }
  }
}

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

.product-item {
  position: relative;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  padding: 15px;
  cursor: pointer;

  &:hover { background: #fafafa; }

  .close-icon {
    position: absolute;
    top: 8px;
    right: 8px;
    font-size: 18px;
    color: #999;
    cursor: pointer;
    &:hover { color: #f56c6c; }
  }

  .sort-icon {
    position: absolute;
    top: 50%;
    right: 6px;
    transform: translateY(-50%);
    cursor: pointer;
    display: flex;
    gap: 0;

    .arrow-down, .arrow-up {
      font-size: 16px;
      font-weight: bold;
      color: #999;
      &:hover { color: #409eff; }
    }
  }

  .product-image {
    width: 100%;
    height: 120px;
    margin-bottom: 10px;

    .el-image {
      width: 100%;
      height: 100%;
      border-radius: 4px;
    }

    .image-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f5f5f5;
      color: #ccc;
      font-size: 30px;
    }
  }

  .product-info {
    .product-name {
      margin: 0 0 5px 0;
      font-size: 14px;
      font-weight: 500;
      color: #333;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .product-desc {
      margin: 0 0 5px 0;
      font-size: 12px;
      color: #999;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .product-price {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #f56c6c;
    }
  }
}

.search-bar {
  display: flex;
  gap: 10px;
}

.image-placeholder-small {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #ccc;
  font-size: 20px;
}

.price-text {
  color: #f56c6c;
  font-weight: 600;
}
</style>
