<script setup lang="ts">
import { reactive, onMounted, ref, nextTick } from "vue";
import { getBannerList, removeBanner } from "@/api/banner";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessage, ElMessageBox } from "element-plus";
import BannerDialog from "./dialog.vue";

defineOptions({ name: "AdminBanner" });

const queryRef = ref();
const dialogRef = ref();

interface ColumnItem {
  label: string;
  prop: string;
  width?: number;
}

const state = reactive({
  formQuery: {
    status: "",
    bannerDesc: ""
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false,
    columns: [
      { label: "Banner图片", prop: "bannerUrl", width: 100 },
      { label: "活动时间", prop: "period", width: 310 },
      { label: "状态", prop: "status", width: 100 },
      { label: "关联跳转地址", prop: "linkUrl", width: 400 },
      { label: "描述", prop: "bannerDesc", width: 200 },
      { label: "创建时间", prop: "createTime", width: 180 },
      { label: "更新时间", prop: "updateTime", width: 180 }
    ] as ColumnItem[]
  }
});

onMounted(() => {
  loadData();
  nextTick(() => {
    const bodyHeight = document.body.clientHeight;
    const queryHeight = queryRef.value?.$el?.clientHeight || 0;
    state.tableData.height = bodyHeight - queryHeight - 280;
  });
});

const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  getBannerList({ ...state.formQuery, ...state.pageQuery })
    .then((res: any) => {
      const { list, total } = res || {};
      state.tableData.data = (list || []).map((item: any) => ({
        ...item,
        period: `${item.startTime || ''} ~ ${item.endTime || ''}`
      }));
      state.pageQuery.total = total || 0;
    })
    .catch(() => {
      state.tableData.data = [];
    })
    .finally(() => {
      state.tableData.loading = false;
    });
};

const handleSizeChange = (size: number) => {
  state.pageQuery.pageSize = size;
  loadData(true);
};

const handleCurrentChange = (page: number) => {
  state.pageQuery.pageNum = page;
  loadData();
};

const handleSearch = () => {
  loadData(true);
};

const handleReset = () => {
  state.formQuery = {
    status: "",
    bannerDesc: ""
  };
  loadData(true);
};

const handleAdd = () => dialogRef.value?.open("add");
const handleEdit = (row: any) => dialogRef.value?.open("edit", row);
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除此横幅广告吗？`, "提示",
    { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
  ).then(() => {
    removeBanner(row.id).then(() => {
      ElMessage.success("删除成功");
      loadData(true);
    });
  }).catch(() => {});
};
</script>

<template>
  <div class="page-container">
    <el-card shadow="hover">
      <el-form ref="queryRef" :model="state.formQuery" inline class="search-form">
        <el-form-item label="描述">
          <el-input v-model="state.formQuery.bannerDesc" placeholder="请输入描述" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :icon="useRenderIcon('ri/search-line')"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button
            :icon="useRenderIcon('ri/refresh-line')"
            @click="handleReset"
          >
            重置
          </el-button>
          <el-button
            type="success"
            :icon="useRenderIcon('ri/add-line')"
            @click="handleAdd"
          >
            新增
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="state.tableData.loading"
        :data="state.tableData.data"
        :height="state.tableData.height"
        border
        stripe
      >
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
        <el-table-column label="Banner图片" width="150">
          <template #default="{ row }">
            <el-image v-if="row.bannerUrl" :src="row.bannerUrl" style="width: 100px; height: 60px" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column prop="period" label="活动时间" width="310" />
        <el-table-column prop="status" label="状态" width="100" />
        <el-table-column prop="linkUrl" label="关联跳转地址" width="300" show-overflow-tooltip />
        <el-table-column prop="bannerDesc" label="描述" width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="state.pageQuery.pageNum"
          v-model:page-size="state.pageQuery.pageSize"
          :total="state.pageQuery.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <BannerDialog ref="dialogRef" @refresh="loadData" />
  </div>
</template>

<style scoped lang="scss">
.page-container {
  padding: 15px;
}

.search-form {
  margin-bottom: 15px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
</style>
