<template>
  <div class="container-box">
    <div class="header-bar">
      <h2>Banner管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddBanner">
          <el-icon>
            <Plus />
          </el-icon>
          添加Banner
        </el-button>
        <el-button @click="refresh" :loading="loading">
          <el-icon>
            <Refresh />
          </el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <el-divider></el-divider>

    <!-- 表格 -->
    <el-table
      :data="bannerList"
      style="width: 100%"
      border
      v-loading="loading"
      element-loading-text="正在加载..."
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      
      <el-table-column prop="title" label="标题" min-width="150" />
      
      <el-table-column label="图片" width="200" align="center">
        <template #default="scope">
          <el-image
            v-if="scope.row.image"
            :src="getImageUrl(scope.row.image)"
            :preview-src-list="[getImageUrl(scope.row.image)]"
            :preview-teleported="true"
            fit="cover"
            style="width: 100px; height: 60px; border-radius: 4px; cursor: pointer;"
          />
          <span v-else style="color: #ccc;">-</span>
        </template>
      </el-table-column>

      <el-table-column prop="desc" label="简介" min-width="200" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="scope.row.desc">{{ scope.row.desc }}</span>
          <span v-else style="color: #ccc;">-</span>
        </template>
      </el-table-column>

      <el-table-column prop="url" label="跳转地址" min-width="200" show-overflow-tooltip>
        <template #default="scope">
          <el-link v-if="scope.row.url" :href="scope.row.url" target="_blank" type="primary">
            {{ scope.row.url }}
          </el-link>
          <span v-else style="color: #ccc;">-</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="sort"
        label="排序"
        width="100"
        align="center"
        sortable
      >
        <template #default="scope">
          <el-tag>{{ scope.row.sort || 0 }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template #default="scope">
          <el-button size="small" text @click="handleEditBanner(scope.row)">
            <el-icon>
              <Edit />
            </el-icon>
            <span>编辑</span>
          </el-button>

          <el-button
            size="small"
            text
            type="danger"
            @click="handleDeleteBanner(scope.row)"
          >
            <el-icon>
              <Delete />
            </el-icon>
            <span>删除</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 引入编辑组件 -->
    <BannerEdit
      v-model:visible="dialogVisible"
      :banner="dialogBanner"
      @save="handleBannerSave"
      @cancel="handleBannerCancel"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Edit, Delete, Refresh } from "@element-plus/icons-vue";
import {
  getBanners,
  createBanner,
  editBanner,
  deleteBanner,
} from "@/api/banner";
import BannerEdit from "./components/edit.vue";

// 定义Banner数据类型
interface Banner {
  id: number;
  title: string;
  desc: string;
  url: string;
  image: string;
  sort: number;
  create_time?: number;
  update_time?: number;
  delete_time?: number;
}

// Banner列表
const bannerList = ref<Banner[]>([]);
const loading = ref(false);

// 对话框相关变量
const dialogVisible = ref(false);
const dialogBanner = ref<Partial<Banner> | null>(null);

// 获取Banner列表
const fetchBanners = async () => {
  loading.value = true;
  try {
    const result = await getBanners();
    if (result.code === 200) {
      bannerList.value = result.data || [];
    } else {
      ElMessage.error("获取Banner列表失败: " + result.message);
    }
  } catch (error) {
    ElMessage.error("获取Banner列表失败: " + (error as Error).message);
  } finally {
    loading.value = false;
  }
};

// 刷新界面
async function refresh() {
  loading.value = true;
  try {
    await fetchBanners();
    ElMessage.success("刷新成功");
  } catch (error) {
    ElMessage.error("刷新失败");
  } finally {
    loading.value = false;
  }
}

// 添加Banner
const handleAddBanner = () => {
  dialogBanner.value = {
    id: 0,
    title: "",
    desc: "",
    url: "",
    image: "",
    sort: 0,
  };
  dialogVisible.value = true;
};

// 编辑Banner
const handleEditBanner = (banner: Banner) => {
  dialogBanner.value = { ...banner };
  dialogVisible.value = true;
};

// 删除Banner
const handleDeleteBanner = (banner: Banner) => {
  ElMessageBox.confirm(
    `确定要删除Banner "${banner.title}" 吗？`,
    "确认删除",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    try {
      const result = await deleteBanner(banner.id);
      if (result.code === 200) {
        ElMessage.success("删除成功");
        fetchBanners();
      } else {
        ElMessage.error("删除失败: " + result.message);
      }
    } catch (error) {
      ElMessage.error("删除失败: " + (error as Error).message);
    }
  });
};

// 处理Banner保存
const handleBannerSave = async (banner: Partial<Banner>) => {
  try {
    const payload = { ...banner };

    // 判断是新增还是编辑
    if (!banner.id || banner.id === 0) {
      // 新增Banner
      const result = await createBanner(payload as Banner);
      if (result.code === 200) {
        ElMessage.success(result.msg || "Banner添加成功");
        dialogVisible.value = false;
        await fetchBanners();
      } else {
        ElMessage.error(result.msg || "添加失败");
      }
    } else {
      // 编辑已存在的Banner
      const result = await editBanner(banner.id!, payload as Banner);
      if (result.code === 200) {
        ElMessage.success(result.msg || "更新成功");
        dialogVisible.value = false;
        await fetchBanners();
      } else {
        ElMessage.error(result.msg || "更新失败");
      }
    }
  } catch (error) {
    ElMessage.error("操作失败: " + (error as Error).message);
  }
};

// 处理Banner取消
const handleBannerCancel = () => {
  dialogVisible.value = false;
};

// 获取图片完整URL（用于显示）
// @ts-ignore
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '/api';
const getImageUrl = (imagePath: string) => {
  if (!imagePath) return '';
  // 如果是绝对路径，直接返回
  if (imagePath.startsWith('http')) return imagePath;
  // 如果是相对路径，拼接API基础地址
  return API_BASE_URL + imagePath;
};

// 组件挂载时加载Banner列表
onMounted(() => {
  fetchBanners();
});
</script>

<style lang="less" scoped>
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
}

.header-bar h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  gap: 8px;
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 0;
  width: 100% !important;
}

:deep(.el-table__body td) {
  padding: 12px 0;
  vertical-align: middle;
}
</style>
