<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="imageFlag">
          <el-upload
            class="upload-control"
            :class="{hidden:count === 8}"
            list-type="picture-card"
            accept=".png,.jpg,.gif"
            :action="action"
            :headers="headers"
            :multiple="true"
            :limit="8"
            :file-list="imageList"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <i class="el-icon-picture-outline" />
            <div slot="tip" class="el-upload__tip" style="color:#999"><span style="color:red">*</span>最多只能上传8张图片</div>
          </el-upload>
          <el-input v-model="formData.imageFlag" class="hiddenInput" />
        </el-form-item>
      </el-form>
      <div class="submit-btn">
        <el-button type="primary" @click="submit">保存</el-button>
        <el-button type="warning" @click="$_back()">返回</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import { getImageDetail, saveImage } from '@/api/doc'
export default {
  data() {
    return {
      count: 0, // 图片个数
      imageId: '', // 图片列表id
      imageList: [], // 回显图片列表
      imageArr: [], // 上传的图片列表
      formData: {
        imageTitle: '', // 图片标题
        imageFlag: '' // 是否上传图片的标识 不为空则代表上传过图片
      },
      formRules: {
        imageTitle: [
          { required: true, message: '标题不能为空', trigger: 'blur' },
          { max: 50, message: '标题不能超过50个字符', trigger: 'blur' }
        ],
        imageFlag: [
          { required: true, message: '图片列表不能为空', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['authUserId']),
    headers() {
      return {
        'X-Token': getToken()
      }
    },
    action() {
      return `${process.env.VUE_APP_UPLOAD_API}/upload/image`
    }
  },
  watch: {
    count(nVal, oVal) {
      this.formData.imageFlag = (nVal > 0 ? 'has image' : '')
    }
  },
  created() {
    this.imageId = this.$route.query.imageId || ''
    this.initFormData()
  },
  methods: {
    submit() {
      // 请求参数
      const params = {
        imageId: this.imageId,
        authUserId: this.authUserId,
        imageTitle: this.formData.imageTitle,
        imageArr: this.imageArr
      }
      // 校验表单数据
      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.imageId) return
      getImageDetail({ imageId: this.imageId }).then(res => {
        console.log(res)
        const { imageTitle, imageList } = res.data
        this.formData.imageTitle = imageTitle
        this.imageArr = imageList
        this.count = imageList.length
        for (let i = 0; i < this.count; i++) {
          this.imageList.push({ name: '', url: imageList[i] })
        }
        console.log(this.imageList)
      })
    },
    // 图片上传成功的回调
    handleUploadSuccess(response, file, fileList) {
      this.count = fileList.length
      this.imageArr.push(response.data)
    },
    // 移除图片的回调
    handleRemove(file, fileList) {
      const removeUrl = this.searchFileUrl(this.imageList, file)
      const pop = this.imageArr.indexOf(removeUrl)
      this.imageArr.splice(pop, 1)
      this.count = fileList.length
    },
    beforeUpload(file, fileList) {
      const flag = file.size <= 5 * 1024 * 1204
      if (!flag) {
        this.$message({
          message: '文件大小超过5MB，请重新选择！',
          duration: 1000,
          type: 'warning'
        })
        this.fileList = []
      }
      return flag
    },
    // 根据图片id获取图片
    searchFileUrl(fileList = [], file) {
      return fileList.filter(v => v.uid === file.uid)[0]?.url
    }
  }
}
</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>
