<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
          <el-form-item label="所属联盟" prop="unionId">
          <el-select v-model="dataForm.unionId" filterable placeholder="请选择" style="width: 100%">
            <el-option v-for="item in options"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
      </el-form-item>
          <el-form-item label="活动名称" prop="title">
          <el-input v-model="dataForm.title" placeholder="活动名称"></el-input>
      </el-form-item>
          <el-form-item label="活动时间" prop="actTime">
          <el-date-picker v-model="dataForm.actTime"
                          type="datetimerange"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期">
          </el-date-picker>
      </el-form-item>
          <el-form-item label="排序" prop="sort">
          <el-input-number v-model="dataForm.sort" :min="0" :max="9999999" label="排序" style="width: 260px"></el-input-number>
      </el-form-item>
          <el-form-item label="简介" prop="content">
          <el-row style="height: 400px;">
              <tinymce-editor v-model="dataForm.content"></tinymce-editor>
          </el-row>
      </el-form-item>
          <el-form-item label="精彩瞬间">
          <el-upload  accept="image/png, image/jpeg"
                      :action="uploadUrl"
                      list-type="picture-card"
                      :file-list="dataForm.images"
                      :limit="10"
                      :on-success="handleAvatarActSuccess"
                      :on-remove="removeImage"
                      :on-exceed="handleExceed">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import Cookies from 'js-cookie'
import TinymceEditor from '@/components/tinymce-editor'
export default {
  data () {
    return {
      visible: false,
      dataForm: {
        id: '',
        unionId: '',
        title: '',
        actStartTime: '',
        actEndTime: '',
        content: '',
        sort: '',
        actTime: [],
        images: []
      },
      uploadUrl: '',
      imgSort: 0,
      options: []
    }
  },
  computed: {
    dataRule () {
      return {
        unionId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        title: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        actTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        content: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.getOptionVolunteerUnion()
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/oss/file/upload?token=${Cookies.get('token')}`
        this.dataForm.images = []
        this.imgSort = 0
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 获取联盟下拉列表
    getOptionVolunteerUnion () {
      this.$http.get(`/heart/volunteerunion/optionVolunteerUnion`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.options = res.data
      }).catch(() => {})
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/heart/volunteerunionact/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        // 如果是追加图片，则赋值 imgSort
        if (this.dataForm.images.length > 0) {
          this.imgSort = this.dataForm.images[this.dataForm.images.length - 1].imgSort
        }
        console.log('this.imgSort:' + this.imgSort)
      }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.id ? 'post' : 'put']('/heart/volunteerunionact/', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    // 图片处理
    handleAvatarActSuccess (res, file) {
      let image = {}
      image.name = Math.round(Math.random() * 5)
      image.url = res.data.url
      this.imgSort = this.imgSort + 1
      image.imgSort = this.imgSort
      this.dataForm.images.push(image)
    },
    removeImage (file, fileList) {
      this.dataForm.images = fileList
    },
    handleExceed () {
      this.$message({
        showClose: true,
        message: '精彩瞬间最多只能上传十张照片',
        type: 'warning'
      })
    }
  },
  components: {
    TinymceEditor
  }
}
</script>
