<template>
  <div class="brand-container">
    <!-- 标题区域（可点击编辑） -->
    <div class="brand-header" @click="handleEditHeader">
      <div class="header-left">
        <span class="brand-title">{{ headerConfig.title }}</span>
        <span class="brand-subtitle">{{ headerConfig.subtitle }}</span>
      </div>
      <div class="header-right">
        <span class="more-link" @click.stop="handleLinkClick">{{ headerConfig.linkText }} ></span>
      </div>
    </div>

    <!-- 品牌图片网格（和商城一模一样） -->
    <div class="brand-grid">
      <div v-for="item in brandList" :key="item.id" class="brand-card" @click="handleUpdate(item)">
        <el-image :src="item.imageUrl || item.image_url" fit="cover" lazy class="brand-image">
          <template #error>
            <div class="image-slot">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-image>
      </div>
    </div>

    <!-- 空状态 -->
    <el-empty v-if="!loading && brandList.length === 0" description="暂无品牌数据" />

    <!-- 编辑标题对话框 -->
    <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="dialog.visible" :title="dialog.title" width="500px" append-to-body @close="cancel">
      <el-form ref="brandFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="品牌名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌图片" prop="imageUrl">
          <image-upload v-model="form.imageUrl" :limit="1" />
          <div class="upload-tip">建议尺寸：400x300，支持 jpg/png 格式</div>
        </el-form-item>
        <el-form-item label="跳转链接" prop="link">
          <el-input v-model="form.link" placeholder="请输入跳转链接" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" controls-position="right" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

const adType = 'decoration_brand';

// 标题配置
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('brand');
    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: 'brand' };
    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 form = reactive({
  id: undefined as number | undefined,
  title: '',
  imageUrl: '',
  link: '',
  sort: 0,
  adType,
  status: 1
});
const rules = {
  title: [{ required: true, message: '品牌名称不能为空', trigger: 'blur' }]
};

const dialog = reactive({ visible: false, title: '' });
const loading = ref(false);
const brandList = ref<any[]>([]);
const brandFormRef = ref();

// 获取品牌广告列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await listAdContent({ adType });
    const rows = res.rows || [];
    // 收集所有ossId，批量查询真实URL
    const ossIds = rows.map((item: any) => item.imageUrl).filter((id: string) => id && /^\d+$/.test(id));
    if (ossIds.length > 0) {
      const ossRes = await listByIds(ossIds.join(','));
      const ossMap = new Map(ossRes.data.map((oss: any) => [String(oss.ossId), oss.url]));
      rows.forEach((item: any) => {
        // 保存原始ossId用于编辑回显
        item.imageOssId = item.imageUrl;
        if (item.imageUrl && ossMap.has(item.imageUrl)) {
          item.imageUrl = ossMap.get(item.imageUrl);
        }
      });
    }
    brandList.value = rows;
  } catch (error) {
    console.error('获取品牌列表失败', error);
    brandList.value = [];
  } finally {
    loading.value = false;
  }
};

const handleUpdate = (row: any) => {
  reset();
  // 编辑时用ossId，这样image-upload组件才能正确回显
  Object.assign(form, {
    ...row,
    imageUrl: row.imageOssId || row.imageUrl || ''
  });
  dialog.visible = true;
  dialog.title = '编辑品牌广告';
};

const submitForm = async () => {
  brandFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await updateAdContent(form);
        ElMessage.success('保存成功');
        dialog.visible = false;
        getList();
      } catch (error) {
        ElMessage.error('保存失败');
      }
    }
  });
};

const cancel = () => {
  dialog.visible = false;
  reset();
};

const reset = () => {
  Object.assign(form, { id: undefined, title: '', imageUrl: '', link: '', sort: 0, adType, status: 1 });
  brandFormRef.value?.resetFields();
};

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

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

.brand-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fff;
  border-radius: 4px;
  cursor: pointer;
  max-width: 920px;
  margin: 0 auto 12px;
  margin-bottom: 10px;

  &:hover {
    background: #fafafa;
  }

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

    .brand-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }

    .brand-subtitle {
      font-size: 12px;
      color: #999;
    }
  }

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

      &:hover {
        color: #333;
      }
    }
  }
}

.brand-grid {
  display: flex;
  gap: 5px;
  justify-content: center;
  max-width: 920px;
  margin: 0 auto;
}

.brand-card {
  width: 180px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fff;

  &:hover {
    opacity: 0.9;
  }

  .brand-image {
    width: 100%;
    height: 240px;
    display: block;
  }

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

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}
</style>
