<template>
  <el-form ref="activityQuery" :model="activityQuery" :rules="rules"  label-width="160px">
    <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="主图：">
          <el-upload
            :action="upFileUrl"
            name='file'
            list-type="picture-card"
            :headers="uploadHeaders"
            :file-list="imgList"
            :show-file-list="true"
            :before-upload="beforeImgUpload"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
    </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="websiteEditorElem" 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-form-item>
  </el-form>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
import apis from '../../config/api'
import E from 'wangeditor'

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:'',
      upFileUrl: apis.file.upload.url,
      radio:'1',
      imgList: [],
      shareImageUrl: '',
      dialogVisible: false,
      dialogImageUrl: "",
      activityQuery: {
       url:'',
       startDate:'',
       endDate:'',
       buildingId:'',
       title:'',
       isEnlist:'1',
       desc:'',
       enlistStart:'',
       enlistEnd:'',
       personNum:'',
       shareImg: ''
      },
      rules: {
          buildingId: [
            { required: true, message: '请选择所属项目', trigger: 'change' }
          ],
          url: [
            { required: true, message: ' ', trigger: 'change' }
          ],
          title: [
            { required: true, message: '请输入标题', trigger: 'blur' },
          ],
          startDate: [
            { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
          ],
          endDate: [
            { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
          ],
          address: [
            {  required: true, message: '请至少输入活动地点', trigger: 'change' }
          ],
          personNum: [
            { required: true, message: '请输入活动人数', trigger: 'change' }
          ],
          desc: [
            { required: true, message: ' ', trigger: 'blur' }
          ],
          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',
    ]),
    ...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.activityQuery.url = res.data
      this.updateDetail({...this.dynamic, imgUrl: res.data})
      this.loading.close()
    },
    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) {
        // 主图不可为空
        if(this.activityQuery.url ===''){
          this.$message({ showClose: true, message: '请选择主图!',type: 'error'});
        return false
        }
      console.log('this.activityQuery.desc',this.activityQuery.desc)
      const endDate=this.activityQuery.endDate
      const startDate=this.activityQuery.startDate
      if( endDate <= startDate){
        this.$message({ showClose: true, message: '活动结束时间不能小于活动开始时间',type: 'error'});
        return false
      }
      if( this.activityQuery.desc === '' || this.activityQuery.desc === null){
        this.$message({ showClose: true, message: '活动详情不能为空',type: 'error'});
        return false
      }

      const enlistStart= this.activityQuery.enlistStart
      const enlistEnd= this.activityQuery.enlistEnd
      if(this.activityQuery.isEnlist ==='1' && enlistEnd<= enlistStart ){
        this.$message({ showClose: true, message: '报名结束时间不能小于报名开始时间',type: 'error'});
        return false
      }
        this.addActivity(
          JSON.stringify(this.activityQuery)
        ).then(() => {
          this.onCancel()
          
        })
        this.$router.push({ name: "activity-list" });
          } else {
            console.log('error submit!!');
            return false;
          }
        })
    },
    onCancel () {
      this.$router.push({name: 'dynamiclist'})
    },
  },
  mounted () {
    const _that = this
    const phoneEditor = new E('#websiteEditorElem')
    phoneEditor.customConfig.zIndex = 1
    phoneEditor.customConfig.onchange = function (html) {
      _that.activityQuery = {..._that.activityQuery, desc: html}
       console.log('that.dynamic.url',_that.activityQuery.desc)
    }
    // phoneEditor.customConfig.uploadImgServer = this.upFileUrl
    // phoneEditor.customConfig.uploadFileName = 'uploadFiles'

    phoneEditor.customConfig.customUploadImg = function (files, insert) {
      _that.uploadImg(files[0]).then(data => {
        insert(data)
      })
    }
    phoneEditor.customConfig.menus = [
      'head',  // 标题
      'bold',  // 粗体
      'fontSize',  // 字号
      'fontName',  // 字体
      'italic',  // 斜体
      'underline',  // 下划线
      'strikeThrough',  // 删除线
      'foreColor',  // 文字颜色
      'backColor',  // 背景颜色
      'justify',  // 对齐方式
      'image',  // 插入图片
    ]
    phoneEditor.create()
    
    this.getBuildings({
      pageNum: 1,
      pageSize: 100,
    }).then(() => {
      if ((this.$route.query.id || '') !== '') {
        this.getDetail({id: this.$route.query.id}).then((data) => {
          phoneEditor.txt.html(data.url)
        })
      }
    })
  }
}
</script>

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