<template>
  <el-container class="video-post-container">
    <el-header height="auto" class="post-header">
      <div class="header-wrapper">
        <h3 class="page-title">
          <i class="el-icon-collection" /> 稿件管理
        </h3>
        <div class="filter-controls">
          <el-select
            v-model="queryInfo.scope"
            clearable
            placeholder="可见范围筛选"
            size="small"
            class="filter-select"
            @change="handleFilterChange"
          >
            <el-option label="全部范围" :value="null" />
            <el-option label="本人可见" :value="1" />
            <el-option label="所有人可见" :value="2" />
            <el-option label="VIP 可见" :value="3" />
          </el-select>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            class="publish-btn"
            @click="handlePost"
          >发布稿件</el-button>
        </div>
      </div>
    </el-header>

    <el-main class="post-main">
      <div class="table-card">
        <el-table
          v-loading="loading"
          :data="dataList"
          style="width: 100%"
          header-cell-class-name="table-header-cell"
        >
          <el-table-column label="No" type="index" width="60" align="center" />

          <el-table-column label="封面" width="120" align="center">
            <template slot-scope="scope">
              <el-image
                class="video-cover"
                :src="scope.row.coverUrl"
                fit="cover"
                :preview-src-list="[scope.row.coverUrl]"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline" />
                </div>
              </el-image>
            </template>
          </el-table-column>

          <el-table-column prop="title" label="视频信息" min-width="200">
            <template slot-scope="scope">
              <div class="video-info-cell">
                <router-link :to="`/video/${scope.row.videoId}`" class="video-title-link">
                  {{ scope.row.title }}
                </router-link>
                <div class="video-meta">
                  <span class="vid-tag">ID: {{ scope.row.videoId }}</span>
                  <span class="duration-tag"><i class="el-icon-time" /> {{ scope.row.duration }}</span>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="pubDate" label="发布时间" width="160" align="center" />

          <el-table-column label="可见范围" width="130" align="center">
            <template slot-scope="scope">
              <el-tooltip content="点击修改可见范围" placement="top">
                <div class="scope-pointer" @click="handleScope(scope.$index, scope.row)">
                  <el-tag v-if="scope.row.scope === 1" size="medium" type="info" effect="plain">本人可见</el-tag>
                  <el-tag v-else-if="scope.row.scope === 2" size="medium" type="success" effect="plain">所有人可见</el-tag>
                  <el-tag v-else-if="scope.row.scope === 3" size="medium" type="warning" effect="plain">VIP 可见</el-tag>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column label="稿件状态" width="120" align="center">
            <template slot-scope="scope">
              <span :class="['status-dot', getStatusClass(scope.row.status)]">
                {{ getStatusText(scope.row.status) }}
              </span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="220" fixed="right" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" icon="el-icon-view" @click="handlePreview(scope.$index, scope.row)">预览</el-button>
              <el-button type="text" size="small" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" size="small" icon="el-icon-delete" class="danger-text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            background
            :small="screenWidth <= 768"
            layout="total, prev, pager, next, jumper"
            :page-size="pageSize"
            :current-page="currentPage"
            :total="totalSize"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </el-main>

    <el-dialog
      :visible.sync="publishVideoDiaglog"
      width="70%"
      custom-class="custom-glass-dialog"
      append-to-body
      destroy-on-close
      @close="editingVideo = null"
    >
      <div slot="title" class="dialog-header-custom">
        <i :class="editingVideo ? 'el-icon-edit' : 'el-icon-circle-plus-outline'" />
        <span>{{ editingVideo ? '编辑视频稿件' : '发布新视频稿件' }}</span>
      </div>

      <video-post-publish
        :video-info="editingVideo"
        @video-publish="onVideoPublish"
      />
    </el-dialog>

    <el-dialog :visible.sync="showEditScopeDialog" width="400px" custom-class="custom-glass-dialog compact-dialog" append-to-body center>
      <div slot="title" class="dialog-header-custom">
        <i class="el-icon-lock" /><span>权限设置</span>
      </div>
      <div class="dialog-body-padding">
        <p class="input-label-tip">请选择该视频的可见范围：</p>
        <el-select v-model="form.scope" placeholder="选择可见范围" style="width: 100%">
          <el-option label="本人可见" value="1" />
          <el-option label="所有人可见" value="2" />
          <el-option label="VIP 可见" value="3" />
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" round @click="showEditScopeDialog = false">取 消</el-button>
        <el-button size="small" type="primary" round @click="onUpdateScope">确认更新</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="showPreviewDialog" width="900px" top="8vh" custom-class="custom-glass-dialog preview-dialog" append-to-body @close="handleDialogClose(()=> { showPreviewDialog = false })">
      <div slot="title" class="dialog-header-custom">
        <i class="el-icon-video-play" /><span>内容预览</span>
      </div>
      <div class="preview-wrapper">
        <video-preview-player :video-prop.sync="videoProp" />
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import VideoPreviewPlayer from 'components/VideoPreviewPlayer'
import VideoPostPublish from '@/views/post/VideoPostPublish'
import { updateVideoScope, deleteVideoPost, getVideoPosts, addVideoPost, updateVideoInfo, getVideoPost } from '@/api/vod'

export default {
  name: 'VideoPost',
  components: { VideoPreviewPlayer, VideoPostPublish },
  data() {
    return {
      loading: false,
      queryInfo: {
        scope: null, // 从 URL 获取
        pn: 1 // 从 URL 获取
      },
      screenWidth: document.body.clientWidth,
      pageSize: 12,
      totalSize: 0,
      dataList: [],
      videoProp: { videoId: null, play: false },
      showEditScopeDialog: false,
      showPreviewDialog: false,
      form: { videoId: null, scope: 1 },
      publishVideoDiaglog: false,
      editingVideo: null
    }
  },
  computed: {
    // 映射当前页码给 el-pagination 使用
    currentPage() {
      return parseInt(this.queryInfo.pn) || 1
    }
  },
  watch: {
    // 核心优化：监听路由变化，一旦 URL 参数变了，就重新抓取数据
    '$route': {
      handler: 'syncParamsAndLoad',
      immediate: true
    }
  },
  methods: {
    // 1. 同步 URL 参数到 data，并执行请求
    syncParamsAndLoad() {
      const { pn, scope } = this.$route.query
      this.queryInfo.pn = pn ? parseInt(pn) : 1
      this.queryInfo.scope = scope ? (isNaN(scope) ? scope : parseInt(scope)) : null
      this.getData()
    },

    // 2. 更新 URL 的通用方法
    updateRouter() {
      this.$router.push({
        path: this.$route.path,
        query: {
          pn: this.queryInfo.pn,
          scope: this.queryInfo.scope || undefined // 为 null 时不显示在 URL 中
        }
      }).catch(err => {
        // 捕获冗余导航错误（点击同一页时）
        if (err.name !== 'NavigationDuplicated') throw err
      })
    },

    // 3. 交互触发：切换分页
    handlePageChange(pageNumber) {
      this.queryInfo.pn = pageNumber
      this.updateRouter()
      window.scrollTo({ top: 0, behavior: 'smooth' })
    },

    // 4. 交互触发：切换筛选
    handleFilterChange() {
      this.queryInfo.pn = 1 // 筛选条件变了，重置回第一页
      this.updateRouter()
    },

    getData() {
      this.loading = true
      // 注意：这里建议给后端接口也加上 scope 参数，此处假设你原有接口支持
      getVideoPosts(this.queryInfo.pn, this.queryInfo.scope).then(resp => {
        if (resp.code === 0) {
          this.dataList = resp.data.list
          this.totalSize = resp.data.totalSize
        }
      }).finally(() => {
        this.loading = false
      })
    },

    /* --- 其余 UI 逻辑保持不变 --- */
    getStatusClass(status) {
      const map = { 1: 'info', 2: 'warning', 3: 'success', 4: 'danger', 5: 'info' }
      return map[status] || 'info'
    },
    getStatusText(status) {
      const map = { 1: '待发布', 2: '待审核', 3: '已发布', 4: '审核未通过', 5: '下架' }
      return map[status] || `未知(${status})`
    },
    handleScope(index, row) {
      this.form.videoId = row.videoId
      this.form.scope = '' + row.scope
      this.showEditScopeDialog = true
    },
    handleDialogClose(done) {
      this.videoProp = { videoId: null, play: false }
      if (typeof done === 'function') done()
    },
    handlePreview(index, row) {
      getVideoPost(row.videoId).then(res => {
        if (res.code === 0) {
          this.showPreviewDialog = true
          this.videoProp = { videoId: res.data.videoId, play: true }
        }
      })
    },
    handleEdit(row) {
      this.editingVideo = row
      this.publishVideoDiaglog = true
    },
    handlePost() {
      this.editingVideo = null
      this.publishVideoDiaglog = true
    },
    handleDelete(index, row) {
      this.$confirm(`确定要删除《${row.title}》?`, '警告', {
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }).then(() => {
        const payload = {}
        payload.videoId = row.videoId
        deleteVideoPost(payload).then(res => {
          if (res.code === 0) {
            this.$message.info('稿件已删除')
            this.getData()
          } else {
            this.$message.warning(res.msg)
          }
        })
      })
    },
    onUpdateScope() {
      updateVideoScope(this.form).then(res => {
        if (res.code === 0) {
          this.showEditScopeDialog = false
          this.getData()
          this.$message.info('可见范围已更新')
        }
      })
    },
    onVideoPublish({ data, mode }) {
      const videoForm = data
      if (mode === 'edit') {
        updateVideoInfo(videoForm).then(res => {
          this.$message.info(res.msg)
        }).catch(error => {
          this.$message.error(error.message)
        })
      } else {
        addVideoPost(videoForm).then(res => {
          if (res.code === 0) {
            this.publishVideoDiaglog = false
            this.$message.info('投稿成功，请等待审核')
            this.getData()
          }
        })
      }
      this.finishPublish()
    },
    finishPublish() {
      this.publishVideoDiaglog = false
      this.editingVideo = null
      this.getData()
    }
  }
}
</script>

<style scoped>
/* 样式部分同上一版，保持“三层”视觉感 */
.video-post-container { padding: 24px; background-color: #f5f7fa; min-height: 100%; }
.post-header { background: white; padding: 20px 24px; border-radius: 12px 12px 0 0; box-shadow: 0 4px 12px 0 rgba(0,0,0,0.03); }
.header-wrapper { display: flex; justify-content: space-between; align-items: center; }
.page-title { margin: 0; font-size: 20px; color: #303133; display: flex; align-items: center; gap: 8px; }
.filter-controls { display: flex; gap: 16px; }
.publish-btn { box-shadow: 0 4px 10px rgba(64, 158, 255, 0.3); }
.post-main { padding: 0; }
.table-card { background: white; border-radius: 0 0 12px 12px; padding: 10px 24px 24px; box-shadow: 0 8px 24px 0 rgba(0,0,0,0.04); min-height: 400px; }
.video-cover { width: 90px; height: 50px; border-radius: 6px; box-shadow: 0 2px 8px rgba(0,0,0,0.12); transition: transform 0.3s; }
.video-cover:hover { transform: scale(1.08); }
.video-title-link { color: #303133; text-decoration: none; font-weight: 600; font-size: 14px; }
.video-title-link:hover { color: #409EFF; }
.video-meta { margin-top: 6px; font-size: 12px; color: #909399; }
.vid-tag { background: #f0f2f5; padding: 2px 6px; border-radius: 4px; margin-right: 10px; }
.status-dot { position: relative; padding-left: 16px; font-size: 13px; color: #606266; }
.status-dot::before { content: ''; position: absolute; left: 0; top: 50%; transform: translateY(-50%); width: 7px; height: 7px; border-radius: 50%; }
.status-dot.success::before { background-color: #67C23A; box-shadow: 0 0 6px #67C23A; }
.status-dot.warning::before { background-color: #E6A23C; box-shadow: 0 0 6px #E6A23C; }
.status-dot.danger::before { background-color: #F56C6C; box-shadow: 0 0 6px #F56C6C; }
.danger-text { color: #F56C6C; }
.pagination-container { margin-top: 30px; display: flex; justify-content: center; }

::v-deep .custom-glass-dialog { border-radius: 16px !important; overflow: hidden; box-shadow: 0 20px 50px rgba(0,0,0,0.15) !important; }
::v-deep .custom-glass-dialog .el-dialog__header { padding: 20px 24px; background: #fcfcfd; border-bottom: 1px solid #f0f0f0; }
.dialog-header-custom { display: flex; align-items: center; gap: 10px; font-size: 18px; font-weight: 600; color: #303133; }
.dialog-header-custom i { color: #409EFF; font-size: 20px; }
::v-deep .custom-glass-dialog .el-dialog__body { padding: 24px; }
.input-label-tip { font-size: 13px; color: #909399; margin-bottom: 12px; }
.preview-wrapper { background: #1a1a1a; border-radius: 12px; overflow: hidden; line-height: 0; }
::v-deep .table-header-cell { background-color: #f8f9fb !important; color: #303133; font-weight: 600; padding: 12px 0; }
</style>
