<template>
  <div id="root">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-position="top" label-width="150px" class="ruleForm">
      <el-form-item  prop="activityTitle">
        <div>活动标题&nbsp;&nbsp;<el-input v-model="ruleForm.activityTitle" placeholder="15字以内" style="width: 80%;padding-left:3.5%;"/></div>
      </el-form-item>
      <el-form-item  prop="activityCarouselImg">
        <div >
          <div style="transform:translateY(250%);">活动轮播图</div>
        <div  style="width: 500px;padding-left:20%;">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          class="avatar-uploader"
          :name="uploadFiles"
          :action="uploadImgUrl">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
        </div>
        </div>
      </el-form-item>
      <el-form-item >
        <div><span style="position:relative;top:-100px">活动详细描述&nbsp;&nbsp;</span><el-input v-model="ruleForm.activityContent" :rows="10" type="textarea" placeholder="活动内容, 活动规则, 活动举办开始时间, 活动举办结束时间, 报名人数上限等" style="width: 80%;"/></div>
      </el-form-item>
      <el-form-item >
        <div >
          <div style="transform:translateY(250%);">公告轮播图</div>
        <div  style="width: 500px;padding-left:13%;">
        <el-upload
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccessContentImg"
          :file-list="activityContentList"
          name="uploadFiles"
          :action="uploadImgUrl"
          list-type="picture-card">
          <i class="el-icon-plus"/>
        </el-upload>
        </div>
        </div>
        <el-dialog :visible.sync="dialogVisible">
          <img :src="dialogImageUrl" width="100%" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item prop="signUpMax">
        <div style="display: flex;">
          <span style="width: 140px;">报名人数上限</span>
          <el-input v-model="ruleForm.signUpMax" placeholder="填写0则不限制报名人数"/>
        </div>
      </el-form-item>
      <el-form-item prop="registrationEndTime">
        <div style="display: flex;">
          <span style="width: 120px;">报名截止时间</span>
          <el-date-picker
            v-model="ruleForm.registrationEndTime"
            value-format="timestamp"
            type="date"
            placeholder="选择日期"/>
        </div>
      </el-form-item>
      <el-form-item>
      <div style="display: flex;">
          <span style="width: 200px;transform:translateY(-1%);">是否需要报名人扫码签到</span>
          <el-radio v-model="ruleForm.signInCode" label="1" style="padding-left:4%;font-weight:bold;font-size:12px;transform:translateY(30%);">需要</el-radio>
          <el-radio v-model="ruleForm.signInCode" label="2" style="padding-left:8%;font-weight:bold;font-size:12px;transform:translateY(30%);">不需要</el-radio> 
      </div>
      </el-form-item>
      <el-form-item prop="sort">
        <div style="display: flex; justify-content: flex-start;">
          <span style="width: 120px;">权重值</span>
          <el-input-number v-model="ruleForm.sort" :min="1" label="权重值" @change="sortHandleChange"/>
        </div>
      </el-form-item>
      <el-form-item style="display: flex; justify-content: center;">
        <el-button type="primary" @click="submitForm('ruleForm')">发布</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

export default {
  name: 'Index',
  data() {
    return {
      ruleForm: {
        signInCode: '',
        id: '',
        activityTitle: '',
        activityCarouselImg: '', // 轮播图
        activityContent: '', // 活动内容详细
        contentImg: [], // 活动内容配图
        signUpMax: '', //  活动人数上限
        registrationEndTime: '', // 报名活动结束时间
        sort: 1, // 权重
        status: '', // 状态 0 是已作废 1 是已发布   2 是草稿 3 是已修改
        radio: ''
      },
      activityContentList: [], // 活动配图预览列表
      imageUrl: '', // 轮播图预览
      dialogVisible: false, // 活动配图, 默认不显示 (以单张为单位)
      dialogImageUrl: '', // 活动配图, 图片链接 (以单张为单位)
      rules: {
        activityTitle: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 15 个字符以内', trigger: 'blur' }
        ],
        activityContent: [
          { required: true, message: '活动详细描述', trigger: 'blur' }
        ],
        signUpMax: [
          { required: true, message: '请输入报名人数上限', trigger: 'blur' }
        ],
        registrationEndTime: [
          { type: 'date', required: true, message: '报名截止时间', trigger: 'change' }
        ],
        sort: [
          { required: true, message: '请输入权重值', trigger: 'change' }
        ]
      },
      uploadImgUrl: process.env.BASE_API + '/uploadimage',
    }
  },
  mounted() {
    this.ruleForm.id = this.$route.query.id
    this.getById()
  },
  methods: {
    submitForm(formName) {
      // 加载框
      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.activityContent.length <= 0 && this.ruleForm.contentImg.length <= 0) {
            this.$message.error('活动内容描述 和 活动配图至少要存在一个!')
            loading.close()
            return false
          }
          this.ruleForm.status = 1 // 发布状态
          this.$store.dispatch('UpdateActivity', this.ruleForm).then((res) => {
            if (res.code === '0') {
              this.$message({
                message: res.message,
                type: 'success'
              })
              this.$router.push({ name: 'activity-index' })
              loading.close()
              return
            }
            this.$message.error(res.message)
          }).catch(() => {
            console.log('error AddActivity')
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
      // 关闭加载框
      loading.close()
    },
    handleAvatarSuccess(res, file) { // 轮播图上传回调
      this.ruleForm.activityCarouselImg = res.data[0]
      this.imageUrl = 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) { // 活动配图移除时
      console.log(file, fileList)
      this.ruleForm.contentImg = []
      for (let i = 0; i < fileList.length; i++) {
        this.ruleForm.contentImg.push(fileList[i].url)
      }

    },
    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
      console.log(value)
    },
    getById() { // 根据ID获取活动信息
      this.$store.dispatch('ActivityById', this.ruleForm.id).then((res) => {
        const resData = res.data
        this.imageUrl = resData.info.activityCarouselImg
        this.ruleForm = resData.info

        const imgArr = resData.contentImg
        this.ruleForm.contentImg = imgArr
        for (let i = 0; i < imgArr.length; i++) {
          this.activityContentList.push({ url: imgArr[i] })
        }
      })
    }

  }
}
</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>
