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

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 = reactive({
  semester_id: props.semesterId || '',
  course_id: props.courseId || '',
  chapter_id: '',
  type: '',
  title: '',
  content: '',
  files: []
})
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 : ''
})
// 提交
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)
  })
}
const images = $computed(() => {
  return form.files.filter((item: any) => !isVideo(item.url))
})
const videos = $computed(() => {
  return form.files.filter((item: any) => isVideo(item.url))
})

function beforeUpload(file: any) {
  if (images.length >= 10 && !isVideo(file.url)) {
    ElMessage.error('最多上传10张图片')
    return false
  }
  if (videos.length >= 1 && isVideo(file.url)) {
    ElMessage.error('最多上传1个视频')
    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" hide-required-asterisk 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">
        <AppEditor v-model="form.content" :height="300" />
      </el-form-item>
      <el-form-item prop="files">
        <AppUpload v-model="form.files" accept="image/*,video/*" :beforeUpload="beforeUpload">
          <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>
