<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import AppUpload from '@/components/base/AppUpload.vue'
import { createPost } from '../api'
import { useMapStore } from '@/stores/map'
import { useGetCourseList } from '@/composables/useGetCourseList'
import { isVideo } from '@/utils/index'
import { useStorage } from '@vueuse/core'

interface Props {
  courseId?: string
  semesterId?: string
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const { courses, courseValue, chapters } = useGetCourseList()
const types = useMapStore().getMapValuesByKey('learning_discussion_type')

const formRef = $ref<FormInstance>()
const form = $(
  useStorage('bbsPost', {
    semester_id: props.semesterId || '',
    course_id: props.courseId || '',
    chapter_id: '',
    type: '',
    title: '',
    content: '',
    files: []
  })
)
if (props.courseId) {
  form.course_id = props.courseId
}
if (props.semesterId) {
  form.semester_id = props.semesterId
}
const rules = ref<FormRules>({
  course_id: [{ required: true, message: '请选择课程', trigger: 'change' }],
  chapter_id: [{ required: true, message: '请选择章节', trigger: 'change' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入正文内容', trigger: 'blur' }]
})
watchEffect(() => {
  courseValue.value = form.course_id
  const course = courses.value.find(item => item.course_id === form.course_id)
  form.semester_id = course ? course.semester.id : ''
})
watch(chapters, () => {
  const chapter = chapters.value.find(item => item.id === form.chapter_id)
  if (!chapter) form.chapter_id = ''
})
// 提交
function handleSubmit() {
  formRef?.validate().then(create)
}
// 修改
const create = () => {
  const params = Object.assign({}, form, { files: form.files.length ? JSON.stringify(form.files) : '' })
  createPost(params).then(() => {
    ElMessage({ message: '发布成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
    // 清空本地存储
    localStorage.removeItem('bbsPost')
  })
}

function onChange(file: any, files: any, uploadRef: any) {
  if (file.status !== 'ready') return
  const images = files.filter((item: any) => !isVideo(item.name))
  const videos = files.filter((item: any) => isVideo(item.name))
  if (images.length > 10 && !isVideo(file.name)) {
    ElMessage.error('最多上传10张图片')
    uploadRef?.handleRemove(file)
    return false
  }
  if (videos.length > 1 && isVideo(file.name)) {
    ElMessage.error('最多上传1个视频')
    uploadRef?.handleRemove(file)
    return false
  }
}
</script>

<template>
  <el-dialog
    append-to-body
    align-center
    title="发帖"
    width="800px"
    :close-on-click-modal="false"
    @update:modelValue="$emit('update:modelValue')">
    <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
      <el-row justify="space-between">
        <el-form-item label="相关课程" prop="course_id" v-if="!courseId">
          <el-select filterable v-model="form.course_id">
            <el-option v-for="item in courses" :key="item.id" :label="item.name" :value="item.course_id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="相关章节" prop="chapter_id">
          <el-select filterable v-model="form.chapter_id">
            <el-option v-for="item in chapters" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select filterable v-model="form.type">
            <el-option v-for="item in types" :key="item.id" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>
      <el-form-item label="正文内容" prop="content">
        <el-input
          type="textarea"
          show-word-limit
          :autosize="{ minRows: 10, maxRows: 12 }"
          :maxlength="500"
          v-model="form.content"></el-input>
      </el-form-item>
      <el-form-item prop="files">
        <AppUpload v-model="form.files" accept="image/*,video/*" :onChange="onChange">
          <el-button size="default">上传图片/视频附件</el-button>
          <template #tip
            >支持最多上传10张图片，格式支持jpg，jpeg，png，2MB以内<br />视频最多上传1个，100Mb以内
          </template>
        </AppUpload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">发布问题</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
