<template>
  <div class="banner-page">
    <div class="banner-container">
      <!-- 表格区域（独立卡片） -->
      <div class="table-card">
        <div class="table-header">
          <span class="table-title">广告位信息列表</span>
          <div class="table-actions">
            <el-button type="primary" icon="Plus" @click="handleAdd">添加广告</el-button>
            <el-button icon="Refresh" circle size="small" @click="getList" />
          </div>
        </div>

        <el-table v-loading="loading" :data="bannerList" border>
          <el-table-column label="公告标题" align="center" prop="title" min-width="150" />
          <el-table-column label="封面图片" align="center" width="120">
            <template #default="scope">
              <el-image
                :src="scope.row.imageUrl"
                fit="cover"
                style="width: 80px; height: 60px; border-radius: 4px"
                :preview-src-list="[scope.row.imageUrl]"
                preview-teleported
              >
                <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" min-width="250">
            <template #default="scope">
              <el-link type="primary" :href="scope.row.link" target="_blank">{{ scope.row.link }}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'info'" size="small">
                {{ 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="120">
            <template #default="scope">
              <span class="action-link primary" @click="handleEdit(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="600px" append-to-body>
      <el-form ref="formRef" :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" />
        </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" :max="999" controls-position="right" />
        </el-form-item>
        <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-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const AD_TYPE = 'gift_bottom_banner';

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
});

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

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

const formRef = ref<FormInstance>();
const initForm = {
  id: undefined as number | undefined,
  adType: AD_TYPE,
  title: '',
  imageUrl: '',
  link: '',
  sort: 0,
  status: 1,
  color: '#ffffff',
  remark: '',
  extJson: '{}',
  startTime: '',
  endTime: ''
};
const form = ref({ ...initForm });

const rules = {
  title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
  link: [{ required: true, message: '请输入链接地址', trigger: 'blur' }]
};

const getList = async () => {
  loading.value = true;
  try {
    const res = await listAdContent({
      adType: AD_TYPE,
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize
    });
    bannerList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error('加载列表失败', error);
  } finally {
    loading.value = false;
  }
};

const reset = () => {
  form.value = { ...initForm };
  formRef.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.title = '添加广告';
  dialog.visible = true;
};

const handleEdit = (row: any) => {
  reset();
  form.value = {
    ...row,
    adType: AD_TYPE,
    imageUrl: 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.title = '编辑广告';
  dialog.visible = true;
};

const handleDelete = (row: any) => {
  proxy?.$modal.confirm(`是否确认删除该广告？`).then(() => {
    delAdContent(row.id).then(() => {
      proxy?.$modal.msgSuccess('删除成功');
      getList();
    });
  });
};

const submitForm = () => {
  formRef.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();
      });
    }
  });
};

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

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

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

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

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

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

.table-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 60px;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
  border-radius: 4px;
}

.action-link {
  cursor: pointer;
  margin: 0 6px;

  &.primary {
    color: #409eff;
    &:hover { color: #66b1ff; }
  }

  &.danger {
    color: #f56c6c;
    &:hover { color: #f78989; }
  }
}
</style>
