<template>
  <div class="floor-ad-page">
    <div class="floor-ad-container">
      <div class="ad-card">
        <!-- 标签页切换 -->
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="首页三联广告" name="triple" />
          <el-tab-pane label="首页图标广告" name="icon" />
          <el-tab-pane label="首页logo" name="logo" />
          <el-tab-pane label="首页联系电话" name="contact" />
        </el-tabs>

        <!-- 三联广告展示区 -->
        <div v-if="activeTab === 'triple'" class="ad-preview triple-preview">
          <div class="triple-grid">
            <div
              v-for="(item, index) in adList"
              :key="item.id"
              class="triple-item"
              :class="{ active: selectedIndex === index }"
              @click="selectAd(index)"
            >
              <el-image :src="item.imageUrl" fit="contain" class="triple-image">
                <template #error>
                  <div class="image-slot"><el-icon><Picture /></el-icon></div>
                </template>
              </el-image>
            </div>
          </div>
        </div>

        <!-- 图标广告展示区 -->
        <div v-if="activeTab === 'icon'" class="ad-preview icon-preview">
          <div class="icon-grid">
            <div
              v-for="(item, index) in adList"
              :key="item.id"
              class="icon-item"
              :class="{ active: selectedIndex === index }"
              @click="selectAd(index)"
            >
              <div class="icon-img">
                <el-image :src="item.imageUrl" fit="contain" class="icon-image">
                  <template #error><el-icon size="32"><Picture /></el-icon></template>
                </el-image>
              </div>
              <span class="icon-text">{{ item.title }}</span>
            </div>
          </div>
        </div>

        <!-- Logo展示区 -->
        <div v-if="activeTab === 'logo'" class="ad-preview logo-preview">
          <div class="logo-item" @click="selectAd(0)" :class="{ active: selectedIndex === 0 }">
            <el-image v-if="adList.length > 0" :src="adList[0]?.imageUrl" fit="contain" class="logo-image">
              <template #error>
                <div class="image-slot"><el-icon><Picture /></el-icon></div>
              </template>
            </el-image>
          </div>
        </div>

        <!-- 联系电话展示区 -->
        <div v-if="activeTab === 'contact'" class="ad-preview contact-preview">
          <el-button type="default" @click="handleAddContact">新增首页图标广告</el-button>
          <div class="contact-list">
            <div
              v-for="(item, index) in adList"
              :key="item.id"
              class="contact-item"
              :class="{ active: selectedContactIndex === index }"
              @click="selectContact(index)"
            >
              <div class="contact-info">
                <span class="contact-label">{{ item.title }}</span>
                <span class="contact-value">{{ item.remark }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="ad-divider"></div>

        <!-- 联系电话编辑表单 -->
        <div v-if="activeTab === 'contact' && selectedContactIndex !== null && adList.length > 0" class="ad-form">
          <el-form :model="contactForm" label-width="50px">
            <el-form-item label="文字:">
              <el-input v-model="contactForm.title" placeholder="请输入文字" style="max-width: 500px" />
            </el-form-item>
            <el-form-item label="排序:">
              <el-input-number v-model="contactForm.sort" :min="0" :max="999" controls-position="right" />
            </el-form-item>
            <el-form-item label="电话:">
              <el-input v-model="contactForm.remark" placeholder="请输入电话" style="max-width: 500px" />
            </el-form-item>
            <el-form-item label=" ">
              <el-button type="primary" @click="handleSubmitContactEdit">提 交</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 编辑表单 -->
        <div v-if="selectedIndex !== null && adList.length > 0 && activeTab !== 'contact'" class="ad-form">
          <el-form ref="formRef" :model="form" label-width="50px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="文字:">
                  <el-input v-model="form.title" placeholder="请输入文字" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="链接:">
                  <el-input v-model="form.link" placeholder="请输入链接地址" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="图片:">
              <upload-image v-model="form.imageUrl" :limit="1" />
              <div class="upload-tip">请上传大小不超过 <span class="tip-highlight">5MB</span> 格式为 <span class="tip-highlight">png/jpg/jpeg</span> 的文件</div>
            </el-form-item>
            <el-form-item label="描述:">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入描述" style="max-width: 500px" />
            </el-form-item>
            <el-form-item label=" ">
              <el-button type="primary" @click="handleSubmit">提 交</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 联系电话编辑对话框 -->
        <el-dialog v-model="contactDialog.visible" title="编辑联系电话" width="500px" append-to-body>
          <el-form :model="contactForm" label-width="80px">
            <el-form-item label="标题:">
              <el-input v-model="contactForm.title" placeholder="如：售后" />
            </el-form-item>
            <el-form-item label="电话:">
              <el-input v-model="contactForm.remark" placeholder="如：400-111-0027" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="contactDialog.visible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmitContact">确定</el-button>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup name="IndustrialFloorAd" lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';
import { listAdContent, updateAdContent, addAdContent } from '@/api/ad/content';
import dayjs from 'dayjs';

const activeTab = ref('triple');
const selectedIndex = ref<number | null>(null);

// 广告类型映射（工业装修专用，避免和平台装修冲突）
const adTypeMap: Record<string, string> = {
  triple: 'industrial_ad_triple',
  icon: 'industrial_ad_icon',
  logo: 'industrial_ad_logo',
  contact: 'industrial_ad_contact'
};

const adList = ref<any[]>([]);
const loading = ref(false);

const form = ref({
  id: undefined as number | undefined,
  adType: '',
  title: '',
  remark: '',
  link: '',
  imageUrl: '',
  sort: 0,
  status: 1,
  startTime: '',
  endTime: ''
});

// 联系电话对话框
const contactDialog = reactive({ visible: false });
const contactForm = ref({ id: undefined as number | undefined, title: '', remark: '', sort: 0 });
const selectedContactIndex = ref<number | null>(null);

const loadAdList = async () => {
  loading.value = true;
  try {
    const adType = adTypeMap[activeTab.value];
    const res = await listAdContent({ adType, pageSize: 100 });
    adList.value = res.rows || [];
    selectedIndex.value = null;
    selectedContactIndex.value = null;
  } catch (error) {
    console.error('加载广告列表失败', error);
    adList.value = [];
  } finally {
    loading.value = false;
  }
};

const handleTabChange = () => {
  selectedIndex.value = null;
  loadAdList();
};

const selectAd = (index: number) => {
  selectedIndex.value = index;
  loadFormData();
};

const loadFormData = () => {
  if (selectedIndex.value === null || !adList.value[selectedIndex.value]) return;
  const item = adList.value[selectedIndex.value];
  form.value = {
    id: item.id,
    adType: adTypeMap[activeTab.value],
    title: item.title || '',
    remark: item.remark || '',
    link: item.link || '',
    imageUrl: item.imageUrl || '',
    sort: item.sort || 0,
    status: item.status ?? 1,
    startTime: item.startTime ? dayjs(item.startTime).format('YYYY-MM-DD') : '',
    endTime: item.endTime ? dayjs(item.endTime).format('YYYY-MM-DD') : ''
  };
};

const handleSubmit = async () => {
  try {
    if (!form.value.startTime) form.value.startTime = dayjs().format('YYYY-MM-DD');
    if (!form.value.endTime) form.value.endTime = dayjs().add(365, 'day').format('YYYY-MM-DD');
    await updateAdContent(form.value);
    ElMessage.success('提交成功');
    await loadAdList();
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

const handleAddContact = () => {
  contactForm.value = { id: undefined, title: '', remark: '', sort: 0 };
  contactDialog.visible = true;
};

// 选择联系电话
const selectContact = (index: number) => {
  selectedContactIndex.value = index;
  const item = adList.value[index];
  contactForm.value = {
    id: item.id,
    title: item.title || '',
    remark: item.remark || '',
    sort: item.sort || 0
  };
};

// 提交联系电话编辑
const handleSubmitContactEdit = async () => {
  try {
    await updateAdContent({
      id: contactForm.value.id,
      adType: adTypeMap.contact,
      title: contactForm.value.title,
      remark: contactForm.value.remark,
      sort: contactForm.value.sort,
      startTime: dayjs().format('YYYY-MM-DD'),
      endTime: dayjs().add(365, 'day').format('YYYY-MM-DD'),
      status: 1
    });
    ElMessage.success('提交成功');
    await loadAdList();
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

const handleSubmitContact = async () => {
  try {
    const data = {
      adType: adTypeMap.contact,
      title: contactForm.value.title,
      remark: contactForm.value.remark,
      startTime: dayjs().format('YYYY-MM-DD'),
      endTime: dayjs().add(365, 'day').format('YYYY-MM-DD'),
      status: 1
    };
    if (contactForm.value.id) {
      await updateAdContent({ ...data, id: contactForm.value.id });
    } else {
      await addAdContent(data);
    }
    ElMessage.success('保存成功');
    contactDialog.visible = false;
    await loadAdList();
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

onMounted(() => {
  loadAdList();
});
</script>


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

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

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

  :deep(.el-tabs__nav-wrap::after) {
    height: 1px;
    background-color: #e4e7ed;
  }

  :deep(.el-tabs__item) {
    font-size: 14px;
    color: #666;
    padding: 0 20px;
    &.is-active {
      color: #409eff;
    }
  }

  :deep(.el-tabs__active-bar) {
    height: 2px;
  }
}

.ad-preview {
  margin: 20px 0;
  padding-bottom: 20px;
}

.ad-divider {
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 20px;
}

.triple-preview {
  .triple-grid {
    display: flex;
    justify-content: flex-start;
    gap: 15px;
  }

  .triple-item {
    width: 200px;
    height: 80px;
    flex-shrink: 0;
    cursor: pointer;
    border: 2px solid transparent;
    &:hover { opacity: 0.9; }
    &.active { border-color: #409eff; }
    .triple-image { width: 100%; height: 100%; }
  }
}

.icon-preview {
  .icon-grid {
    display: flex;
    justify-content: flex-start;
    gap: 10px;
  }

  .icon-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10px;
    cursor: pointer;
    border-radius: 4px;
    border: 2px solid transparent;
    &:hover { background: #f5f5f5; }
    &.active { border-color: #409eff; background: #ecf5ff; }

    .icon-img {
      width: 50px;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 6px;
      .icon-image { width: 100%; height: 100%; }
    }

    .icon-text {
      font-size: 12px;
      color: #333;
    }
  }
}

.logo-preview {
  .logo-item {
    width: 400px;
    height: 80px;
    cursor: pointer;
    border: 2px solid transparent;
    &.active { border-color: #409eff; }
    .logo-image { width: 100%; height: 100%; }
  }
}

.contact-preview {
  .contact-list {
    display: flex;
    gap: 30px;
    margin-top: 15px;
  }

  .contact-item {
    cursor: pointer;
    padding: 8px 12px;
    border-radius: 4px;
    border: 2px solid transparent;

    &:hover {
      background: #f5f5f5;
    }

    &.active {
      border-color: #409eff;
      background: #ecf5ff;
    }

    .contact-info {
      display: flex;
      flex-direction: column;
      .contact-label {
        font-size: 12px;
        color: #999;
        margin-bottom: 4px;
      }
      .contact-value {
        font-size: 14px;
        color: #333;
      }
    }
  }
}

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

.ad-form {
  padding-top: 20px;

  .upload-tip {
    font-size: 12px;
    color: #999;
    margin-top: 8px;

    .tip-highlight {
      color: #f56c6c;
    }
  }
}
</style>
