<template>
  <div id="root">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-position="top" label-width="150px" class="ruleForm">
      <el-form-item label="公告标题" prop="announcementTitle">
        <el-input v-model="ruleForm.announcementTitle" placeholder="15字以内"/>
      </el-form-item>
      <el-form-item label="公告轮播图" prop="announcementCarouselImg">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          class="avatar-uploader"
          name="uploadFiles"
          action="http://106.14.20.193:8086/property-api/uploadimage">
          <img v-if="Urlimage" :src="Urlimage" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>
      <el-form-item label="公告详细描述">
        <el-input v-model="ruleForm.announcementContent" :rows="10" type="textarea" placeholder="公告内容"/>
      </el-form-item>
      <el-form-item label="公告配图">
        <el-upload
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccessContentImg"
          :file-list="contentImgList"
          name="uploadFiles"
          action="http://106.14.20.193:8086/property-api/uploadimage"
          list-type="picture-card">
          <i class="el-icon-plus"/>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img :src="dialogImageUrl" width="100%" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="权重值" prop="sort">
        <el-input-number v-model="ruleForm.sort" label="权重值" @change="sortHandleChange"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm','1')">发布</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'Index',
  data() {
    return {
      ruleForm: {
        id: '',
        announcementTitle: '',
        announcementCarouselImg: '', // 轮播图
        announcementContent: '', // 内容详细
        contentImg: [], // 内容配图
        sort: 1, // 权重
        status: '' // 状态 0 是已作废 1 是已发布   2 是草稿 3 是已修改
      },
      contentImgList: [],
      Urlimage: '', // 轮播图预览
      dialogVisible: false, // 公告配图, 默认不显示 (以单张为单位)
      dialogImageUrl: '', // 公告配图, 图片链接 (以单张为单位)
      rules: {
        announcementTitle: [
          { required: true, message: '请输入公告名称', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 15 个字符以内', trigger: 'blur' }
        ],
        announcementContent: [
          { required: true, message: '公告详细描述', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入权重值', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.ruleForm.id = this.$route.query.id
    this.getById()
  },
  methods: {
    submitForm(formName, status) {
      // 加载框
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.announcementContent.length <= 0 && this.ruleForm.contentImg.length <= 0) {
            this.$message.error('公告内容描述 和 公告配图至少要存在一个!')
            loading.close()
            return
          }
          this.ruleForm.status = status // 发布状态
          this.$store.dispatch('Updateannouncement', this.ruleForm).then((res) => {
            if (res.code === '0') {
              this.$message({
                message: res.message,
                type: 'success'
              })
              this.$router.push({ name: 'announcement-index' })
              loading.close()
              return
            }
            this.$message.error(res.message)
            loading.close()
          }).catch(() => {
            console.log('error AddActivity')
          })
        } else {
          console.log('error submit!!')
          loading.close()
          return false
        }
      })
      // 关闭加载框
      loading.close()
    },
    handleAvatarSuccess(res, file) { // 轮播图上传回调
      this.ruleForm.announcementCarouselImg = res.data[0]
      this.Urlimage = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) { // 轮播图上传前操作
      // const isJPG = file.type === 'image/jpeg'
      // const isLt2M = file.size / 1024 / 1024 < 2
      //
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!')
      // }
      // return isJPG && isLt2M
    },
    handleRemove(file, fileList) { // 活动配图移除时
      this.ruleForm.contentImg = []
      for (let i = 0; i < fileList.length; i++) {
        this.ruleForm.contentImg.push(fileList[i].url)
      }
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) { // 点击公告配图文件列表中已上传的文件时的钩子
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSuccessContentImg(response, file, fileList) { // 活动配图上传成功时回调
      const resImg = response.data[0]
      this.ruleForm.contentImg.push(resImg)
      console.log('上传活动配图成功时回调!')
    },
    sortHandleChange(value) { // 权重值
      this.ruleForm.sort = value
    },
    getById() { // 页面初始化后调用此方法根据ID获取公告信息
      this.$store.dispatch('AnnouncementById', this.ruleForm).then((res) => {
        const resData = res.data
        this.ruleForm.announcementTitle = resData.tpAnnouncement.announcementTitle// 标题
        this.ruleForm.announcementContent = resData.tpAnnouncement.announcementContent// 内容
        this.Urlimage = resData.tpAnnouncement.announcementCarouselImg // 轮播图
        this.ruleForm.sort = resData.tpAnnouncement.sort// 权重
        // 多张图片进行遍历
        for (let i = 0; i < resData.studentList.length; i++) {
          this.contentImgList.push({ url: resData.studentList[i].imageUrl })
          this.ruleForm.contentImg.push(resData.studentList[i].imageUrl)
        }
      })
    }
  }
}
</script>

<style scoped>
#root {
  display: flex;
}
.ruleForm {
  width: 800px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 50px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
