<template>
  <div class="newsSettingBox">
    <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="附件">
        <div class="uploadFileBox">
          <span>
            <el-button type="primary" @click="uploadHandle">上传</el-button>
            <input type="file" style="display: none" ref="fileRef" @change="fileChangeHandle" />
          </span>
          <ul class="prviewFile">
            <li v-for="(item, index) in fileUrls" :key="index">
              <span>
                <a href="javascript:void(0);" @click="downloadFile(item['url'])">{{
                  item['name']
                }}</a>
              </span>
              <el-button
                type="text"
                @click="
                  deleteFile(item['id'], () => {
                    ElMessage.success('文件删除成功！')
                  })
                "
                >删除</el-button
              >
            </li>
          </ul>
        </div>
      </el-form-item>
      <el-form-item label="内容">
        <Tinymce v-model="formData.content" width="100%" height="800px" />
      </el-form-item>
    </el-form>
    <div class="btnGroup" style="text-align: right">
      <span>
        <el-button type="primary" @click="onSubmit(ruleFormRef)">发布</el-button>
      </span>
      <el-button @click="router.back()">取消</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router'
import { ElMessage, FormRules, FormInstance } from 'element-plus'
import request from '@/config/axios'
import router from '@/router'
import { useFiles } from './mixins'

const { fileUrls, downloadFile, uploadFile, deleteFile } = useFiles(request)

defineOptions({
  name: 'NoticeAdd'
})
const route: any = useRoute()
const routeName: string = route.name ?? ''
const initFormData: any = {
  id: null,
  title: '',
  type: routeName.startsWith('Notice') || routeName.startsWith('notice') ? 1 : 2,
  studyType: null,
  files: '',
  userId: '',
  nickname: '',
  content: ''
}
const formData = ref(initFormData)
const ruleFormRef = ref<FormInstance>()
const rules = reactive<
  FormRules<{
    title: string
    content: string
  }>
>({
  title: {
    required: true,
    message: '标题不能为空! ',
    trigger: 'change'
  },
  content: {
    required: true,
    message: '内容不能为空! ',
    trigger: 'change'
  }
})
function onSubmit(formEl: FormInstance | undefined, num?: number): void {
  if (!formEl) return
  if (formData.value.content) {
    /**
     * 解决定义controlsList="nodownload"属性时tinymce组件会剔除
     * **/
    formData.value.content = formData.value.content.replace(
      'title="nodownload"',
      'controlsList="nodownload"'
    )
  }
  formEl.validate((valid, fields: any) => {
    if (valid) {
      let urlApi: string = '/adm/noticeAndLearn/add'
      const sendData = {
        ...formData.value
      }
      if (fileUrls.value.length > 0) {
        sendData.files = fileUrls.value.map((item) => item.id).join(',')
      }
      request.post({ url: urlApi, data: sendData }).then((result) => {
        if (result) {
          ElMessage({
            showClose: true,
            message: '保存成功.',
            type: 'success'
          })
          if (num !== 0) {
            const timer = setTimeout(() => {
              clearTimeout(timer)
              router.back()
            })
          }
        }
      })
    } else {
      const keys = Object.keys(fields)
      ElMessage.error(fields[keys[0]][0]['message'])
    }
  })
}
const fileRef = ref()
function uploadHandle() {
  fileRef.value.click()
}
function fileChangeHandle(evt) {
  const target = evt.target
  uploadFile(target.files[0])
}
</script>

<style lang="scss" scoped>
.newsSettingBox {
  margin-top: 20px;
  height: calc(100% - 20px);
  background-color: #fff;
  border-radius: 20px;
  padding: 20px;
  overflow-y: auto;
  .prviewFile {
    padding-left: 20px;
    > li {
      margin-bottom: 10px;
      > span {
        display: inline-block;
        margin-right: 15px;
      }
    }
  }
  .switchGroup {
    display: flex;
  }
  .btnGroup {
    > span {
      margin-right: 20px;
    }
  }
  .uploadFileBox {
    position: relative;
    flex: 1;
    display: flex;
  }
  .preImg {
    margin-bottom: 20px;
    margin-left: 120px;
    > img {
      width: 200px;
    }
  }
}
</style>
