<template>
  <div class="flash-sale-page">
    <div class="flash-sale-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="brand-showcase-card">
        <!-- 左侧大图（可点击编辑） -->
        <div class="showcase-left" @click="handleEditBanner">
          <el-image :src="bannerConfig.imageUrl || defaultBannerUrl" fit="cover" class="featured-image">
            <template #error>
              <div class="image-slot"><el-icon><Picture /></el-icon></div>
            </template>
          </el-image>
          <el-button type="warning" size="small" class="view-all-btn" @click.stop="handleViewAll">查看全部 ></el-button>
        </div>

        <!-- 右侧品牌网格 -->
        <div class="showcase-right">
          <div v-for="(item, index) in brandList" :key="item.id" class="brand-item">
            <el-icon class="close-icon" @click.stop="handleRemoveBrand(index)"><CircleClose /></el-icon>
            <div class="sort-icon" @click.stop="handleSort(index)">
              <span class="arrow-down">↓</span>
              <span class="arrow-up">↑</span>
            </div>
            <div class="brand-logo">
              <el-image :src="item.logoUrl" fit="contain" class="logo-image">
                <template #error>
                  <span class="logo-text">{{ item.title }}</span>
                </template>
              </el-image>
            </div>
            <div class="brand-info">
              <p class="brand-name">{{ item.title }}</p>
              <p class="brand-desc">{{ item.description }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 搜索区域（独立卡片） -->
      <div class="search-section-card">
        <div class="search-title">品牌闪购搜索列表</div>
        <div class="search-bar">
          <el-input v-model="searchKeyword" placeholder="请输入品牌编号或名称" clearable style="width: 280px" />
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>
      </div>
    </div>

    <!-- 编辑标题对话框 -->
    <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="标题名称">
              <el-input v-model="headerForm.title" placeholder="请输入标题名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="副标题">
              <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-form>
      <template #footer>
        <el-button type="primary" @click="saveHeaderConfig">确 认</el-button>
        <el-button @click="headerDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 编辑左侧大图对话框 -->
    <el-dialog v-model="bannerDialog.visible" title="编辑品牌广告" width="500px" append-to-body>
      <el-form :model="bannerForm" label-width="80px">
        <el-form-item label="图片">
          <image-upload v-model="bannerForm.imageUrl" :limit="1" />
        </el-form-item>
        <el-form-item label="链接">
          <el-input v-model="bannerForm.link" placeholder="请输入跳转链接" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="saveBannerConfig">确 认</el-button>
        <el-button @click="bannerDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 排序对话框 -->
    <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="selectDialog.visible" title="选择商品" width="800px" append-to-body>
      <div class="search-bar mb-[10px]">
        <el-input v-model="selectDialog.keyword" placeholder="请输入品牌编号或名称" clearable style="width: 280px" />
        <el-button type="primary" @click="loadSearchBrands">搜索</el-button>
      </div>
      <el-table :data="selectDialog.list" border max-height="400">
        <el-table-column label="品牌编号" align="center" prop="brandNo" width="120" />
        <el-table-column label="品牌图片" align="center" width="100">
          <template #default="scope">
            <el-image :src="scope.row.coverImage" fit="cover" style="width: 60px; height: 60px" lazy>
              <template #error><span class="text-gray-400">加载失败</span></template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="品牌名称" align="center" prop="brandName" />
        <el-table-column label="操作" align="center" width="80">
          <template #default="scope">
            <el-button type="primary" link @click="handleConfirmBrand(scope.row)">确认</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="selectDialog.total > 0"
        v-model:page="selectDialog.pageNum"
        v-model:limit="selectDialog.pageSize"
        :total="selectDialog.total"
        @pagination="loadSearchBrands"
      />
      <template #footer>
        <el-button @click="selectDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FlashSale" lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Picture, CircleClose } from '@element-plus/icons-vue';
import { getDecorationSectionByType, addDecorationSection, updateDecorationSection } from '@/api/decoration/section';
import { listAdContent, addAdContent, updateAdContent } from '@/api/ad/content';
import { listByIds } from '@/api/system/oss';
import { listBrand } from '@/api/product/brand';

const searchKeyword = ref('');
const defaultBannerUrl = 'https://via.placeholder.com/200x300/1a237e/FFFFFF?text=品牌广告';

// 左侧大图配置
const bannerConfig = ref({ id: null as number | null, imageUrl: '', imageOssId: '', link: '' });
const bannerDialog = reactive({ visible: false });
const bannerForm = reactive({ id: null as number | null, title: '品牌闪购大图', imageUrl: '', link: '', adType: 'flash_sale_banner', status: 1 });

const loadBannerConfig = async () => {
  try {
    const res = await listAdContent({ adType: 'flash_sale_banner', pageNum: 1, pageSize: 1 });
    if (res.rows && res.rows.length > 0) {
      const data = res.rows[0];
      const ossId = data.imageUrl || '';
      let displayUrl = ossId;
      if (ossId && /^\d+$/.test(ossId)) {
        try {
          const ossRes = await listByIds(ossId);
          if (ossRes.data && ossRes.data.length > 0) displayUrl = ossRes.data[0].url;
        } catch (e) { console.error('获取图片URL失败', e); }
      }
      bannerConfig.value = { id: data.id, imageUrl: displayUrl, imageOssId: ossId, link: data.link || '' };
    }
  } catch (error) { console.error('加载大图配置失败', error); }
};

const handleEditBanner = () => {
  // 编辑时用ossId，这样image-upload组件才能正确回显
  Object.assign(bannerForm, { 
    id: bannerConfig.value.id, 
    imageUrl: bannerConfig.value.imageOssId, 
    link: bannerConfig.value.link,
    adType: 'flash_sale_banner', 
    status: 1 
  });
  bannerDialog.visible = true;
};

const saveBannerConfig = async () => {
  try {
    if (bannerForm.id) await updateAdContent(bannerForm);
    else await addAdContent(bannerForm);
    await loadBannerConfig();
    bannerDialog.visible = false;
    ElMessage.success('保存成功');
  } catch (error) { ElMessage.error('保存失败'); }
};

// 标题配置
const headerConfig = ref({ id: null as number | null, title: '大牌推荐', subtitle: '甄选大牌,优质好品', linkText: '查看更多品牌信息', linkUrl: '' });
const headerDialog = reactive({ visible: false });
const headerForm = reactive({ id: null as number | null, title: '', subtitle: '', linkText: '', linkUrl: '' });

const loadHeaderConfig = async () => {
  try {
    const res = await getDecorationSectionByType('flash_sale');
    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 || '' };
    }
  } catch (error) { console.error('加载标题配置失败', error); }
};

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

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

// 品牌列表
const brandList = ref<any[]>([]);

// 加载品牌列表
const loadBrandList = async () => {
  try {
    const res: any = await listBrand({ pageNum: 1, pageSize: 10, isShow: 1 });
    brandList.value = (res.rows || []).map((item: any) => ({
      id: item.id,
      title: item.brandName,
      description: item.brandDescribe || item.brandName,
      logoUrl: item.brandBigImageUrl || item.brandLogo
    }));
  } catch (error) {
    console.error('加载品牌列表失败', error);
    brandList.value = [];
  }
};

const handleViewAll = () => { if (bannerConfig.value.link) window.open(bannerConfig.value.link, '_blank'); else ElMessage.info('暂未配置跳转链接'); };
const handleLinkClick = () => { if (headerConfig.value.linkUrl) window.open(headerConfig.value.linkUrl, '_blank'); };

// 选择商品对话框
const selectDialog = reactive({
  visible: false,
  keyword: '',
  list: [] as any[],
  total: 0,
  pageNum: 1,
  pageSize: 10
});

// 搜索品牌
const loadSearchBrands = async () => {
  try {
    const res: any = await listBrand({
      pageNum: selectDialog.pageNum,
      pageSize: selectDialog.pageSize,
      brandName: selectDialog.keyword || undefined
    });
    selectDialog.list = (res.rows || []).map((item: any) => ({
      id: item.id,
      brandNo: item.brandNo,
      brandName: item.brandName,
      coverImage: item.brandBigImageUrl || item.brandLogo
    }));
    selectDialog.total = res.total || 0;
  } catch (error) {
    console.error('搜索品牌失败', error);
    selectDialog.list = [];
  }
};

// 打开搜索弹框
const handleSearch = () => {
  selectDialog.keyword = searchKeyword.value;
  selectDialog.pageNum = 1;
  selectDialog.visible = true;
  loadSearchBrands();
};

// 确认选择品牌
const handleConfirmBrand = (row: any) => {
  // 检查是否已存在
  if (brandList.value.find((b) => String(b.id) === String(row.id))) {
    ElMessage.warning('该品牌已添加');
    return;
  }
  brandList.value.push({
    id: row.id,
    title: row.brandName,
    description: row.brandName,
    logoUrl: row.coverImage
  });
  ElMessage.success('添加成功');
};

// 品牌操作
const handleRemoveBrand = (index: number) => { brandList.value.splice(index, 1); ElMessage.success('已移除'); };

// 排序对话框
const sortDialog = reactive({ visible: false, index: 0, sortValue: 0 });
const handleSort = (index: number) => {
  sortDialog.index = index;
  sortDialog.sortValue = index;
  sortDialog.visible = true;
};
const saveSortConfig = () => {
  // 这里可以保存排序值到后端，目前只是前端展示
  sortDialog.visible = false;
  ElMessage.success('排序已保存');
};

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


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

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

// 标题区域卡片
.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; } }
  }
}

// 品牌展示卡片
.brand-showcase-card {
  display: flex;
  gap: 10px;
  margin-bottom: 12px;
}

.showcase-left {
  position: relative;
  width: 200px;
  flex-shrink: 0;
  cursor: pointer;
  background: #fff;
  border-radius: 4px;
  overflow: hidden;

  .featured-image { width: 100%; height: 100%; min-height: 260px; display: block; }
  .image-slot { display: flex; align-items: center; justify-content: center; width: 100%; height: 260px; background: #f5f5f5; color: #999; font-size: 40px; }
  .view-all-btn { position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); z-index: 10; white-space: nowrap; }
}

.showcase-right {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 10px;
}

.brand-item {
  position: relative;
  background: #fff;
  padding: 20px 15px;
  text-align: center;
  cursor: pointer;
  border-radius: 4px;
  border: 1px solid #e8e8e8;



  &: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; }
    }
  }

  .brand-logo {
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 10px;

    .logo-image {
      max-height: 36px;
      max-width: 90%;

      :deep(img) {
        object-fit: contain !important;
        max-height: 36px;
        max-width: 100%;
      }
    }
    .logo-text { font-size: 14px; font-weight: 600; color: #333; }
  }

  .brand-info {
    .brand-name { margin: 0 0 4px 0; font-size: 13px; font-weight: 500; color: #333; }
    .brand-desc { margin: 0; font-size: 11px; color: #999; }
  }
}

// 搜索区域卡片
.search-section-card {
  background: #fff;
  border-radius: 4px;

  .search-title { 
    font-size: 14px; 
    font-weight: 500; 
    color: #333; 
    padding: 12px 20px;
    border-bottom: 1px solid #e8e8e8;
  }
  .search-bar { 
    display: flex; 
    gap: 10px; 
    padding: 16px 20px;
  }
}
</style>
