<template>
  <div class="icon-page">
    <div class="icon-container">
      <!-- 标题栏（独立卡片） -->
      <div class="header-card">
        <div class="table-title">福礼图标广告信息列表</div>
        <div class="action-btns">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">添加图标广告</el-button>
          <el-button icon="Refresh" @click="getList">刷新</el-button>
        </div>
      </div>

      <!-- 表格区域（独立卡片） -->
      <div class="table-card">
        <!-- 表格 -->
        <el-table v-loading="loading" :data="iconList" border>
        <el-table-column label="分类标题" align="center" prop="title" min-width="160" />
        <el-table-column label="封面图片" align="center" width="140">
          <template #default="scope">
            <el-image
              :src="scope.row.imageUrl"
              :preview-src-list="[scope.row.imageUrl]"
              fit="cover"
              style="width: 64px; height: 64px"
              lazy
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="链接地址" align="center" prop="link" :show-overflow-tooltip="true" min-width="220">
          <template #default="scope">
            <span class="link-text">{{ scope.row.link || '#' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '显示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort" width="80" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <span class="action-link primary" @click="handleUpdate(scope.row)">编辑</span>
            <span class="action-link danger" @click="handleDelete(scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>

        <!-- 分页 -->
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="total"
          @pagination="getList"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="620px" append-to-body @close="cancel">
      <el-form ref="iconFormRef" :model="form" :rules="rules" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公告标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入公告标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告链接" prop="link">
              <el-input v-model="form.link" placeholder="请输入公告链接" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="form.status"
                :active-value="1"
                :inactive-value="0"
                active-text="显示"
                inactive-text="隐藏"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="封面图片" prop="imageUrl">
          <image-upload v-model="form.imageUrl" :limit="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确认</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GiftIcon" lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import type { FormInstance } from 'element-plus';
import dayjs from 'dayjs';
import { listAdContent, addAdContent, updateAdContent, delAdContent } from '@/api/ad/content';
import { listByIds } from '@/api/system/oss';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const loading = ref(false);
const total = ref(0);
const iconList = ref<any[]>([]);

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  adType: 'gift_icon'
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const iconFormRef = ref<FormInstance>();

const initFormData = {
  id: undefined as number | undefined,
  adType: 'gift_icon',
  title: '',
  imageUrl: '',
  link: '',
  sort: 0,
  status: 1,
  color: '#ffffff',
  remark: '',
  extJson: '{}',
  startTime: '',
  endTime: ''
};

const form = ref({ ...initFormData });

const rules = reactive({
  title: [{ required: true, message: '公告标题不能为空', trigger: 'blur' }]
});

const getList = async () => {
  loading.value = true;
  const res = await listAdContent({
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    adType: queryParams.value.adType
  });
  const rows = res.rows || [];
  // 把 ossId 转换成真正的图片 URL
  const ossIds = rows.map((item: any) => item.imageUrl).filter((id: any) => id).join(',');
  if (ossIds) {
    try {
      const ossRes = await listByIds(ossIds);
      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(String(item.imageUrl))) {
          item.imageUrl = ossMap.get(String(item.imageUrl));
        }
      });
    } catch (e) {
      console.error('获取图片URL失败', e);
    }
  }
  iconList.value = rows;
  total.value = res.total || 0;
  loading.value = false;
};

const reset = () => {
  form.value = { ...initFormData };
  iconFormRef.value?.resetFields();
};

const handleAdd = () => {
  reset();
  const today = dayjs().format('YYYY-MM-DD');
  const future = dayjs().add(365, 'day').format('YYYY-MM-DD');
  form.value.startTime = today;
  form.value.endTime = future;
  dialog.visible = true;
  dialog.title = '新增图标广告';
};

const handleUpdate = (row: any) => {
  reset();
  form.value = {
    ...row,
    adType: 'gift_icon',
    // 编辑时用ossId，这样image-upload组件才能正确回显
    imageUrl: row.imageOssId || row.imageUrl || '',
    status: row.status ?? 1,
    color: row.color || '#ffffff',
    remark: row.remark || '',
    extJson: row.extJson || '{}',
    startTime: row.startTime ? dayjs(row.startTime).format('YYYY-MM-DD') : '',
    endTime: row.endTime ? dayjs(row.endTime).format('YYYY-MM-DD') : ''
  };
  dialog.visible = true;
  dialog.title = '编辑图标广告';
};

const submitForm = () => {
  iconFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      const api = form.value.id ? updateAdContent : addAdContent;
      api(form.value).then(() => {
        proxy?.$modal.msgSuccess(form.value.id ? '修改成功' : '新增成功');
        dialog.visible = false;
        getList();
      });
    }
  });
};

const handleDelete = (row: any) => {
  proxy?.$modal.confirm(`是否确认删除分类标题为\"${row.title}\"的数据项?`).then(() => {
    delAdContent(row.id).then(() => {
      proxy?.$modal.msgSuccess('删除成功');
      getList();
    });
  });
};

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

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

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

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

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

  .table-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .action-btns {
    display: flex;
    gap: 10px;
  }
}

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

.image-slot {
  width: 64px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #c0c4cc;
  border-radius: 4px;
}

.link-text {
  color: #409eff;
}

.action-link {
  cursor: pointer;
  margin: 0 8px;
  
  &.primary {
    color: #409eff;
    &:hover { color: #66b1ff; }
  }
  
  &.danger {
    color: #f56c6c;
    &:hover { color: #f78989; }
  }
}
</style>


