<template>
    <el-card shadow="never"
             class="aui-card--fill">
        <div class="mod-news__news}">
            <el-form :inline="true"
                     :model="dataForm"
                     :rules="dataRule"
                     ref="dataForm"
                     :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'">
                <el-row>
                    <el-form-item label="活动头图：" v-loading="loading" prop="headPic">
                        <el-upload class="avatar-uploader"
                                   :action="uploadUrl"
                                   :show-file-list="false"
                                   :on-success="handleAvatarActSuccess"
                                   :on-error="handelError"
                                   :before-upload="beforeAvatarUpload">
                            <img v-if="dataForm.headPic"
                                 :src="dataForm.headPic"
                                 class="avatar">
                            <i v-else
                               class="el-icon-plus avatar-uploader-icon"></i>
                            <div slot="tip"
                                 class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="活动标题："
                                  prop="title">
                        <el-input v-model="dataForm.title"
                                  type="text"
                                  maxlength="40"
                                  show-word-limit
                                  placeholder="请输入标题，40字以内"
                                  clearable
                                  style="width:500px">
                        </el-input>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="报名要求：" prop="requirement">
                        <el-input v-model="dataForm.requirement" placeholder="请输入报名要求，200字以内"
                                  type="textarea"
                                  style="width:500px"
                                  maxlength="200"
                                  clearable>
                        </el-input>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="报名截止时间："
                                  prop="signupEndTime">
                        <el-date-picker v-model="dataForm.signupEndTime"
                                        type="datetime"
                                        value-format="yyyy-MM-dd hh:mm"
                                        format="yyyy-MM-dd hh:mm"
                                        placeholder="选择日期时间">
                        </el-date-picker>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="活动名额："
                                  prop="actQuota">
                        <template>
                            <el-radio v-model="dataForm.actQuotaCategory"
                                      label="1">固定名额</el-radio>&emsp;&emsp;
                            <el-input-number v-enter-number type="number" :min="1" v-model="dataForm.actQuota" placeholder="固定名额"style="width:150px"></el-input-number>&emsp; 人&emsp;&emsp;
                            <el-radio v-model="dataForm.actQuotaCategory"
                                      label="0">不限名额</el-radio>
                        </template>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="活动时间："
                                  prop="actStartTime">
                        <el-date-picker v-model="dataForm.actStartTime"
                                        type="datetime"
                                        value-format="yyyy-MM-dd hh:mm"
                                        format="yyyy-MM-dd hh:mm"
                                        @change="dateChangeTime"
                                        placeholder="选择日期时间">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="至"
                                  label-width="40px"
                                  prop="actEndTime">
                        <el-date-picker v-model="dataForm.actEndTime"
                                        type="datetime"
                                        value-format="yyyy-MM-dd hh:mm"
                                        format="yyyy-MM-dd hh:mm"
                                        placeholder="选择日期时间">
                        </el-date-picker>
                    </el-form-item>
                </el-row>
                <el-row>
                    <div>
                        <el-form-item label="打卡范围时间："
                                      prop="signinStartTime">
                            <el-date-picker v-model="dataForm.signinStartTime"
                                            :disabled="signInIsAble"
                                            type="datetime"
                                            value-format="yyyy-MM-dd hh:mm"
                                            format="yyyy-MM-dd hh:mm"
                                            placeholder="选择日期时间">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="至"
                                      label-width="40px"
                                      prop="signinEndTime">
                            <el-date-picker v-model="dataForm.signinEndTime"
                                            type="datetime"
                                            value-format="yyyy-MM-dd hh:mm"
                                            format="yyyy-MM-dd hh:mm"
                                            placeholder="选择日期时间">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label=" ">
                            <div>
                                <font color="gray">默认活动开始（不可编辑时间）至活动结束一小时后，可修改时间范围，必须早于开始时间，晚于结束时间</font>
                            </div>
                        </el-form-item>
                    </div>
                </el-row>

                <el-row>
                    <el-form-item label="活动地点："
                                  prop="actAddress">
                        <el-input v-model="dataForm.actAddress"
                                  :disabled="signInIsAble"
                                  type="text"
                                  clearable
                                  style="width:400px">
                        </el-input>&emsp;
                        <el-button type="primary"
                                   @click="mapSelectHandle(1)">地图选择</el-button>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="打卡地点："
                                  prop="signinAddress">
                        <el-input v-model="dataForm.signinAddress"
                                  :disabled="signInIsAble"
                                  type="text"
                                  clearable
                                  style="width:400px">
                        </el-input>&emsp;
                        <el-button type="primary"
                                   @click="mapSelectHandle(2)">地图选择</el-button>
                        <div>
                            <font color="gray">打卡地点，默认活动地点，可以修改打卡地点（如集合地点，集体出发等）</font>
                        </div>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="打卡范围："
                                  prop="clockRadius">
                        <div>
                            <el-input-number v-enter-number type="number" :min="0" :max="5000"  v-model="dataForm.clockRadius"
                                      clearable style="width:150px">
                            </el-input-number>&emsp;米以内
                        </div>
                        <div>
                            <font color="gray">默认已打卡地点200米以内，可修改范围，在范围内打卡签到有效</font>
                        </div>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="联系人："
                                  prop="contacts">
                        <el-input v-model="dataForm.contacts" style="width:150px"></el-input>
                    </el-form-item>
                    <el-form-item label="联系电话："
                                  prop="tel">
                        <el-input v-model="dataForm.tel" style="width:200px"></el-input>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="活动主办方："
                                  prop="sponsor">
                        <el-input v-model="dataForm.sponsor"
                                  type="text"
                                  maxlength="30"
                                  show-word-limit
                                  placeholder="请输入主办方，30字以内"
                                  clearable
                                  style="width:500px">
                        </el-input>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="奖励积分："
                                  prop="reward">
                        <el-input-number v-enter-number type="number" :min="0"v-model="dataForm.reward"
                                  clearable style="width:150px">
                        </el-input-number>&emsp;积分
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="惩罚积分："
                                  prop="punishmentPoints">
                        <el-input-number v-enter-number type="number" :min="0" v-model="dataForm.punishmentPoints"
                                  clearable style="width:150px">
                        </el-input-number>&emsp;积分
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item prop="actContent"
                                  label="活动内容：">
                        <div style="width:1000px">
                            <!-- 富文本编辑器, 容器 -->
                            <div id="J_quillEditor" ></div>
                            <!-- 自定义上传图片功能 (使用element upload组件) -->
                            <el-upload :action="uploadUrl"
                                       :show-file-list="false"
                                       :before-upload="uploadBeforeUploadHandle"
                                       :on-success="uploadSuccessHandle"
                                       style="display: none;">
                                <el-button ref="uploadBtn"
                                           type="primary"
                                           size="small">{{ $t('upload.button') }}</el-button>
                            </el-upload>
                        </div>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="banner展示："
                                  prop="isBanner">
                        <template>
                            <el-radio v-model="dataForm.isBanner"
                                      label="1">是</el-radio>
                            <el-radio v-model="dataForm.isBanner"
                                      label="0">否</el-radio>
                        </template>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label=" " v-loading="loading" prop="bannerUrl">
                        <el-upload class="avatar-uploader"
                                   :action="uploadUrl"
                                   :show-file-list="false"
                                   :on-success="handleAvatarBannerSuccess"
                                   :on-error="handelError"
                                   :before-upload="beforeAvatarUpload">
                            <img v-if="dataForm.bannerUrl"
                                 :src="dataForm.bannerUrl"
                                 class="avatar">
                            <i v-else
                               class="el-icon-plus avatar-uploader-icon"></i>
                            <div slot="tip"
                                 class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label-width="500px">
                        <el-button type="primary" :disabled="isAble"
                                   @click="dataFormSubmitHandle()">{{$t("confirm")}}</el-button>
                        <el-button  @click="backToActList">{{ $t('cancel') }}</el-button>
                    </el-form-item>
                </el-row>
            </el-form>
            <map-select v-if="mapSelectVisible" ref="mapSelect" v-on:position="position"></map-select>
        </div>
    </el-card>
</template>
<script>
import Cookies from 'js-cookie'
import MapSelect from './map-select'
import debounce from 'lodash/debounce'
import 'quill/dist/quill.snow.css'
import Quill from 'quill'
export default {
  name: 'ActInfoAdd',
  data () {
    return {
      visible: false,
      dataForm: {
        id:"",
        title: '',
        headPic: '',
        signupStartTime: '',
        signupEndTime: '',
        actQuotaCategory:'1',
        actStartTime: '',
        actEndTime: '',
        actAddress: '',
        actLongitude: '',
        actLatitude: '',
        signinStartTime: '',
        signinEndTime: '',
        signinAddress: '',
        signinLongitude: '',
        signinLatitude: '',
        clockRadius: 200,
        actQuota: '',
        contacts: '',
        tel: '',
        requirement: '',
        actContent: '',
        actStatus: '',
        publishTime: '',
        sponsor: '',
        deptId: '',
        punishmentPoints: '',
        reward: '',
        isBanner:"1",
        bannerUrl:""
      },
        mapSelectVisible:false,
        signInIsAble: true,
        isAble: false,
        loading: false,
        // 富文本
        quillEditor: null,
        quillEditorToolbarOptions: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block', 'image'],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'script': 'sub' }, { 'script': 'super' }],
            [{ 'indent': '-1' }, { 'indent': '+1' }],
            [{ 'direction': 'rtl' }],
            [{ 'size': ['small', false, 'large', 'huge'] }],
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            [{ 'color': [] }, { 'background': [] }],
            [{ 'font': [] }],
            [{ 'align': [] }],
            ['clean']
        ],
        uploadUrl: '',
        pickerBeginDateBefore: {
            disabledDate: (time) => {
                let beginDateVal = this.dataForm.actStartTime
                if (beginDateVal) {
                    return time.getTime() > new Date(beginDateVal).getTime()
                }

            }
        },
        pickerBeginSignInDateAfter: {
            disabledDate: (time) => {
                let EndDateVal = this.dataForm.signinEndTime
                if (EndDateVal) {
                    return time.getTime() < new Date(EndDateVal).getTime()
                }
            }
        },
        pickerBeginDateAfter: {
            disabledDate: (time) => {
                let EndDateVal = this.dataForm.actEndTime
                if (EndDateVal) {
                    return time.getTime() < new Date(EndDateVal).getTime()
                }
            }
        }
    }
  },
    created () {
        this.$http
            .get(`/sys/user/deptOptions/getByLoginUser`)
            .then(({ data: res }) => {
                if (res.code !== 0) {
                    return this.$message.error(res.msg)
                }
                this.options = res.data.options
            })
            .catch(() => {})
        this.visible = true
        this.$nextTick(() => {
            // 富文本
            this.hideUpload = false
            this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/oss/file/upload?token=${Cookies.get('token')}`
            if (this.quillEditor) {
                this.quillEditor.deleteText(0, this.quillEditor.getLength())
            } else {
                this.quillEditorHandle()
            }
            // 富文本end
        })
    },
  computed: {
    dataRule () {
      return {
        title: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        headPic: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        signupStartTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        signupEndTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        signinStartTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        signinEndTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        actStartTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        actEndTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        actAddress: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        actLongitude: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        actLatitude: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        signinAddress: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        signinLongitude: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        signinLatitude: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        clockRadius: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        actQuota: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        signupNum: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        clockNum: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        actShareNum: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        actBrowseNum: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        contacts: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        tel: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        requirement: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        actContent: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        actStatus: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        publishTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        sponsor: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        punishmentPoints: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        reward: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        revision: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        createdBy: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        createdTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        updatedBy: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        updatedTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    dateChangeTime(){
        this.dataForm.signinStartTime = this.dataForm.actStartTime
    },
    backToActList () {
        this.$emit('refreshDataList')
        this.$parent.selectComponent = 'ActInfoList'
        this.$router.push({ path: '/heart-actinfo'})

    },
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
      position(position){
        if(position.type == 1 ){
            this.dataForm.actAddress = position.address;
            this.dataForm.actLatitude = position.latitude;
            this.dataForm.actLongitude = position.longitude;
            this.dataForm.signinAddress = position.address;
            this.dataForm.signinLatitude = position.latitude;
            this.dataForm.signinLongitude = position.longitude;
        } else {
            this.dataForm.signinAddress = position.address;
            this.dataForm.signinLatitude = position.latitude;
            this.dataForm.signinLongitude = position.longitude;
        }
      },
      // 富文本编辑器
      quillEditorHandle () {
          this.quillEditor = new Quill('#J_quillEditor', {
              modules: {
                  toolbar: this.quillEditorToolbarOptions
              },
              theme: 'snow'
          })
          this.quillEditor.container.style.height = `${300}px`
          // // 自定义上传图片功能 (使用element upload组件)
          this.quillEditor.getModule('toolbar').addHandler('image', () => {
              this.$refs.uploadBtn.$el.click()
          })
          // 监听内容变化，动态赋值
          this.quillEditor.on('text-change', () => {
              this.dataForm.actContent = this.quillEditor.root.innerHTML
              if ((this.dataForm.actContent).length > 10000) {
                  return this.$message.error('您输入的的内容已超过字数')
              }
          })
      },
      // 上传图片之前 (富文本)
      uploadBeforeUploadHandle (file) {
          if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
              this.$message.error(this.$t('upload.tip', { 'format': 'jpg、png、gif' }))
              return false
          }
      },
      // 上传图片成功 (富文本)
      uploadSuccessHandle (res, file, fileList) {
          if (res.code !== 0) {
              return this.$message.error(res.msg)
          }
          this.quillEditor.insertEmbed(this.quillEditor.getSelection().index, 'image', res.data.url)
      },
      setRegistTime () {
          this.dataForm.newsReleaseStartTime = this.time[0]
          this.dataForm.newsReleaseEndTime = this.time[1]
      },
      // 上传图片ends
    // 获取信息
    getInfo () {
      this.$http.get(`/heart/actinfo/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
      }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
        if (this.dataForm.isActQuota == 0){
            this.dataForm.actQuota = 0
        }
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.isAble = true
        this.$http[!this.dataForm.id ? 'post' : 'put']('/heart/actinfo/', this.dataForm).then(({ data: res }) => {
          this.isAble = false
          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')
            }
          })
          this.$parent.selectComponent = 'ActInfoList'
          this.$router.push({ path: '/heart-actinfo'})
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false }),
      handleAvatarActSuccess (res, file) {
          this.loading = false
          this.dataForm.headPic = res.data.url
      },
      handleAvatarBannerSuccess (res, file) {
          this.loading = false
          this.dataForm.bannerUrl = res.data.url
      },
      beforeAvatarUpload (file) {
          this.loading = true
      },
      handelError () {
          this.loading = false
      },
      mapSelectHandle (type) {
          this.mapSelectVisible = true
          this.$nextTick(() => {
              this.$refs.mapSelect.init(type,this.dataForm.clockRadius)
          })
      }
  },
  components: {
      MapSelect
    }
}
</script>
<style>
    .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>
<style lang="scss">
    .project-handle {
        .el-timeline {
            padding-left: 9px;
            font-size: 13px;
        }
        .el-textarea {
            width: 600px !important;
        }
        .el-input {
            width: 600px !important;
        }
    }
    .el-form-item__label {
        font-weight: bold;
    }
</style>

<style lang="scss" scoped>
    .project-handle {
        width: 100%;
        height: calc(100vh - 120px);
        background: #ffffff;
        box-sizing: border-box;
        padding: 10px;
        .project-detail {
            width: 100%;
            height: 49%;
            border: 2px solid #ccc;
            box-sizing: border-box;
            padding: 10px;
            padding-top: 20px;
            float:left;
            margin-bottom: 1%;
            position:relative;
            .project-detail-tip {
                position: absolute;
                top: 0;
                left:0;
                width: 80px;
                height: 30px;
                line-height: 30px;
                color: #ffffff;
                background: #4ac38b;
                text-align:center;
            }
            .el-form {
                width: 58%;
                height: 100%;
                float:left;
                overflow-y:auto;
                &::-webkit-scrollbar {
                    width: 5px;
                    height: 1px;
                }
                &::-webkit-scrollbar-thumb {
                    border-radius: 5px;
                    background: #ccc;
                }
                &::-webkit-scrollbar-track {
                    border-radius: 10px;
                    background: #fff;
                }
            }
            .container {
                width: 40%;
                height: 100%;
                float: right;
                .location {
                    height: 30px;
                    line-height: 30px;
                }
                #map {
                    width: 100%;
                    height: calc(100% - 30px);
                }
            }
        }
        .project-progress {
            width: 20%;
            height: 100%;
            float: right;
            border: 2px solid #ccc;
            box-sizing: border-box;
            margin-left: 1%;
            padding-top: 20px;
            overflow-y:auto;
            &::-webkit-scrollbar {
                width: 5px;
                height: 1px;
            }
            &::-webkit-scrollbar-thumb {
                border-radius: 5px;
                background: #aaa;
            }
            &::-webkit-scrollbar-track {
                border-radius: 10px;
                background: #ccc;
            }
        }
        .handle-operation {
            padding-top: 30px;
            box-sizing: border-box;
            width: 100%;
            height: 49%;
            box-sizing: border-box;
            border: 2px solid #ccc;
            float:left;
            position: relative;
            overflow-y:auto;
            &::-webkit-scrollbar {
                width: 5px;
                height: 1px;
            }
            &::-webkit-scrollbar-thumb {
                border-radius: 5px;
                background: #aaa;
            }
            &::-webkit-scrollbar-track {
                border-radius: 10px;
                background: #ccc;
            }
            .handle-operation-tip {
                position: absolute;
                top: 0;
                left:0;
                width: 80px;
                height: 30px;
                line-height: 30px;
                color: #ffffff;
                background: #ff7600;
                text-align:center;
            }
        }
    }
</style>