<template>
  <div class="app-container">
    <div class="form">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="70px">
        <el-form-item label="标题：" prop="imageTitle">
          <el-input v-model="formData.imageTitle" placeholder="图片列表标题" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="图片：" prop="imageList">
          <upload-image
            :image-list="imageList"
            :limit="8"
            :before-upload="beforeUpload"
            @success="handleUploadSuccess"
            @remove="handleRemove"
          />
          <el-input v-show="false" v-model="formData.imageList" />
        </el-form-item>
      </el-form>
      <div class="submit-btn">
        <el-button type="primary" @click="submit">保存</el-button>
        <el-button type="warning" @click="navigateBack()">返回</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import UploadImage from '@/components/UploadImage'
import { mapGetters } from 'vuex'
import { getImageDetail, saveImage } from '@/api/doc'
export default {
  components: { UploadImage },
  data() {
    return {
      editType: 'add',
      imageId: '', // 图片列表id
      imageList: [], // 回显图片列表
      formData: {
        imageTitle: '', // 图片标题
        imageList: '' // 是否上传图片的标识 不为空则代表上传过图片
      },
      formRules: {
        imageTitle: [
          { required: true, message: '标题不能为空', trigger: 'blur' },
          { max: 50, message: '标题不能超过50个字符', trigger: 'blur' }
        ],
        imageList: [{ required: true, message: '图片列表不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {
    ...mapGetters(['authUserId'])
  },
  created() {
    this.imageId = this.$route.query.imageId || ''
    this.editType = this.$route.query.type || 'add'
    this.initFormData()
  },
  methods: {
    submit() {
      // 请求参数
      const params = {
        imageId: this.imageId,
        authUserId: this.authUserId,
        imageTitle: this.formData.imageTitle
      }
      params.imageArr = this.imageList.map(image => image.response ? image.response.data : image.url)
      // 校验表单数据
      this.$refs.formRef.validate(valid => {
        if (!valid) return
        this.isLoading = true
        // 保存
        saveImage(params)
          .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.editType !== 'edit') return
      getImageDetail({ imageId: this.imageId }).then(res => {
        const { imageTitle, imageList } = res.data
        this.formData.imageTitle = imageTitle
        this.imageList = imageList.map(image => ({ url: image, name: '' }))
      })
    },
    // 文件上传
    handleUploadSuccess({ response, file, fileList }) {
      this.formData.imageList = fileList.length
      this.imageList = fileList
    },
    handleRemove({ response, file, fileList }) {
      this.formData.imageList = fileList.length > 0 ? fileList.length : ''
      this.imageList = fileList
    },
    beforeUpload(file, fileList) {
      const flag = file.size <= 50 * 1024 * 1204
      if (!flag) {
        this.$message.warning('文件大小不能超过50MB，请重新选择！')
      }
      return flag
    }
  }
}
</script>

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