<template>
  <div v-loading="isLoading" class="page-form-container">
    <el-form ref="formRef" label-width="120px" :model="formData" :rules="formRules">
      <el-form-item label="文章类型：" prop="articleType">
        <el-radio-group v-model="formData.articleType">
          <el-radio :label="1">自主</el-radio>
          <el-radio :label="2">第三方</el-radio>
        </el-radio-group>
      </el-form-item>
      <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"
          :image-list="imageList"
          @success="handleUploadImageSussces"
          @remove="handleRemoveImage"
        />
        <el-input v-show="false" v-model="formData.articleImage" />
      </el-form-item>
      <template v-if="formData.articleType === 1">
        <el-form-item label="文章内容：" prop="articleContent">
          <tinymce v-model="formData.articleContent" :token="token" :action="action" :height="300" />
          <el-input v-show="false" v-model="formData.articleContent" />
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item label="文章链接：" prop="articleLink">
          <el-input v-model="formData.articleLink" placeholder="请输入链接" />
        </el-form-item>
      </template>
    </el-form>
    <div class="control-box center">
      <el-button type="primary" @click="submit">保存</el-button>
      <el-button type="warning" @click="navigateBack()">返回</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import UploadImage from '@/components/UploadImage'
import Tinymce from '@/components/Tinymce'
import { getToken } from '@/utils/auth'
import { saveArticle, getArticleDeatil } from '@/api/doc'
export default {
  components: { UploadImage, Tinymce },
  data() {
    const fileNameValidate = (rule, value, callback) => {
      if (/[\\\/\[\]\|^%&',;=?$\x22]+/g.test(value)) {
        callback(new Error("文章标题不能包含|\/\\^%&',;=?$等特殊字符"))
      } else {
        callback()
      }
    }

    return {
      editType: 0, // 编辑模式 1：添加文章  2：修改文章
      formData: {
        articleId: '', // 文章id
        articleType: 1, // 文章类型
        articleTitle: '', // 文章标题
        articleImage: '', // 文章封面
        articleContent: '', // 文章内容
        articleLink: '',
        parentId: ''
      },
      // 表单验证规则
      formRules: {
        articleTitle: [
          { required: true, message: '文章标题不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: fileNameValidate, trigger: 'blur' }
        ],
        articleImage: [{ required: true, message: '文章必须上传封面', trigger: 'change' }],
        articleContent: [{ required: true, message: '文章内容不能为空', trigger: 'change' }],
        articleLink: [{ required: true, message: '文章链接不能为空', trigger: 'blur' }]
      },
      // 表单是否处于加载状态
      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.formData.parentId = this.$route.query.parentId || 0
    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)) {
            if (res.data[key]) {
              this.formData[key] = res.data[key]
            }
          }
        }
        this.imageList = [{ name: '文章封面', url: this.formData.articleImage }]
        console.log(res)
      })
    },
    // 封面图片上传成功
    handleUploadImageSussces({ response, file, fileList }) {
      this.imageList = fileList
      this.formData.articleImage = response.data
    },
    handleRemoveImage({ response, file, fileList }) {
      this.imageList = fileList
      this.formData.articleImage = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.page-form-container {
  width: 900px;
}
</style>
