<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.title"
            placeholder="搜索轮播图标题"
            clearable
            size="small"
            style="width: 240px"
          >
            <template #prefix>
              <i class="el-input__icon el-icon-search"></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.position" 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="2"></el-option>
            <el-option label="其他" :value="3"></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"
              :hide-on-click-modal="false"
              :preview-teleported="true"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <div>加载失败</div>
                </div>
              </template>
            </el-image>
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="position" label="显示位置" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getPositionType(scope.row.position)" size="small">
              {{ getPositionText(scope.row.position) }}
            </el-tag>
          </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="clickCount" label="点击次数" width="100" align="center"></el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="160"></el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="160"></el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="pagination.total > 0"
        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, jumper"
        :total="pagination.total"
      ></el-pagination>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      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="position">
          <el-select v-model="formData.position" placeholder="请选择显示位置" style="width: 100%">
            <el-option label="首页" :value="1"></el-option>
            <el-option label="赛事详情" :value="2"></el-option>
            <el-option label="其他" :value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="图片" prop="imageUrl">
          <div class="image-upload-wrapper">
            <div v-if="formData.imageUrl" class="image-preview">
              <el-image
                :src="formData.imageUrl"
                class="preview-image"
                fit="cover"
                :preview-src-list="[formData.imageUrl]"
              />
              <div class="image-actions">
                <el-button type="primary" size="small" @click.stop="handleChangeImage">更换图片</el-button>
                <el-button type="danger" size="small" @click.stop="handleRemoveImage">删除图片</el-button>
              </div>
            </div>
            <el-button v-else type="primary" icon="el-icon-upload" @click.stop="handleOpenUpload">
              上传图片
            </el-button>
          </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="startTime">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            placeholder="选择开始显示时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="formData.endTime"
            type="datetime"
            placeholder="选择结束显示时间"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>

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

    <!-- 图片上传对话框 -->
    <el-dialog
      title="上传轮播图"
      v-model="uploadDialogVisible"
      width="555px"
      append-to-body
      :close-on-click-modal="false"
    >
      <avue-form
        ref="uploadForm"
        :option="uploadOption"
        v-model="uploadForm"
        :upload-after="uploadAfter"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getBannerList, submitBanner, removeBanner } from '@/api/martial/banner'
import { Picture } from '@element-plus/icons-vue'

export default {
  name: 'BannerList',
  components: {
    Picture
  },
  data() {
    return {
      loading: false,
      submitLoading: false,
      dialogVisible: false,
      dialogTitle: '新增轮播图',
      isEdit: false,
      uploadDialogVisible: false,
      uploadForm: {},
      searchForm: {
        title: '',
        position: null
      },
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      formData: {
        id: null,
        title: '',
        position: 1,
        imageUrl: '',
        linkUrl: '',
        sortOrder: 0,
        startTime: '',
        endTime: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入轮播图标题', trigger: 'blur' }
        ],
        position: [
          { required: true, message: '请选择显示位置', trigger: 'change' }
        ],
        imageUrl: [
          { required: true, message: '请输入图片链接', trigger: 'blur' }
        ],
        sortOrder: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]
      },
      uploadOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '轮播图上传',
            prop: 'bannerImage',
            type: 'upload',
            drag: true,
            loadText: '图片上传中，请稍等',
            span: 24,
            accept: 'image/*',
            tip: '建议尺寸：800x400像素，支持 JPG、PNG 格式，大小不超过 2MB',
            propsHttp: {
              res: 'data',
            },
            action: '/blade-resource/oss/endpoint/put-file'
          }
        ]
      }
    }
  },
  mounted() {
    this.loadBannerList()
  },
  methods: {
    // 加载轮播图列表
    loadBannerList() {
      this.loading = true
      const params = {}
      if (this.searchForm.title) {
        params.title = this.searchForm.title
      }
      if (this.searchForm.position !== null && this.searchForm.position !== '') {
        params.position = this.searchForm.position
      }

      getBannerList(this.pagination.current, this.pagination.size, params)
        .then(res => {
          console.log('轮播图列表返回数据:', res)
          const responseData = res.data?.data
          if (responseData && responseData.records) {
            this.tableData = responseData.records
            this.pagination.total = responseData.total || 0
            // 调试：打印每条记录的 imageUrl
            this.tableData.forEach((item, index) => {
              console.log(`记录 ${index + 1} - imageUrl:`, item.imageUrl)
            })
          }
        })
        .catch(err => {
          console.error('加载轮播图列表失败', err)
          this.$message.error('加载轮播图列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 获取位置文本
    getPositionText(position) {
      const positionMap = {
        1: '首页',
        2: '赛事详情',
        3: '其他'
      }
      return positionMap[position] || '未知'
    },

    // 获取位置标签类型
    getPositionType(position) {
      const typeMap = {
        1: 'success',
        2: 'primary',
        3: 'info'
      }
      return typeMap[position] || ''
    },

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

    // 重置
    handleReset() {
      this.searchForm = {
        title: '',
        position: null
      }
      this.pagination.current = 1
      this.loadBannerList()
    },

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

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

    // 新增
    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(() => {
        this.loading = true
        removeBanner(row.id.toString())
          .then(res => {
            this.$message.success('删除成功')
            this.loadBannerList()
          })
          .catch(err => {
            console.error('删除失败', err)
            this.$message.error('删除失败')
          })
          .finally(() => {
            this.loading = false
          })
      }).catch(() => {})
    },

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

          const submitData = { ...this.formData }
          // 如果是编辑模式，需要传入 id
          if (!this.isEdit) {
            delete submitData.id
          }

          submitBanner(submitData)
            .then(res => {
              this.$message.success(this.isEdit ? '修改成功' : '新增成功')
              this.dialogVisible = false
              this.loadBannerList()
            })
            .catch(err => {
              console.error('保存失败', err)
              this.$message.error(this.isEdit ? '修改失败' : '新增失败')
            })
            .finally(() => {
              this.submitLoading = false
            })
        }
      })
    },

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

    // 打开上传对话框
    handleOpenUpload() {
      console.log('打开上传对话框')
      this.uploadDialogVisible = true
      this.uploadForm = {}
    },

    // 更换图片
    handleChangeImage() {
      console.log('更换图片')
      this.uploadDialogVisible = true
      this.uploadForm = {}
    },

    // 删除图片
    handleRemoveImage() {
      console.log('删除图片')
      this.$confirm('确定删除当前图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formData.imageUrl = ''
        this.$message.success('删除成功')
      }).catch(() => {})
    },

    // 上传成功回调
    uploadAfter(res, done, loading, column) {
      console.log('uploadAfter 触发')
      console.log('上传响应:', res)
      console.log('done:', done)
      console.log('loading:', loading)
      console.log('column:', column)

      if (res && res.link) {
        this.formData.imageUrl = res.link
        this.$message.success('图片上传成功')
        this.uploadDialogVisible = false
      } else if (res && res.url) {
        this.formData.imageUrl = res.url
        this.$message.success('图片上传成功')
        this.uploadDialogVisible = false
      } else {
        this.$message.error('上传失败，未获取到图片地址')
      }
      done()
    }
  }
}
</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;
  }

  .image-upload-wrapper {
    .image-preview {
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 10px;

      .preview-image {
        width: 100%;
        height: 200px;
        display: block;
        margin-bottom: 10px;
        border-radius: 4px;
      }

      .image-actions {
        display: flex;
        gap: 10px;
        justify-content: center;
      }
    }
  }

  .image-error {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    font-size: 12px;
    color: #999;
    background-color: #f5f7fa;

    .el-icon {
      font-size: 24px;
      margin-bottom: 5px;
    }
  }
}
</style>
