<script setup lang="ts">
/**
 * 首页轮播图管理
 *
 * 关键点：
 *  - 图片 URL 必填，支持输入完整 URL 或使用 /uploads/ 本地路径
 *  - linkType: 0=不跳转 1=商品 2=分类 3=外链；只有选了类型才需要填 linkValue
 *  - 状态切换 / 排序 / 删除 走独立接口；新增与编辑共用 BannerSavePayload
 *  - 时间区间可选；与后端 listActive() 配合，仅在生效时段内展示给用户端
 */
import { computed, reactive, ref } from 'vue'
import {
  Delete,
  Edit,
  Picture,
  Plus,
  Refresh,
  Search,
  Top,
  View
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  createBannerApi,
  deleteBannerApi,
  getBannerDetailApi,
  getBannerPageApi,
  updateBannerApi,
  updateBannerSortApi,
  updateBannerStatusApi
} from '@/api/banner'
import type {
  BannerItem,
  BannerLinkType,
  BannerPageQuery,
  BannerSavePayload,
  BannerStatus
} from '@/api/banner'
import { formatDate } from '@/utils/date'
import SearchBar from '@/components/common/SearchBar.vue'

// ============================================================
// 列表
// ============================================================
const loading = ref(false)
const list = ref<BannerItem[]>([])
const total = ref(0)

const query = reactive<BannerPageQuery>({
  current: 1,
  size: 10,
  keyword: '',
  status: undefined
})

async function fetchData() {
  loading.value = true
  try {
    const res = await getBannerPageApi(query)
    list.value = res.records
    total.value = res.total
  } finally {
    loading.value = false
  }
}

function handleReset() {
  query.keyword = ''
  query.status = undefined
  query.current = 1
  fetchData()
}

// ============================================================
// 上下线 / 排序 / 删除
// ============================================================
async function handleToggleStatus(row: BannerItem) {
  try {
    const next: BannerStatus = row.status === 1 ? 0 : 1
    await updateBannerStatusApi(row.id, next)
    ElMessage.success(next === 1 ? '已上线' : '已下线')
    fetchData()
  } catch {
    /* 拦截器已提示 */
  }
}

async function handleEditSort(row: BannerItem) {
  let value: number | null = row.sort
  try {
    const { value: input } = await ElMessageBox.prompt('请输入新的排序号（升序展示，数字越小越靠前）', '调整排序', {
      inputValue: String(row.sort ?? 0),
      inputValidator: (val) => (/^-?\d+$/.test(val) ? true : '请输入整数')
    })
    value = Number(input)
  } catch {
    return
  }
  try {
    await updateBannerSortApi(row.id, value ?? 0)
    ElMessage.success('排序已更新')
    fetchData()
  } catch {
    /* 拦截器已提示 */
  }
}

async function handleDelete(row: BannerItem) {
  await ElMessageBox.confirm(
    `确定要删除轮播图【${row.title || '未命名'}】吗？该操作不可恢复。`,
    '提示',
    { type: 'warning' }
  )
  try {
    await deleteBannerApi(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch {
    /* 拦截器已提示 */
  }
}

// ============================================================
// 新增 / 编辑弹窗
// ============================================================
const dialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit'>('create')
const dialogTitle = computed(() => (dialogMode.value === 'edit' ? '编辑轮播图' : '新增轮播图'))
const formRef = ref<FormInstance>()
const submitting = ref(false)

interface FormState {
  id?: number
  title: string
  image: string
  linkType: BannerLinkType
  linkValue: string
  sort: number
  status: BannerStatus
  startTime: string
  endTime: string
}

function emptyForm(): FormState {
  return {
    id: undefined,
    title: '',
    image: '',
    linkType: 0,
    linkValue: '',
    sort: 0,
    status: 1,
    startTime: '',
    endTime: ''
  }
}

const form = reactive<FormState>(emptyForm())

const rules: FormRules<FormState> = {
  image: [{ required: true, message: '请输入图片 URL', trigger: 'blur' }],
  linkValue: [
    {
      validator: (_r, val, cb) => {
        if (form.linkType === 0) return cb()
        if (!val || !val.trim()) return cb(new Error('请填写跳转目标'))
        if (form.linkType === 1 && !/^\d+$/.test(val.trim())) {
          return cb(new Error('跳转商品时目标值必须为商品 ID（数字）'))
        }
        if (form.linkType === 2 && !/^\d+$/.test(val.trim())) {
          return cb(new Error('跳转分类时目标值必须为分类 ID（数字）'))
        }
        if (form.linkType === 3 && !/^https?:\/\//i.test(val.trim())) {
          return cb(new Error('外链必须以 http:// 或 https:// 开头'))
        }
        cb()
      },
      trigger: 'blur'
    }
  ]
}

const LINK_TYPE_LABELS: Record<BannerLinkType, string> = {
  0: '不跳转',
  1: '商品详情',
  2: '分类页',
  3: '外链'
}

const LINK_TYPE_PLACEHOLDER: Record<BannerLinkType, string> = {
  0: '无需填写',
  1: '商品 ID，例如 1001',
  2: '分类 ID，例如 2',
  3: 'https://example.com/promo'
}

async function openCreate() {
  dialogMode.value = 'create'
  formRef.value?.resetFields()
  Object.assign(form, emptyForm())
  dialogVisible.value = true
}

async function openEdit(row: BannerItem) {
  dialogMode.value = 'edit'
  formRef.value?.resetFields()
  let detail: BannerItem | null = null
  try {
    detail = await getBannerDetailApi(row.id)
  } catch {
    detail = row
  }
  Object.assign(form, {
    id: detail!.id,
    title: detail!.title ?? '',
    image: detail!.image ?? '',
    linkType: (detail!.linkType ?? 0) as BannerLinkType,
    linkValue: detail!.linkValue ?? '',
    sort: detail!.sort ?? 0,
    status: (detail!.status ?? 1) as BannerStatus,
    startTime: detail!.startTime ?? '',
    endTime: detail!.endTime ?? ''
  })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitting.value = true
    try {
      const payload: BannerSavePayload = {
        id: form.id,
        image: form.image.trim(),
        title: form.title?.trim() || undefined,
        linkType: form.linkType,
        linkValue: form.linkType === 0 ? undefined : form.linkValue?.trim() || undefined,
        sort: form.sort ?? 0,
        status: form.status,
        startTime: form.startTime || undefined,
        endTime: form.endTime || undefined
      }
      if (dialogMode.value === 'create') {
        await createBannerApi(payload)
        ElMessage.success('新增成功')
      } else {
        await updateBannerApi(payload)
        ElMessage.success('更新成功')
      }
      dialogVisible.value = false
      await fetchData()
    } catch {
      /* 拦截器已提示 */
    } finally {
      submitting.value = false
    }
  })
}

// ============================================================
// 图片预览
// ============================================================
const previewVisible = ref(false)
const previewImage = ref('')
function openPreview(row: BannerItem) {
  previewImage.value = row.image
  previewVisible.value = true
}
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <div>
        <h2>轮播图管理</h2>
        <p class="page-desc">配置首页轮播图，支持跳转商品 / 分类 / 外链，定时上下线</p>
      </div>
      <el-button type="primary" :icon="Plus" @click="openCreate">新增轮播图</el-button>
    </div>

    <el-card shadow="never" class="table-card">
      <SearchBar show-divider>
        <el-input
          v-model="query.keyword"
          placeholder="标题关键字"
          :prefix-icon="Search"
          clearable
          style="width: 200px"
          @keyup.enter="fetchData"
        />
        <el-select v-model="query.status" placeholder="状态" clearable style="width: 120px">
          <el-option label="已上线" :value="1" />
          <el-option label="已下线" :value="0" />
        </el-select>
        <el-button type="primary" :icon="Search" @click="fetchData">搜索</el-button>
        <el-button :icon="Refresh" @click="handleReset">重置</el-button>
      </SearchBar>

      <el-table v-loading="loading" :data="list" stripe border>
        <el-table-column type="index" label="#" width="60" align="center" />
        <el-table-column label="图片" width="160" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.image"
              :src="row.image"
              fit="cover"
              class="banner-thumb"
              :preview-src-list="[row.image]"
              hide-on-click-modal
            />
            <el-tag v-else type="info" size="small">暂无</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="标题" min-width="200">
          <template #default="{ row }">
            <span class="title-text">{{ row.title || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="跳转" width="220">
          <template #default="{ row }">
            <el-tag size="small" :type="row.linkType === 0 ? 'info' : 'primary'">
              {{ LINK_TYPE_LABELS[row.linkType as BannerLinkType] }}
            </el-tag>
            <span v-if="row.linkType !== 0" class="link-value">{{ row.linkValue || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="排序" width="100" align="center">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleEditSort(row as BannerItem)">
              <el-icon><Top /></el-icon>
              {{ (row as BannerItem).sort ?? 0 }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="生效时段" width="240">
          <template #default="{ row }">
            <div v-if="(row as BannerItem).startTime || (row as BannerItem).endTime" class="time-cell">
              {{ (row as BannerItem).startTime ? formatDate((row as BannerItem).startTime, 'YYYY-MM-DD HH:mm') : '不限' }}
              <span class="dash">~</span>
              {{ (row as BannerItem).endTime ? formatDate((row as BannerItem).endTime, 'YYYY-MM-DD HH:mm') : '不限' }}
            </div>
            <div v-else class="muted">不限</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <span :class="['status-dot', (row as BannerItem).status === 1 ? 'success' : 'info']">
              {{ (row as BannerItem).status === 1 ? '已上线' : '已下线' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="170">
          <template #default="{ row }">{{ formatDate((row as BannerItem).createTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" :icon="View" @click="openPreview(row as BannerItem)">
              预览
            </el-button>
            <el-button link type="primary" size="small" :icon="Edit" @click="openEdit(row as BannerItem)">
              编辑
            </el-button>
            <el-button
              link
              :type="(row as BannerItem).status === 1 ? 'warning' : 'success'"
              size="small"
              @click="handleToggleStatus(row as BannerItem)"
            >
              {{ (row as BannerItem).status === 1 ? '下线' : '上线' }}
            </el-button>
            <el-button link type="danger" size="small" :icon="Delete" @click="handleDelete(row as BannerItem)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="query.current"
          v-model:page-size="query.size"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @current-change="fetchData"
          @size-change="fetchData"
        />
      </div>
    </el-card>

    <!-- 新增 / 编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="640px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="图片 URL" prop="image">
          <el-input
            v-model="form.image"
            placeholder="支持 https:// 链接或 /uploads/ 本地路径"
            clearable
          />
          <div v-if="form.image" class="image-preview">
            <el-image :src="form.image" fit="cover" class="preview-thumb" />
          </div>
        </el-form-item>
        <el-form-item label="标题">
          <el-input
            v-model="form.title"
            placeholder="选填，例：双 11 大促"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="跳转类型">
          <el-radio-group v-model="form.linkType">
            <el-radio :value="0">不跳转</el-radio>
            <el-radio :value="1">商品详情</el-radio>
            <el-radio :value="2">分类页</el-radio>
            <el-radio :value="3">外链</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.linkType !== 0" label="跳转目标" prop="linkValue">
          <el-input
            v-model="form.linkValue"
            :placeholder="LINK_TYPE_PLACEHOLDER[form.linkType]"
            clearable
          />
        </el-form-item>
        <el-form-item label="排序号">
          <el-input-number v-model="form.sort" :min="0" :max="9999" controls-position="right" />
          <span class="form-hint">升序展示，数字越小越靠前</span>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-text="上线"
            inactive-text="下线"
          />
        </el-form-item>
        <el-form-item label="生效时段">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="生效时间（不填 = 立即生效）"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 45%"
          />
          <span style="margin: 0 8px">至</span>
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="失效时间（不填 = 长期有效）"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 45%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览弹窗 -->
    <el-dialog
      v-model="previewVisible"
      title="图片预览"
      width="720px"
      destroy-on-close
      align-center
    >
      <el-image
        v-if="previewImage"
        :src="previewImage"
        fit="contain"
        style="width: 100%; max-height: 540px"
      />
      <el-empty v-else description="暂无图片" :image-size="80">
        <template #image>
          <el-icon :size="48" color="#c0c4cc"><Picture /></el-icon>
        </template>
      </el-empty>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.banner-thumb {
  width: 120px;
  height: 60px;
  border-radius: 6px;
  background: #f5f7fa;
  border: 1px solid $color-border-light;
}
.title-text {
  font-weight: 500;
  color: $color-text-primary;
}
.link-value {
  margin-left: 8px;
  font-size: 12px;
  color: $color-text-secondary;
  word-break: break-all;
}
.time-cell {
  font-size: 12px;
  color: $color-text-secondary;
  .dash {
    margin: 0 4px;
  }
}
.muted {
  color: $color-text-secondary;
  font-size: 12px;
}
.status-dot {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 10px;
  font-size: 12px;
  &.success {
    background: rgba(16, 185, 129, 0.1);
    color: $color-success;
  }
  &.info {
    background: rgba(156, 163, 175, 0.15);
    color: $color-text-secondary;
  }
}
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 16px 20px;
}
.image-preview {
  margin-top: 8px;
}
.preview-thumb {
  width: 200px;
  height: 100px;
  border-radius: 6px;
  border: 1px solid $color-border-light;
  background: #f5f7fa;
}
.form-hint {
  margin-left: 12px;
  font-size: 12px;
  color: $color-text-secondary;
}
</style>
