<script setup lang="ts">
import type { Post } from '../types'
import { ArrowUp } from '@element-plus/icons-vue'
import AppList from '@/components/base/AppList.vue'
import DiscussItem from '../components/DiscussItem.vue'

import { getPostAndDiscussList } from '../api'
import { collectionResource } from '@/api/base'

const DiscussForm = defineAsyncComponent(() => import('../components/DiscussForm.vue'))

interface Props {
  id: string
}
const props = defineProps<Props>()

let detail = $ref<Post>()

const appList = $ref<InstanceType<typeof AppList> | null>(null)
// 列表配置
const listOptions = computed(() => {
  return {
    hasFilterButton: false,
    remote: {
      httpRequest: getPostAndDiscussList,
      params: { id: props.id },
      callback(res: { total: number; data: any; info: any }) {
        detail = res.info
        return { total: res.total, list: res.data }
      }
    }
  }
})
// 刷新
function handleRefetch() {
  appList?.refetch()
}
const discussFormVisible = $ref(false)

// 收藏/取消收藏
function toggleCollection() {
  collectionResource({
    course_id: detail.course_id,
    semester_id: detail.semester_id,
    chapter_id: detail.chapter_id,
    source_id: detail.id,
    type: 6,
    status: detail.collection_count ? 0 : 1
  }).then(() => {
    detail.collection_count = detail.collection_count ? 0 : 1
  })
}
</script>

<template>
  <div class="bbs">
    <div class="bbs-hd" v-if="detail">
      <h1>{{ detail.title }}</h1>
      <el-button round auto-insert-space @click="toggleCollection">
        {{ detail.collection_count ? '取消收藏' : '收藏' }}
      </el-button>
      <el-button round type="primary" auto-insert-space @click="discussFormVisible = true">回复</el-button>
    </div>
    <AppList v-bind="listOptions" ref="appList">
      <template #body="{ data }">
        <DiscussItem :landlordId="detail.sso_id" :data="item" v-for="item in data" :key="item.id"></DiscussItem>
      </template>
    </AppList>
  </div>
  <DiscussForm v-model="discussFormVisible" :id="id" @update="handleRefetch" v-if="discussFormVisible"></DiscussForm>
  <el-backtop :right="22" :bottom="100">
    <el-icon><ArrowUp /></el-icon>
    <span class="t1">返回<br />顶部</span>
  </el-backtop>
</template>

<style lang="scss">
.bbs {
  background-color: #fff;
  border: 1px solid #e5e5e5;
  border-radius: 6px;
  .table-list-ft {
    padding: 40px;
  }
}
.bbs-hd {
  position: relative;
  padding: 20px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #e4e4e4;
  box-shadow: #e4e4e4 0px 5px 10px;
  z-index: 10;
  h1 {
    flex: 1;
  }
}
.el-backtop {
  width: 60px;
  height: 60px;
  color: #000;
  .t1 {
    display: none;
    font-size: 14px;
    color: #fff;
  }
  &:hover {
    background-color: var(--main-color);
    .el-icon {
      display: none;
    }
    .t1 {
      display: inline-block;
    }
  }
}
</style>
