<template>
  <div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" @click="handleAdd">新增Banner</el-button>
      </div>
      <el-table :data="tableData" v-loading="tableLoading" border stripe>
        <el-table-column prop="ID" label="ID" width="80" />
        <el-table-column prop="title" label="标题" width="200" />
        <el-table-column prop="link" label="链接" show-overflow-tooltip />
        <el-table-column label="图片" width="120">
          <template #default="{ row }">
            <el-image
              style="width: 100px; height: 60px"
              :src="row.img"
              :preview-src-list="[row.img]"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              :loading="row.loading"
              @change="() => handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.CreatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" @click="handleDelete(row)" style="color: #f56c6c">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
       <div class="gva-pagination">
        <el-pagination
          :current-page="queryParams.page"
          :page-size="queryParams.pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 新增/编辑Banner弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleClose"
    >
      <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="link">
          <el-input v-model="form.link" placeholder="请输入链接" />
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <selectImage v-model="form.img" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import selectImage from '@/components/selectImage/selectImage.vue'
import { list, creat, put, deleteBanner } from '@/api/banner/index.js'
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils/format'

const tableLoading = ref(true)
const tableData = ref([])
const total = ref(0)
const queryParams = ref({
  page: 1,
  pageSize: 10
})

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const form = ref({
  title: '',
  link: '',
  img: '',
  status: 1
})

const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ],
  link: [
    { required: true, message: '请输入链接', trigger: 'blur' }
  ],
  img: [
    { required: true, message: '请输入图片链接', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

onMounted(() => {
  getList()
})

async function getList() {
  tableLoading.value = true
  try {
    const res = await list(queryParams.value)
    if (res.code === 0) {
      tableData.value = res.data.list
      for (let item of tableData.value) {
        item.loading = false
      }
      total.value = res.data.total
    }
  } catch (error) {
    console.error(error)
  } finally {
    tableLoading.value = false
  }
}

const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  queryParams.value.page = 1
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.value.page = val
  getList()
}

function handleAdd() {
  dialogTitle.value = '新增Banner'
  form.value = {
    title: '',
    link: '',
    img: '',
    status: 1
  }
  dialogVisible.value = true
}

function handleEdit(row) {
  dialogTitle.value = '编辑Banner'
  form.value = { ...row }
  dialogVisible.value = true
}

function handleClose() {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

async function submitForm() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      let res
      if (form.value.ID) {
        // 编辑
        res = await put(form.value)
      } else {
        // 新增
        res = await creat(form.value)
      }
      
      if (res.code === 0) {
        ElMessage.success(form.value.ID ? '编辑成功' : '添加成功')
        handleClose()
        getList()
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    }
  })
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm('确定要删除这个Banner吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteBanner({ ID: row.ID })
    if (res.code === 0) {
      ElMessage.success('删除成功')
      getList()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    // 用户取消删除
  }
}

async function handleStatusChange(row) {
  row.loading = true
  try {
    const res = await put(row)
    if (res.code === 0) {
      ElMessage.success('状态修改成功')
    } else {
      ElMessage.error(res.msg || '状态修改失败')
      // 恢复原状态
      row.status = row.status === 1 ? 0 : 1
    }
  } catch (error) {
    ElMessage.error('状态修改失败')
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  } finally {
    row.loading = false
  }
}
</script>

<style lang="scss" scoped>
.gva-btn-list {
  margin-bottom: 20px;
}
.gva-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
