<template>
  <div class="app-container user-section-comment">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="72px">
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="commentList" border>
      <el-table-column label="用户昵称" prop="nickName" width="120" show-overflow-tooltip />
      <el-table-column label="类型" width="72" align="center">
        <template slot-scope="scope">
          <el-tag size="mini" :type="scope.row.type === 2 ? 'info' : ''">
            {{ scope.row.type === 2 ? '回复' : '评论' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="留言内容" min-width="360">
        <template slot-scope="scope">
          <div class="comment-content-cell">
            <template v-for="(part, idx) in parseCommentContent(scope.row.content)">
              <p v-if="part.kind === 'text'" :key="'t-' + scope.row.commentId + '-' + idx" class="comment-text">
                {{ part.value }}
              </p>
              <el-image
                v-else-if="part.kind === 'image'"
                :key="'i-' + scope.row.commentId + '-' + idx"
                class="comment-media comment-image"
                :src="part.value"
                :preview-src-list="[part.value]"
                fit="contain"
              />
              <video
                v-else-if="part.kind === 'video'"
                :key="'v-' + scope.row.commentId + '-' + idx"
                class="comment-media comment-video"
                :src="part.value"
                controls
                preload="metadata"
              />
              <a
                v-else-if="part.kind === 'link'"
                :key="'l-' + scope.row.commentId + '-' + idx"
                :href="part.value"
                target="_blank"
                rel="noopener"
                class="comment-link"
              >{{ part.value }}</a>
            </template>
            <span v-if="!scope.row.content" class="comment-empty">—</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="点赞" prop="likes" width="70" align="center" />
      <el-table-column label="可见范围" width="100" align="center">
        <template slot-scope="scope">
          <el-tag size="mini" :type="scope.row.visibleAll === 1 ? 'success' : 'info'">
            {{ scope.row.visibleAll === 1 ? '全部人可见' : '自己可见' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="留言时间" prop="createTime" width="160" align="center" />
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            :disabled="scope.row.visibleAll === 1"
            @click="handleUpdateVisible(scope.row, 1)"
          >全部人可见</el-button>
          <el-button
            type="text"
            size="mini"
            :disabled="scope.row.visibleAll === 0 || scope.row.visibleAll == null"
            @click="handleUpdateVisible(scope.row, 0)"
          >自己可见</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listSectionUserComments, updateCommentVisibleAll } from '@/api/course/userCourseComment'

const IMAGE_EXT = /\.(png|jpe?g|gif|webp|bmp|svg)(\?.*)?$/i
const VIDEO_EXT = /\.(mp4|webm|ogg|mov|m4v|m3u8)(\?.*)?$/i

export default {
  name: 'UserCourseSectionComment',
  props: {
    courseId: {
      type: [String, Number],
      required: true
    },
    videoId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      loading: false,
      total: 0,
      commentList: [],
      visibleUpdatingId: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseId: null,
        videoId: null,
        nickName: null
      }
    }
  },
  watch: {
    courseId: {
      immediate: true,
      handler(val) {
        this.queryParams.courseId = val
      }
    },
    videoId: {
      immediate: true,
      handler(val) {
        this.queryParams.videoId = val
      }
    }
  },
  methods: {
    getList() {
      if (!this.queryParams.courseId || !this.queryParams.videoId) {
        return
      }
      this.loading = true
      listSectionUserComments(this.queryParams).then(response => {
        this.commentList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.nickName = null
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleUpdateVisible(row, visibleAll) {
      const label = visibleAll === 1 ? '全部人可见' : '自己可见'
      this.$confirm(`确认将该留言设置为「${label}」？`, '提示', { type: 'warning' }).then(() => {
        this.visibleUpdatingId = row.commentId
        updateCommentVisibleAll({
          commentId: row.commentId,
          visibleAll: visibleAll
        }).then(() => {
          this.$message.success('修改成功')
          this.getList()
        }).finally(() => {
          this.visibleUpdatingId = null
        })
      }).catch(() => {})
    },
    parseCommentContent(content) {
      if (!content || !String(content).trim()) {
        return []
      }
      const lines = String(content).split(/\r?\n/).map(s => s.trim()).filter(Boolean)
      const parts = []
      lines.forEach(line => {
        if (!/^https?:\/\//i.test(line)) {
          parts.push({ kind: 'text', value: line })
          return
        }
        if (VIDEO_EXT.test(line) || /\/comment\/video\//i.test(line)) {
          parts.push({ kind: 'video', value: line })
        } else if (IMAGE_EXT.test(line) || /\/comment\/image\//i.test(line)) {
          parts.push({ kind: 'image', value: line })
        } else {
          parts.push({ kind: 'link', value: line })
        }
      })
      return parts
    }
  }
}
</script>

<style scoped>
.user-section-comment {
  padding: 0;
}
.comment-content-cell {
  text-align: left;
  line-height: 1.6;
}
.comment-text {
  margin: 0 0 6px;
  white-space: pre-wrap;
  word-break: break-word;
}
.comment-media {
  display: block;
  margin: 6px 0;
  max-width: 280px;
  border-radius: 4px;
}
.comment-image {
  max-height: 160px;
}
.comment-video {
  max-height: 200px;
  background: #000;
}
.comment-link {
  display: block;
  margin: 4px 0;
  color: #409eff;
  word-break: break-all;
}
.comment-empty {
  color: #909399;
}
</style>
