<template>
  <div class="banner-container">
    <el-card shadow="hover">
      <div class="page-header">
        <h2 class="page-title">轮播图管理</h2>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">
          新增轮播图
        </el-button>
      </div>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索轮播图标题"
            clearable
            size="small"
            style="width: 240px"
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="状态" clearable size="small" style="width: 120px">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
          <el-button size="small" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        size="small"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="title" label="轮播图标题" min-width="150"></el-table-column>
        <el-table-column prop="imageUrl" label="轮播图图片" width="150" align="center">
          <template #default="scope">
            <el-image
              v-if="scope.row.imageUrl"
              :src="scope.row.imageUrl"
              :preview-src-list="[scope.row.imageUrl]"
              style="width: 100px; height: 50px; cursor: pointer;"
              fit="cover"
            />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="linkUrl" label="跳转链接" min-width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="80" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160"></el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.size"
        layout="total, sizes, prev, pager, next"
        :total="pagination.total"
        small
      ></el-pagination>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form ref="bannerForm" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入轮播图标题" clearable></el-input>
        </el-form-item>

        <el-form-item label="图片链接" prop="imageUrl">
          <el-input v-model="formData.imageUrl" placeholder="请输入图片链接地址" clearable>
            <template #append>
              <el-button @click="formData.imageUrl = 'https://via.placeholder.com/800x400'">使用示例</el-button>
            </template>
          </el-input>
          <div v-if="formData.imageUrl" style="margin-top: 10px;">
            <el-image :src="formData.imageUrl" style="width: 200px; height: 100px;" fit="cover" />
          </div>
        </el-form-item>

        <el-form-item label="跳转链接" prop="linkUrl">
          <el-input v-model="formData.linkUrl" placeholder="选填，点击轮播图跳转的链接地址" clearable></el-input>
        </el-form-item>

        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="formData.sortOrder" :min="0" :max="999" style="width: 100%"></el-input-number>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'BannerList',
  data() {
    return {
      loading: false,
      submitLoading: false,
      dialogVisible: false,
      dialogTitle: '新增轮播图',
      isEdit: false,
      searchForm: {
        keyword: '',
        status: null
      },
      allTableData: [
        {
          id: 1,
          title: '2025年全国武术锦标赛',
          imageUrl: 'https://via.placeholder.com/800x400/dc2626/ffffff?text=2025年全国武术锦标赛',
          linkUrl: '/martial/competition/list',
          sortOrder: 1,
          status: 1,
          createTime: '2025-11-20 10:00:00'
        },
        {
          id: 2,
          title: '青少年武术大赛',
          imageUrl: 'https://via.placeholder.com/800x400/991b1b/ffffff?text=青少年武术大赛',
          linkUrl: '/martial/competition/list',
          sortOrder: 2,
          status: 1,
          createTime: '2025-11-21 11:00:00'
        },
        {
          id: 3,
          title: '传统武术邀请赛',
          imageUrl: 'https://via.placeholder.com/800x400/dc2626/ffffff?text=传统武术邀请赛',
          linkUrl: '/martial/competition/list',
          sortOrder: 3,
          status: 0,
          createTime: '2025-11-22 14:00:00'
        }
      ],
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      formData: {
        id: null,
        title: '',
        imageUrl: '',
        linkUrl: '',
        sortOrder: 0,
        status: 1
      },
      rules: {
        title: [
          { required: true, message: '请输入轮播图标题', trigger: 'blur' }
        ],
        imageUrl: [
          { required: true, message: '请输入图片链接', trigger: 'blur' }
        ],
        sortOrder: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.loadBannerList()
  },
  methods: {
    // 从 localStorage 加载数据
    loadBannerList() {
      const savedData = localStorage.getItem('bannerList')
      if (savedData) {
        try {
          this.allTableData = JSON.parse(savedData)
        } catch (e) {
          console.error('加载轮播图数据失败', e)
        }
      } else {
        // 首次加载，保存默认数据
        this.saveBannerList()
      }
      this.fetchData()
    },

    // 保存数据到 localStorage
    saveBannerList() {
      localStorage.setItem('bannerList', JSON.stringify(this.allTableData))
    },

    // 获取数据
    fetchData() {
      this.loading = true

      setTimeout(() => {
        // 过滤数据
        let filteredData = [...this.allTableData]

        // 搜索过滤
        if (this.searchForm.keyword) {
          const keyword = this.searchForm.keyword.toLowerCase()
          filteredData = filteredData.filter(item =>
            item.title.toLowerCase().includes(keyword)
          )
        }

        // 状态过滤
        if (this.searchForm.status !== null && this.searchForm.status !== '') {
          filteredData = filteredData.filter(item => item.status === this.searchForm.status)
        }

        // 按排序字段排序
        filteredData.sort((a, b) => a.sortOrder - b.sortOrder)

        this.pagination.total = filteredData.length

        // 分页处理
        const start = (this.pagination.current - 1) * this.pagination.size
        const end = start + this.pagination.size
        this.tableData = filteredData.slice(start, end)

        this.loading = false
      }, 300)
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.fetchData()
    },

    // 重置
    handleReset() {
      this.searchForm = {
        keyword: '',
        status: null
      }
      this.pagination.current = 1
      this.fetchData()
    },

    // 分页
    handleSizeChange(size) {
      this.pagination.size = size
      this.fetchData()
    },

    handleCurrentChange(current) {
      this.pagination.current = current
      this.fetchData()
    },

    // 新增
    handleAdd() {
      this.dialogTitle = '新增轮播图'
      this.isEdit = false
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑轮播图'
      this.isEdit = true
      this.formData = { ...row }
      this.dialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确定删除该轮播图吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.allTableData.findIndex(item => item.id === row.id)
        if (index !== -1) {
          this.allTableData.splice(index, 1)
          this.saveBannerList()
          this.$message.success('删除成功')
          this.fetchData()
        }
      }).catch(() => {})
    },

    // 状态变更
    handleStatusChange(row) {
      const index = this.allTableData.findIndex(item => item.id === row.id)
      if (index !== -1) {
        this.allTableData[index].status = row.status
        this.saveBannerList()
        this.$message.success('状态更新成功')
      }
    },

    // 提交表单
    handleSubmit() {
      this.$refs.bannerForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true

          setTimeout(() => {
            if (this.isEdit) {
              // 编辑
              const index = this.allTableData.findIndex(item => item.id === this.formData.id)
              if (index !== -1) {
                this.allTableData[index] = { ...this.formData }
                this.$message.success('修改成功')
              }
            } else {
              // 新增
              const newId = this.allTableData.length > 0
                ? Math.max(...this.allTableData.map(item => item.id)) + 1
                : 1
              const now = new Date()
              const createTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`

              this.allTableData.push({
                ...this.formData,
                id: newId,
                createTime
              })
              this.$message.success('新增成功')
            }

            this.saveBannerList()
            this.dialogVisible = false
            this.fetchData()
            this.submitLoading = false
          }, 500)
        }
      })
    },

    // 关闭弹窗
    handleDialogClose() {
      this.$refs.bannerForm.resetFields()
      this.formData = {
        id: null,
        title: '',
        imageUrl: '',
        linkUrl: '',
        sortOrder: 0,
        status: 1
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.banner-container {
  min-height: 100%;
  padding: 15px;

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

    .page-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #2c3e50;
    }
  }

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

  .pagination {
    margin-top: 15px;
    text-align: right;
  }

  .dialog-footer {
    text-align: right;
  }
}
</style>
