<!-- views/backend/carousel/index.vue -->
<template>
  <div class="carousel-page">
    <!-- 顶部操作栏 -->
    <div class="action-section">
      <el-button type="primary" :icon="Search" @click="getList">搜索</el-button>
      <el-button type="primary" class="add-btn" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table v-loading="loading" :data="list">
        <!-- <el-table-column type="selection" width="55" /> -->

        <el-table-column prop="image" label="资源图" min-width="300">
          <template #default="{ row }">
            <div class="image-cell">
              <el-image
                :src="row.assetUrl"
                fit="cover"
                class="carousel-image"
                :preview-src-list="[row.assetUrl]"
                :preview-teleported="true"
              />
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="url" label="跳转文章标题" width="300" align="center">
          <template #default="{ row }">
            <el-link :underline="false" type="primary" @click="handleOpenNewTab(row.url)">
              {{ row.articleTitle }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="100" align="center" />

        <el-table-column prop="type" label="类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.type === 0 ? 'success' : 'primary'">
              {{ row.type === 0 ? '图片' : '视频' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="creator" label="操作人" width="200">
          <template #default="{ row }">
            <div class="creator-info">
              <div>{{ row.lastName }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-alert
        title="未选择对应的文章，则不跳转"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      />

      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <!-- <el-form-item label="轮播类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :value="0">图片</el-radio>
            <el-radio :value="1">视频</el-radio>
          </el-radio-group>
        </el-form-item> -->

        <el-form-item label="显示资源" prop="assetUrl">
          <div class="upload-section">
            <UploadFile v-model="form.assetUrl" :limit="1" />
            <div class="upload-hint">上传图片，推荐比例为 W/H: 4 / 1</div>
          </div>
        </el-form-item>

        <el-form-item label="跳转文章标题" prop="url">
          <span class="mr-2">{{ form.articleTitle }}</span>
          <el-link :underline="false" @click="articleDialogVisible = true">请选择</el-link>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="form.sort"
            :min="0"
            :max="100"
            controls-position="right"
            style="width: 60%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          <el-icon class="btn-icon"><Upload /></el-icon>
          保存
        </el-button>
      </template>

      <el-dialog v-model="articleDialogVisible" title="选择文章" width="850px">
        <!-- 类型选择 -->
        <div class="flex items-center gap-2 mb-2">
          <el-input v-model="searchParams.title" placeholder="请输入文章标题" />
          <el-select v-model="searchParams.type" placeholder="请选择文章类型">
            <el-option
              v-for="item in articleTypeListOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button type="primary" @click="handleSearchArticle"> 搜索 </el-button>
        </div>

        <!-- 文章列表 -->
        <el-table :data="articleList" style="width: 100%">
          <el-table-column prop="title" label="标题">
            <template #default="{ row }">
              <el-link :underline="false" type="primary" @click="handlePreviewArticle(row)">
                {{ row.title }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="100" tooltip-effect="dark">
            <template #default="{ row }">
              <el-tag type="primary">
                {{ articleTypeListOptions.find((item) => item.value === row.type)?.label }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="200">
            <template #default="{ row }">
              {{ dayjs(row.createTime * 1000 || 0).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column prop="showName" label="创建人" width="150" />
          <el-table-column prop="showName" label="操作" width="80">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleSelectArticle(row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-show="articleList.length" class="flex justify-end mt-2">
          <el-pagination
            v-model:current-page="searchParams.current"
            v-model:page-size="searchParams.size"
            :total="total"
            :page-sizes="[10, 20, 30]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="changePageSize"
            @current-change="goToPage"
          />
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Search, Plus, Upload } from '@element-plus/icons-vue'
import { useResetData } from '@/hooks'
import { getCarouselList, addCarousel, editCarousel, getArticleList } from '@/api/backend'
import type { FormInstance, FormRules } from 'element-plus'
import UploadFile from '@/components/common/UploadFile/index.vue'

import type {
  AddOrUpdateCarouselDto,
  BackendArticleListItemDto,
  BackendCarouselListItemDto,
} from '@/api/backend'
import { ArticleTypeEnum, articleTypeListOptions } from '@/constants'
import { usePageSearch } from '@/hooks'
import dayjs from 'dayjs'

// 列表数据
const loading = ref(false)
const list = ref<BackendCarouselListItemDto[]>([])

// 获取列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getCarouselList()
    list.value = res.data
  } finally {
    loading.value = false
  }
}

// 对话框
const dialogVisible = ref(false)
const dialogTitle = computed(() => (form.value.id ? '编辑轮播' : '新增轮播'))
const formRef = ref<FormInstance>()

// 表单数据
const [form, resetForm] = useResetData<AddOrUpdateCarouselDto>({
  type: 0,
  assetUrl: '',
  url: '',
  sort: 0,
  id: undefined,
  isRelease: 1,
  articleTitle: '',
})

// 表单验证规则
const formRules: FormRules = {
  type: [{ required: true, message: '请选择轮播类型', trigger: 'change' }],
  assetUrl: [{ required: true, message: '请上传资源', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
}

// 新增
const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: BackendCarouselListItemDto) => {
  resetForm()
  form.value = {
    type: row.type,
    assetUrl: row.assetUrl,
    url: row.url,
    sort: row.sort,
    id: row.id,
    isRelease: row.isRelease,
    articleTitle: row.articleTitle,
  }
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: BackendCarouselListItemDto) => {
  try {
    await ElMessageBox.confirm('确定要删除该轮播吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await editCarousel({
      ...row,
      id: row.id,
      isRelease: 0, // 状态设置为0
    })

    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    if (form.value.id) {
      await editCarousel(form.value)
    } else {
      await addCarousel(form.value)
    }

    ElMessage.success(form.value.id ? '编辑成功' : '新增成功')
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const articleDialogVisible = ref(false)

const {
  list: articleList,
  searchParams,
  refresh,
  total,
  changePageSize,
  goToPage,
  clear,
} = usePageSearch(getArticleList, {
  defaultParams: {
    title: '',
    type: ArticleTypeEnum.POST,
  },
  immediate: false,
})

const handleSearchArticle = async () => {
  refresh()
}

const handleOpenNewTab = (url: string) => {
  window.open(url)
}

const handlePreviewArticle = (row: BackendArticleListItemDto) => {
  if (row.type === ArticleTypeEnum.VIDEO) {
    window.open(`/videoDetail/${row.id}`)
  } else {
    window.open(`/articleDetail/${row.id}`)
  }
}

const handleSelectArticle = (row: BackendArticleListItemDto) => {
  if (row.type === ArticleTypeEnum.VIDEO) {
    form.value.url = `/videoDetail/${row.id}`
  } else {
    form.value.url = `/articleDetail/${row.id}`
  }
  form.value.articleTitle = row.title
  // 重置表单列表
  clear()
  articleDialogVisible.value = false
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.carousel-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

// 操作区域
.action-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  gap: 12px;
  flex-shrink: 0;

  .add-btn {
    margin-left: auto;
  }
}

// 表格区域
.table-section {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  min-height: 0;
  overflow: auto;
}

// 图片单元格
.image-cell {
  padding: 8px 0;

  .carousel-image {
    width: 240px;
    height: 90px;
    border-radius: 4px;
    cursor: pointer;
  }
}

// 操作人信息
.creator-info {
  .create-time {
    color: #909399;
    font-size: 12px;
    margin-top: 4px;
  }
}

// 上传区域
.upload-section {
  width: 100%;

  .upload-hint {
    color: #409eff;
    font-size: 12px;
    margin-top: 8px;
  }
}

.btn-icon {
  margin-right: 4px;
}
</style>
