<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import AppUpload from '@/components/base/AppUpload.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)
  })
}

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" hide-required-asterisk label-position="top">
      <el-form-item 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" auto-insert-space @click="handleSubmit">发表</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
