<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 { replyToPost } from '../api'
import { isVideo } from '@/utils/index'
interface Props {
  id: string
}
const props = defineProps<Props>()

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

const formRef = $ref<FormInstance>()
const form = reactive({
  id: props.id,
  reply_type: 1,
  content: '',
  files: []
})
const rules = ref<FormRules>({
  content: [{ required: true, message: '请输入回复内容', trigger: 'blur' }]
})

// 提交
function handleSubmit() {
  formRef?.validate().then(create)
}
// 修改
const create = () => {
  const params = Object.assign({}, form, { files: form.files.length ? JSON.stringify(form.files) : '' })
  replyToPost(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-form-item 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" auto-insert-space @click="handleSubmit">发表</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
