<template>
  <div class="page"
       style="padding-bottom: 70px">
    <el-form label-width="170px"
             label-suffix=":"
             class="input-form model"
             size="small">
      <el-form-item label="活动封面（选填）">
        <el-upload class="avatar-uploader"
                   accept=".jpg,.png,.jpeg,.gif"
                   :limit="1"
                   :on-exceed="handleExceed"
                   :before-remove="beforeRemove"
                   :on-remove="handleRemove"
                   :on-error="uploadError"
                   action=""
                   :http-request="handleRequest">
          <img v-if="form.coverUrl"
               :src="form.coverUrl"
               class="avatar">
          <div class="uploader-default"
               v-else>
            <i class="el-icon-plus"></i>
            <p>上传封面</p>
          </div>
          <div slot="tip"
               class="el-upload__tip">
            <p>展示宽度为220，高度140，JPG/PNG/GIF，3MB以内</p>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item prop="source"
                    label="活动分类">
        <el-select v-model="classificationId"
                   clearable>
          <template v-for="item in classifications">
            <el-option v-if="item.id"
                       :key="item.id"
                       :label="item.classificationName"
                       :value="item.id">
            </el-option>
          </template>
        </el-select>
        <el-button class="set-btn"
                   type="primary"
                   @click="setClass">设置</el-button>
      </el-form-item>
      <el-form-item class="req"
                    label="活动名称">
        <div class="d-inline-block">
          <el-input id="firstInput"
                    placeholder="请输入活动名称"
                    v-model="form.name"
                    clearable></el-input>
        </div>
      </el-form-item>
      <el-form-item class="req"
                    label="主办方">
        <div class="inline-input">
          <div class="input-wrap"
               v-for="(item,index) in sponsorList"
               :key="index">
            <el-input placeholder="主办方名称"
                      v-model="sponsorList[index]"></el-input>
            <i v-if="sponsorList.length > 1"
               class="remove"
               @click="delSponsor(index)"></i>
            <button v-if="index == 0"
                    class="add-btn"
                    type="button"
                    @click="addSponsor">
              <i class="el-icon-plus"></i>
              <span>添加</span>
            </button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="承办方（选填）">
        <div class="inline-input">
          <div class="input-wrap"
               v-for="(item,index) in undertakerList"
               :key="index">
            <el-input placeholder="承办方名称"
                      v-model="undertakerList[index]"></el-input>
            <i v-if="undertakerList.length > 1"
               class="remove"
               @click="delOrganizer(index)"></i>
            <button v-if="index == 0"
                    class="add-btn"
                    type="button"
                    @click="addOrganizer">
              <i class="el-icon-plus"></i>
              <span>添加</span>
            </button>
          </div>
        </div>
        <button v-if="!undertakerList.length"
                class="add-btn"
                type="button"
                @click="addOrganizer">
          <i class="el-icon-plus"></i>
          <span>添加</span>
        </button>
      </el-form-item>
      <el-form-item class="req"
                    label="报名时间">
        <el-date-picker v-model="signupTime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        type="datetimerange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :picker-options="pickerOptions"></el-date-picker>
      </el-form-item>
      <el-form-item class="req"
                    label="举办时间">
        <el-date-picker v-model="playTime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        type="datetimerange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :picker-options="pickerOptions"></el-date-picker>
      </el-form-item>
      <el-form-item class="req"
                    label="举办地点">
        <el-input placeholder="请输入举办地点"
                  type="textarea"
                  v-model="form.reportingPlace"
                  clearable />
      </el-form-item>
      <el-form-item class="req"
                    label="发布范围">
        <div>
          <el-radio v-model="form.competitionScope"
                    :label="1">全平台</el-radio>
        </div>
        <div class="flex a-center">
          <el-radio v-model="form.competitionScope"
                    :label="0">指定范围</el-radio>

          <el-checkbox-group v-if="!form.competitionScope"
                             v-model="competitionScope">
            <el-checkbox v-for="(item, i) in scopes"
                         :key="i"
                         :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>

        </div>
      </el-form-item>
      <el-form-item class="req"
                    label="报名人数上限">
        <div class="input-center">
          <el-input placeholder="请输入人数"
                    v-model.number="form.quantityLimit"
                    type="number"></el-input> 人
        </div>
      </el-form-item>
      <el-form-item label="是否展示报名人员">
        <el-radio v-model="form.whetherToShowApplicants"
                  label="1">是</el-radio>
        <el-radio v-model="form.whetherToShowApplicants"
                  label="0">否</el-radio>
      </el-form-item>
      <el-form-item class="req"
                    label="报名邀请码">
        <div class="input-center"
             style="width: 550px;">
          <el-radio v-model="form.isNeedCode"
                    :label="0">不需要</el-radio>
          <el-radio v-model="form.isNeedCode"
                    :label="1">需要</el-radio>
          <el-input style="width: 250px"
                    placeholder="请输入4位邀请码或点击随机生成"
                    maxlength="4"
                    v-model="form.invitationCode"
                    :disabled="form.isNeedCode === 0"></el-input>
          <el-button v-if="form.isNeedCode === 1"
                     @click="randomInv">随机</el-button>
        </div>
      </el-form-item>
      <el-form-item class="req"
                    label="活动详情">
        <Editor api-key='rnk6zw9v267xqz7pf98twt1vmrvltmd436je7a642pckltda'
                v-model="form.description"
                :init="editorConfig" />
      </el-form-item>
      <el-form-item label="附件">
        <Upload :limit="5"
                :file-list.sync="form.competitionAnnexList"
                :changeFileList="false"
                :on-remove="handleAnnexRemove"
                @onSuccess="uploadAnnexSuccess" />
      </el-form-item>
    </el-form>

    <div class="btns">
      <el-button @click="save(0)">保存</el-button>
      <el-button type="primary"
                 @click="save(1)">发布</el-button>
      <el-button type="danger"
                 @click="preview">预览</el-button>
      <el-button @click="back">取消</el-button>
    </div>

    <el-dialog title="所属分类设置"
               :visible.sync="classVisible"
               width="500px"
               :close-on-click-modal="false"
               class="manage-dia"
               :before-close="closeClass">
      <div class="plus">
        <i class="el-icon-circle-plus-outline"
           @click="addClass"></i>
      </div>
      <el-table :data="classifications"
                ref="table"
                header-align="center"
                row-key="id">
        <el-table-column type="index"
                         width="60"
                         label="序号"
                         align="center"></el-table-column>
        <el-table-column prop="classificationName"
                         label="分类名称"
                         align="center"
                         min-width="130">
          <template slot-scope="scope">
            <el-input v-if="scope.row.edit"
                      placeholder="请输入分类名称"
                      v-model="scope.row.classificationName"
                      clearable
                      maxlength="30"></el-input>
            <span v-else>{{ scope.row.classificationName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         align="center"
                         min-width="60">
          <template slot-scope="scope">
            <i v-if="scope.row.edit"
               class="el-icon-check edit"
               @click="submitClass(scope.row)"></i>
            <i v-else
               class="el-icon-edit edit"
               @click="editClass(scope.row)"></i>
            <i class="el-icon-delete del"
               @click="delClass(scope.row, scope.$index)"></i>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer">
        <el-button @click="closeClass">返回</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Util from "@/libs/util";
import Editor from '@tinymce/tinymce-vue'
import editorConfig from '@/components/editor'
import Setting from "@/setting";
import Upload from '@/components/upload';
import Oss from '@/components/upload/upload.js'
export default {
  data () {
    return {
      id: this.$route.query.id || '',
      name: this.$route.query.name,
      headers: {
        token: Util.local.get(Setting.tokenKey)
      },
      editorConfig,
      scope: 0,
      form: {
        id: this.$route.query.id || '',
        founder: 1,
        carouselUrl: '',
        coverUrl: '',
        competitionAnnexList: [], // 赛事附件
        isNeedCode: 0,
        invitationCode: '',
        signUpStartTime: '',
        signUpEndTime: '',
        playStartTime: '',
        playEndTime: '',
        description: '',
        name: '',
        publishStatus: 0,
        competitionScope: 1,
        whetherToShowApplicants: '1',
        reportingPlace: '',
        competitionRangeList: [],
        competitionRegistration: {},
        createSource: 0,
        quantityLimit: '',
        classificationId: ''
      },
      classifications: [],
      classVisible: false,
      competitionScope: [],
      scopes: [
        {
          id: 5,
          name: '幼儿园端'
        },
        {
          id: 6,
          name: '供应商端'
        },
      ],
      pickerOptions: {
        disabledDate: time => {
          return this.$route.query.id ? false : time.getTime() < new Date().getTime() - 86400000;
        }
      },
      fileName: '',
      signupTime: [],
      playTime: [],
      sponsorList: [""],
      undertakerList: [''],
      fileList: [],
      submiting: false,
      pass: false,
      updateTime: 0,
    };
  },
  components: {
    Editor,
    Upload
  },
  computed: {
    classificationId: {
      get () {
        const data = this.classifications.find(item => item.id == this.form.classificationId)
        return data ? data.id : ''
      },
      set (newVal) {
        this.form.classificationId = newVal
      }
    },
  },
  watch: {
    // 监听信息是否有更改,有的话页面离开的时候要询问是否要保存
    form: {
      handler () {
        this.updateTime++
      },
      deep: true
    },
    signupTime: function (val) {
      const { form } = this
      if (val) {
        form.signUpStartTime = val[0];
        form.signUpEndTime = val[1];
      } else {
        form.signUpStartTime = ''
        form.signUpEndTime = ''
      }
    },
    playTime: function (val) {
      const { form } = this
      if (val) {
        form.playStartTime = val[0]
        form.playEndTime = val[1]
      } else {
        form.playStartTime = ''
        form.playEndTime = ''
      }
    }
  },
  // 页面离开的时候如果没有保存则提示
  // beforeRouteLeave (to, from, next) {
  //   if (this.submiting) {
  //     next()
  //   } else if (!this.pass) {
  //     // 更改了信息才需要提示
  //     if (this.updateTime) {
  //       this.$confirm(`所填写内容暂未保存，是否保存？`, '提示', {
  //         type: 'warning'
  //       }).then(() => {
  //         this.save(this.form.publishStatus)
  //       }).catch(() => {
  //         next()
  //       })
  //     } else {
  //       next()
  //     }
  //   } else {
  //     next()
  //   }
  // },
  mounted () {
    this.$store.commit('user/setCrumbs', [
      {
        name: '活动管理',
        route: '/activity'
      },
      {
        name: this.id ? this.name : '创建活动'
      },
    ])
    this.getClassification()
    this.getData()
  },
  methods: {
    getData () {
      const { id } = this.form
      id && this.$post(`${this.api.getCompetition}?competitionId=${id}`).then(res => {
        const data = res.competition
        if (data.signUpStartTime) this.signupTime = [data.signUpStartTime, data.signUpEndTime]
        if (data.playStartTime) this.playTime = [data.playStartTime, data.playEndTime]
        if (data.sponsor) this.sponsorList = data.sponsor.split(",")
        if (data.undertaker) this.undertakerList = data.undertaker.split(",")
        if (!data.competitionScope) {
          data.competitionScope = 1
        } else if (data.competitionScope !== 1) {
          this.competitionScope = data.competitionScope.split(',').map(e => +e)
          data.competitionScope = 0
        }
        // 附件
        const fileList = data.competitionAnnexList
        if (fileList) {
          fileList.map(e => {
            e.name = e.fileName
            e.url = e.filePath
          })
        } else {
          data.competitionAnnexList = []
        }
        this.form = data
        this.$nextTick(() => {
          this.updateTime = 0
        })
      }).catch(err => { })
    },
    // 获取活动分类
    async getClassification () {
      const { page } = await this.$post(this.api.listComClass)
      this.classifications = page
    },
    // 显示所属分类弹框
    setClass () {
      this.classVisible = true
    },
    // 新增所属分类
    addClass () {
      this.classifications.push({
        edit: true,
        id: '',
        classificationName: ''
      })
    },
    // 编辑所属分类
    editClass (row) {
      this.$set(row, 'edit', 1)
    },
    // 删除所属分类
    delClass (row, i) {
      if (row.id) {
        this.$confirm('确定要删除吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.$post(this.api.delComClass, [row.id]).then(res => {
            Util.successMsg('删除成功')
            this.getClassification()
          }).catch(res => { })
        }).catch(() => { })
      } else {
        this.classifications.splice(i, 1)
      }
    },
    // 提交所属分类
    submitClass (row, showMsg = 1) {
      if (!row.classificationName) return Util.errorMsg('请输入分类名称')
      this.$post(this.api[row.id ? 'updateComClass' : 'saveComClass'], {
        classificationName: row.classificationName,
        id: row.id,
      }).then(res => {
        showMsg && Util.successMsg((row.id ? '修改' : '新增') + '成功')
        this.getClassification()
      }).catch(res => { })
    },
    // 关闭所属分类
    closeClass () {
      const list = this.classifications
      if (list.find(e => e.edit && e.classificationName)) {
        this.$confirm('所填写内容暂未保存，是否保存？', '提示', {
          type: 'warning'
        }).then(() => {
          list.map(e => {
            e.edit && e.classificationName && this.submitClass(e, 0)
          })
          this.classVisible = false
        }).catch(() => {
          this.classVisible = false
        })
      } else {
        this.classVisible = false
      }
    },


    handleExceed (files, fileList) {
      Util.warningMsg(`当前限制选择 1 个文件，如需更换，请删除上一个文件再重新选择！`);
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleRemove () {
      Oss.del(this.form.coverUrl)
      this.form.coverUrl = ''
    },
    uploadError (err, file, fileList) {
      this.$message({
        message: "上传出错，请重试！",
        type: "error",
        center: true
      })
    },
    // 封面自定义上传
    async handleRequest ({ file }) {
      this.form.coverUrl && Oss.del(this.form.coverUrl)
      Oss.upload(file).then(res => {
        this.form.coverUrl = res.url
      })
    },
    // 附件上传成功
    uploadAnnexSuccess (file) {
      const url = file.url
      const data = {
        competitionId: this.form.id || '',
        fileName: file.name,
        name: file.name,
        filePath: url,
        url
      }
      this.form.competitionAnnexList.push(data)
    },
    handleExceedAnnex (files, fileList) {
      Util.warningMsg(`当前限制选择 5 个文件，如需更换，请删除一个文件再重新选择！`);
    },
    // 附件上传前
    beforeUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) Util.warningMsg('请上传小于10MB的附件！')
      if (isLt2M) {
        this.fileName = file.name
        return true
      } else {
        return false
      }
    },
    handleAnnexRemove (file, fileList) {
      Oss.del(file.url)
      this.form.competitionAnnexList = fileList
    },
    // 随机邀请码
    randomInv () {
      let result = ''
      for (let i = 0; i < 4; i++) {
        result += Math.floor(Math.random() * 10);
      }
      this.form.invitationCode = result
    },
    // 提交
    save (status) {
      const { form } = this
      if (!form.name) return Util.warningMsg("请填写活动名称");
      // 发布需要校验
      if (status) {
        if (!this.sponsorList.length) return Util.warningMsg("请填写主办方");
        if (!form.signUpStartTime) return Util.warningMsg("请选择报名时间");
        let now = new Date().getTime();
        let signUpStartTime = new Date(form.signUpStartTime).getTime();
        let signUpEndTime = new Date(form.signUpEndTime).getTime();
        let playStartTime = new Date(form.playStartTime).getTime();
        // if (signUpStartTime && now > signUpStartTime) return Util.warningMsg("报名时间不能早于当前时间");
        if (!form.playStartTime) return Util.warningMsg("请选择举办时间");
        if (playStartTime && signUpEndTime && playStartTime < signUpEndTime) return Util.warningMsg("举办时间不能早于报名结束时间");
        if (form.isNeedCode && (!form.invitationCode || form.invitationCode.length !== 4)) return Util.warningMsg('请填写四位数邀请码')
        if (!form.competitionScope && !this.competitionScope.length) return Util.warningMsg('请选择指定范围')
        if (!form.quantityLimit) return Util.warningMsg('请填写报名人数上限')
        if (!form.description) return Util.warningMsg("请填写活动详情");
      }
      form.publishStatus = status
      if (!form.competitionScope) {
        form.competitionScope = this.competitionScope.join(',')
      }
      form.sponsor = this.sponsorList.filter(d => d).join();
      form.undertaker = this.undertakerList.filter(d => d).join();
      form.id = this.$route.query.id
      if (this.submiting) return false
      this.submiting = true
      if (form.id) {
        this.$post(this.api.editCompetition, form).then(res => {
          this.backList()
          Util.successMsg("修改成功");
        }).catch(err => {
          this.submiting = false
        });
      } else {
        this.$post(this.api.addCompetition, form).then(res => {
          this.backList()
          Util.successMsg("创建成功");
        }).catch(err => {
          this.submiting = false
        });
      }
    },
    // 预览
    preview () {
      Util.local.set('activity', this.form)
      window.open(this.$router.resolve('preview').href)
    },
    addSponsor () {
      this.sponsorList.push("");
    },
    delSponsor (index) {
      this.sponsorList.splice(index, 1);
    },
    addOrganizer () {
      this.undertakerList.push("");
    },
    delOrganizer (index) {
      this.undertakerList.splice(index, 1);
    },
    backList () {
      this.pass = true
      this.updateTime = 0
      this.$router.back()
    },
    back () {
      this.pass = true
      // 更改了信息才需要提示
      if (this.updateTime) {
        this.$confirm(`编辑的内容未保存，是否保存？`, '提示', {
          type: 'warning'
        }).then(() => {
          this.save(this.form.publishStatus)
        }).catch(() => {
          this.backList()
        })
      } else {
        this.backList()
      }
    },
  }
};
</script>

<style scoped lang="scss">
$upload-width: 220px;
$upload-height: 140px;
$upload-lg-height: 150px;
/deep/ .avatar-uploader {
    .el-upload {
        position: relative;
        width: $upload-width;
        height: $upload-height;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        overflow: hidden;

        &:hover {
            border-color: #cb221c;
        }

        .uploader-default {
            display: flex;
            height: $upload-height;
            flex-direction: column;
            justify-content: center;
            text-align: center;
            background: rgba(0, 0, 0, 0.04);

            i {
                font-size: 20px;
                font-weight: bold;
                color: #8c939d;
            }

            p {
                margin-top: 10px;
                font-size: 14px;
                color: rgba(0, 0, 0, 0.65);
                line-height: 1;
            }
        }
    }

    &.avatar-uploader-lg {
        .el-upload {
            width: 100%;
            max-width: 960px;
            height: $upload-lg-height;

            .uploader-default {
                height: $upload-lg-height;
            }
        }
    }

    .avatar {
        display: block;
        width: $upload-width;
        height: $upload-height;
    }

    .avatar-lg {
        display: block;
        width: 100%;
        height: $upload-lg-height;
    }

    .el-upload__tip {
        margin-top: 0;

        p {
            font-size: 14px;
            color: rgba(0, 0, 0, 0.45);
            line-height: 1;

            &:first-child {
                margin-bottom: 5px;
            }
        }
    }
}

/deep/ .d-inline-block {
    width: 216px;

    .el-select,
    .el-input {
        width: 100%;
    }
}
.inline-input {
    .input-wrap {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        .el-input {
            display: inline-block;
            width: 216px;
            margin-right: 8px;
        }

        .remove {
            width: 16px;
            height: 16px;
            background: url('../../../assets/images/close.png') 0 0 / cover no-repeat;
            cursor: pointer;
        }
    }

    .add-btn {
        margin-left: 32px;
    }
}

.plus {
    margin-bottom: 10px;
    font-size: 18px;
    color: #2962ff;
    text-align: right;
    cursor: pointer;
}
.set-btn {
    margin-left: 10px !important;
}
.manage-dia {
    .edit,
    .del {
        font-size: 14px;
        cursor: pointer;
    }
    .edit {
        margin-right: 10px;
    }
}
.add-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 216px;
    line-height: 32px;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.65);
    background-color: transparent;
    border: 1px dashed rgba(0, 0, 0, 0.15);
    border-radius: 4px;
    cursor: pointer;

    i {
        margin-right: 8px;
        font-size: 14px;
        font-weight: bold;
    }
}
.range-check {
    display: inline-block;
    margin: 0 0 10px 10px;
}
/deep/.range-cas {
    .el-tag {
        display: none;
    }
}
.input-center {
    display: flex;
    align-items: center;
    width: 216px;
    white-space: nowrap;
    .el-input {
        margin-right: 5px;
    }
}
.el-steps {
    justify-content: center;
}
/deep/.req {
    .el-form-item__label {
        &:before {
            content: '*';
            margin-right: 5px;
            font-size: 18px;
            vertical-align: middle;
            color: #f00;
        }
    }
}
</style>