<template>
  <el-form ref="activityQuery" label-width="160px" :rules="rules" :model="activityQuery">
    <el-form-item label="所属项目" prop="buildingId">
      <el-select v-model="activityQuery.buildingId"  placeholder="请选择">
        <el-option v-for="(build,i) in buildings.list || []" :key="i" :label="build.buildingName" :value="build.buildingId"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="主图：" prop="buildingId">
      <el-upload
        :headers="uploadHeaders"
        :action="upFileUrl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>
    <el-form-item label="海报图：" prop="buildingId">
      <el-upload
              class="avatar-uploader"
              :headers="uploadHeaders"
              :action="upFileUrl"
              :show-file-list="false"
              :on-success="shareImageHandleAvatarSuccess">
        <img v-if="shareImageUrl" :src="shareImageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>
    <el-form-item label="活动标题" prop="title">
      <el-input v-model="activityQuery.title"></el-input>
    </el-form-item>
    <el-form-item label="活动时间" prop="startDate">
       <el-date-picker v-model="activityQuery.startDate" type="datetime" placeholder="选择日期"/>
        <span>-</span>
       <el-date-picker v-model="activityQuery.endDate" type="datetime" placeholder="选择日期"/>   
    </el-form-item>
    <el-form-item label="活动地点"  prop="address">
      <el-input v-model="activityQuery.address"></el-input>
    </el-form-item>
    <el-form-item label="活动人数" prop="personNum">
      <el-input v-model="activityQuery.personNum" type="number"></el-input>
    </el-form-item>
    <!-- <el-form-item label="链接地址">
      <el-input v-model="dynamic.url"></el-input>
    </el-form-item> -->
    <el-form-item label="活动详情">
      <div id="desc">
        <rich-editor v-model="activityQuery.desc" style="height: 400px"/>
      </div>   
    </el-form-item>
    <el-form-item label="是否需要报名">
       <el-radio v-model="activityQuery.isEnlist" label="1">是</el-radio>
       <el-radio v-model="activityQuery.isEnlist" label="0">否</el-radio>
    </el-form-item>
    <el-form-item label="报名时间" v-if="activityQuery.isEnlist == '1'"  prop="enlistStart">
       <el-date-picker v-model="activityQuery.enlistStart" type="datetime" placeholder="选择日期"/>
        <span>-</span>
       <el-date-picker v-model="activityQuery.enlistEnd" type="datetime" placeholder="选择日期"/>   
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit('activityQuery')">保存</el-button>
      <el-button @click="onCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
import apis from '../../config/api'
import E from 'wangeditor'
import dayjs from 'dayjs'
const { mapState: mapDynamicState, mapActions: mapDynamicActions, mapMutations: mapDynamicMutations } = createNamespacedHelpers('building')
const { mapState: mapActivityState, mapActions: mapActivityActions } = createNamespacedHelpers('activity')
const { mapState: mapBuildingState, mapActions: mapBuildingActions } = createNamespacedHelpers('building')
const { mapActions: mapImgActions } = createNamespacedHelpers('img')

export default {
  data () {
    return {
      url:'',
      buildingId:'',
      upFileUrl: apis.file.upload.url,
      radio:'1',
      imageUrl: '',
      shareImageUrl: '',
      imgList: [],
      dialogVisible: false,
      dialogImageUrl: "",
      activityQuery: {
       dynamicId:'',
       url:'',
       startDate:'',
       endDate:'',
       buildingId:'',
       title:'',
       isEnlist:'',
       desc:'',
       enlistStart:'',
       enlistEnd:'',
       address:'',
       personNum:'',
       shareImg: ''
      },
      rules: {
          buildingId: [
            { required: true, message: '请选择活动区域', trigger: 'blur' }
          ],
          url: [
            { required: true, message: ' ', trigger: 'change' }
          ],
          title: [
            { required: true, message: '请输入活动标题', trigger: 'blur' },
          ],
          startDate: [
            { required: true, message: '请选择日期', trigger: 'blur' }
          ],
          endDate: [
            { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
          ],
          address: [
            {  required: true, message: '请输入活动地点', trigger: 'blur' }
          ],
          personNum: [
            { required: true, message: '请输入活动人数', trigger: 'blur' }
          ],
          desc: [
            { required: true, message: ' ', trigger: 'blur' }
          ],
          // img: [
          //   { required: true, message: ' '}
          // ],
          enlistStart:[
            { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
          ]
        }
      
    }
  },
  computed: {
    ...mapDynamicState({
      detail: x => x.detail,
    }),
    dynamic: {
      get () {
        return this.detail
      },
      set (val) {
        return this.updateDetail(val)
      }
    },
    ...mapBuildingState({
      buildings: x => x.buildings
    }),
    uploadHeaders () {
                const token = localStorage.getItem('x-token') || ''
                return {
                    Authorization: `Bearer ${token}`
                }
            }
  },
  methods: {
    ...mapBuildingActions([
      'getBuildings'
    ]),
    ...mapDynamicMutations([
      'updateDetail'
    ]),
    ...mapDynamicActions([
      'getDetail',
      'editDynamics'
    ]),
        ...mapActivityActions([
      'addActivity',
      'activityDetails',
      'updateActivity'
    ]),
    ...mapImgActions([
      'uploadImg'
    ]),
    beforeImgUpload (file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        return false
      }
      // if (file.size / 1024 > 300) {
      //   this.$message.error('图片大小不允许超过300k!')
      //   return false
      // }
      this.loading = this.$loading({
        lock: true,
        text: '上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      return true
    },
    handleRemove(file, fileList) {
      this.imgList = fileList;
    },

    handleAvatarSuccess (res) {
      this.imageUrl = res.data
    },
    shareImageHandleAvatarSuccess(res, file) { // 海报图
      this.shareImageUrl = URL.createObjectURL(file.raw);
      // console.log(res)
      this.activityQuery.shareImg = res.data
    },
    onSubmit (formName) {
      this.$refs[formName].validate((valid) => {
      if (valid) {
        // 活动时间校验
      const endDate = this.formateDate(this.activityQuery.endDate); 
      const startDate = this.formateDate(this.activityQuery.startDate);           
      if( endDate <= startDate){
        this.$message({ showClose: true, message: '活动结束时间不能小于活动开始时间',type: 'error'});
        return 
      }
      // 富文本校验
      if( this.activityQuery.desc === '' || this.activityQuery.desc === null|| this.activityQuery.desc ==='<p><br></p>'){
        this.$message({ showClose: true, message: '活动详情不能为空',type: 'error'});
        return 
      }
      // 报名时间校验
      const enlistStart = this.formateDate(this.activityQuery.enlistStart); 
      const enlistEnd = this.formateDate(this.activityQuery.enlistEnd);           
      if(this.activityQuery.isEnlist ==='1' && enlistEnd<= enlistStart ){
        this.$message({ showClose: true, message: '报名结束时间不能小于报名开始时间',type: 'error'});
        return 
      }
      this.activityQuery.url = this.imageUrl 
        this.updateActivity(    
           JSON.stringify(this.activityQuery)
        ).then((res) => {
          this.$notify.success('操作成功')
          this.$router.push({ name: "activity-list" });
        }).catch((err) => {
          this.$notify.error(err.msg || err.message)
        })
     
        } else {
            console.log('error submit!!');
            return false;
          }
        })
    },
    onCancel () {
      this.$router.push({name: 'activity-list'})
    },
    getDetails(){
      this.activityQuery.dynamicId = this.$route.query.row
        this.activityDetails(this.activityQuery).then((data) => {
        this.activityQuery.buildingId = data.buildingId
        this.activityQuery.title = data.title
        this.activityQuery.startDate = data.startDate 
        this.activityQuery.endDate = data.endDate
        this.activityQuery.address = data.address
        this.activityQuery.personNum = data.personNum
        this.imageUrl = data.url
        this.activityQuery.isEnlist = data.isEnlist
        this.activityQuery.desc = data.desc
        this.activityQuery.enlistStart = dayjs(data.enlistStart).toDate()
        this.activityQuery.enlistEnd = dayjs(data.enlistEnd).toDate()
        this.activityQuery.shareImg = data.shareImg
        this.shareImageUrl = data.shareImg

        })
    },
    formateDate(dt) {
      return !dt ? '' : dayjs(dt).format('YYYY-MM-DD HH:mm')
    },
  },
  mounted () {
    // const editor = new E('#desc')
    // editor.customConfig.zIndex = 1
    // editor.create()
    this.getDetails()
    
  }
}
</script>

<style lang="scss" scoped>
  .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>
