<script setup lang="ts">
import { Search, Upload } from '@element-plus/icons-vue'
import { usePageSearch, useResetData } from '@/hooks'
import { addOrUpdateColumn } from '@/api/backend'
import { getArticleList, updateArticleRecommendAndSort } from '@/api'
import type { FormInstance, FormRules } from 'element-plus'
import type { BackendColumnListItemDto, AddOrUpdateColumnDto } from '@/api/backend'
import dayjs from 'dayjs'
import { ArticleTypeEnum, BooleanFlag } from '@/constants'
import type { ArticleItemDto } from '@/api/article/types'
import { push } from 'notivue'
const { loading, list, total, reset, goToPage, changePageSize, refresh, searchParams, search } =
  usePageSearch(getArticleList, {
    defaultParams: {
      type: ArticleTypeEnum.VIDEO,
    },
  })

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

// 表单数据

const [form] = useResetData<AddOrUpdateColumnDto>({
  title: '',
  color: '#000000',
  id: undefined,
  sort: 0,
  type: 'column',
})
// 表单验证规则
const formRules: FormRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  color: [{ required: true, message: '请选择颜色', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
}

// 是否推荐改变
const handleIsRecommendChange = async (val: BooleanFlag, row: ArticleItemDto) => {
  await updateArticleRecommendAndSort({
    articleId: row.id,
    recommendSort: 0, // 默认传 0
    isRecommend: val,
  })
  push.success('修改成功')
  refresh()
}

// 编辑排序
const handleEditSort = async (row: ArticleItemDto) => {
  const { value } = await ElMessageBox.prompt('请输入排序值', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    // 数字
    inputPattern: /^\d+$/,
    inputErrorMessage: '请输入数字',
  })
  await updateArticleRecommendAndSort({
    articleId: row.id,
    recommendSort: Number(value),
    isRecommend: BooleanFlag.YES,
  })
  push.success('修改成功')
  refresh()
}

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

  try {
    await formRef.value.validate()

    if (form.value.id) {
      await addOrUpdateColumn(form.value)
    } else {
      await addOrUpdateColumn(form.value)
    }

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

const selectedRows = ref<BackendColumnListItemDto[]>([])
// 选择
const handleSelectionChange = (selection: BackendColumnListItemDto[]) => {
  selectedRows.value = selection
}
</script>

<template>
  <div class="official-tag-page">
    <!-- 搜索栏 -->
    <div class="search-section">
      <el-input
        v-model="searchParams.title"
        placeholder="请输入标题"
        class="w-200px mr-12px"
      ></el-input>
      <el-button type="primary" :icon="Search" @click="refresh">搜索</el-button>
      <el-button @click="reset">重置</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <!-- 表格 -->
      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="list"
          height="100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column prop="title" label="视频标题" min-width="200" />
          <el-table-column prop="content" label="视频简介" min-width="200" />
          <el-table-column prop="faceUrl" label="视频封面" width="300">
            <template #default="{ row }">
              <el-image
                :preview-teleported="true"
                :src="row.faceUrl"
                class="w-20 h-20 object-cover"
                :preview-src-list="[row.faceUrl]"
              />
            </template>
          </el-table-column>
          <el-table-column prop="videoUrl" label="视频地址" min-width="200">
            <template #default="{ row }">
              <el-link type="primary" :href="row.videoUrl" target="_blank" :underline="false">
                {{ row.videoUrl }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="releaseStatus" label="标签" min-width="200">
            <template #default="{ row }">
              <el-tag
                v-for="tag in row.tagNameList"
                :key="tag.tagId"
                type="primary"
                class="mr-2! mb-2!"
              >
                {{ tag }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="是否推荐" min-width="200">
            <template #header>
              <div class="flex items-center gap-2">
                <span>是否推荐</span>
                <el-tooltip content="推荐后前台将按照排序值从大到小展示" placement="top">
                  <el-icon><IEpInfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <template #default="{ row }">
              <div class="flex items-center gap-2">
                <el-switch
                  :model-value="row.isRecommend"
                  :active-value="BooleanFlag.YES"
                  :inactive-value="BooleanFlag.NO"
                  @change="(val) => handleIsRecommendChange(val as BooleanFlag, row)"
                />
                <el-link
                  v-if="row.isRecommend"
                  class="flex items-center gap-2"
                  type="primary"
                  @click="handleEditSort(row)"
                  :underline="false"
                  >排序值：{{ row.recommendSort }}</el-link
                >
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="showName" label="创建人" min-width="200" />

          <el-table-column prop="createTime" label="创建时间" min-width="200">
            <template #default="{ row }">
              {{ dayjs(row.createTime * 1000).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <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>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="form.color" />
          <span class="color-value">{{ form.color }}</span>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="100" />
        </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>
  </div>
</template>

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

// 搜索区域
.search-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px 0;
  flex-shrink: 0;

  .search-select {
    width: 200px;
  }
}

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

.table-wrapper {
  flex: 1;
  min-height: 0;

  .color-cell {
    display: flex;
    align-items: center;
    gap: 12px;

    .color-block {
      width: 100%;
      height: 36px;
      border-radius: 4px;
      border: 1px solid #e5e7eb;
      flex: 1;
    }

    .color-text {
      color: #fff;
      font-size: 14px;
      font-weight: 500;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      text-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
    }
  }
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  flex-shrink: 0;
}

// 对话框内的颜色显示
.color-value {
  margin-left: 12px;
  color: #606266;
  font-family: monospace;
}

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