<template>
  <div v-loading="isLoading" class="app-container">
    <div class="form">
      <el-form ref="formRef" label-width="120px" :model="formData" :rules="formRules">
        <el-form-item label="标题：" prop="articleTitle">
          <el-input v-model="formData.articleTitle" placeholder="请输入文章标题" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="头图：" prop="articleImage">
          <upload-image tip-title="128px * 128px" :file-list="imagelist" @success="handleSussces" @error="handleError" />
          <el-input v-model="formData.articleImage" class="hiddenInput" />
        </el-form-item>
        <el-form-item label="文章内容：" prop="articleContent">
          <tinymce v-model="formData.articleContent" :token="token" :action="action" :height="300" />
          <el-input v-model="formData.articleContent" class="hiddenInput" />
        </el-form-item>
      </el-form>
    </div>
    <div class="submit-btn">
      <el-button type="primary" @click="submit">保存</el-button>
      <el-button type="warning" @click="$_back()">返回</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import UploadImage from '@/views/components/uploadImage'
import Tinymce from '@/components/Tinymce'
import { getToken } from '@/utils/auth'
import { saveArticle, getArticleDeatil } from '@/api/doc'
export default {
  components: { UploadImage, Tinymce },
  data() {
    return {
      editType: 0, // 编辑模式 1：添加文章  2：修改文章
      formData: {
        articleId: '', // 文章id
        authUserId: '', // 用户id
        articleTitle: '', // 文章标题
        articleImage: '', // 文章封面
        articleContent: '' // 文章内容
      },
      // 表单验证规则
      formRules: {
        articleTitle: [
          { required: true, message: '文章标题不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        articleImage: [{ required: true, message: '文章必须上传封面', trigger: 'change' }],
        articleContent: [{ required: true, message: '文章内容不能为空', trigger: 'change' }]
      },
      // 表单是否处于加载状态
      isLoading: true,
      // 当前用户登录的token
      token: '',
      // 富文本框上传图片的接口
      action: process.env.VUE_APP_UPLOAD_API + '/upload/image',
      // 封面图片列表
      imagelist: []
    }
  },
  computed: {
    ...mapGetters(['authUserId'])
  },
  created() {
    this.token = getToken()
    this.formData.articleId = this.$route.query.articleId || ''
    this.editType = this.formData.articleId ? 2 : 1
    this.initFormData()
  },
  mounted() {
    setTimeout(() => {
      this.isLoading = false
    }, 500)
  },
  methods: {
    // 保存文章
    submit() {
      this.formData.authUserId = this.authUserId
      this.$refs.formRef.validate(valid => {
        if (!valid) return
        this.isLoading = true
        saveArticle(this.formData).then(res => {
          console.log(res)
          if (res.code !== 0) return
          this.$message.success(res.data)
          // 如果保存文章成功就要关闭当前页面
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.back()
        }).finally(() => {
          this.isLoading = false
        })
      })
    },
    // 初始化表单回显数据
    initFormData() {
      if (!this.formData.articleId) return
      getArticleDeatil({ articleId: this.formData.articleId }).then(res => {
        for (const key in this.formData) {
          if (Object.hasOwnProperty.call(this.formData, key)) {
            this.formData[key] = res.data[key]
          }
        }
        this.imagelist = [{ name: '文章封面', url: this.formData.articleImage }]
        console.log(res)
      })
    },
    // 封面图片上传成功
    handleSussces(res) {
      console.log(res)
      if (!res.data) {
        this.imagelist = []
        return
      }
      this.formData.articleImage = res.data
    },
    // 封面图片上传失败
    handleError() {
      this.imagelist = []
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container{
  .form{
    width: 1000px;
    margin: 30px auto;
  }
}
.hiddenInput{
  height: 0;
  display: none;
}
.submit-btn {
  text-align: center;
  .el-button {
    width: 140px;
  }
}
</style>
