<template>
  <div>
    <breadcrumb v-if="!id"
                :routes.sync="routes" />
    <div class="page">
      <div class="page-content">
        <el-form label-width="170px"
                 label-suffix=":"
                 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 label="项目封面长图（选填）">
            <el-upload class="avatar-uploader avatar-uploader-lg"
                       accept=".jpg,.png,.jpeg,.gif"
                       :limit="1"
                       :on-exceed="handleExceed"
                       :before-remove="beforeRemove"
                       :on-remove="handleCarouselRemove"
                       :on-error="uploadError"
                       action=""
                       :http-request="handleRequestLg">
              <img v-if="form.carouselUrl"
                   :src="form.carouselUrl"
                   class="avatar-lg">
              <div class="uploader-default"
                   v-else>
                <i class="el-icon-plus"></i>
                <p>上传封面</p>
              </div>
              <div slot="tip"
                   class="el-upload__tip">
                <p>展示宽度为1920，高度300，JPG/PNG/GIF，3MB以内</p>
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item class="req"
                        label="项目名称">
            <div class="d-inline-block">
              <el-input placeholder="请输入项目名称"
                        v-model="form.projectName"
                        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 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="发布范围">
            <div>
              <el-radio v-model="scope"
                        :label="0"
                        disabled>本校内</el-radio>
            </div>
          </el-form-item>
          <el-form-item class="req"
                        label="报名人数上限">
            <div class="input-center">
              <el-input placeholder="请输入人数"
                        v-model.number="form.maximumNumber"
                        type="number"></el-input> 人
            </div>
          </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位邀请码或点击随机生成"
                        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="项目详情">
            <quill ref="quill"
                   :border="true"
                   v-model="form.projectDescribe"
                   :height="400" />
          </el-form-item>
          <el-form-item label="附件">
            <Upload :limit="5"
                    :file-list.sync="form.activityFileList"
                    :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>
      </div>
    </div>
  </div>
</template>

<script>
import util from "@/libs/util";
import quill from "@/components/quill";
import Setting from "@/setting";
import Upload from '@/components/upload';
import Oss from '@/components/upload/upload.js'
import breadcrumb from '@/components/breadcrumb'
export default {
  data () {
    return {
      routes: [
        {
          name: '我的项目',
          path: this.$store.state.activity.mgReferrer
        },
        {
          name: '创建项目'
        },
      ],
      id: this.$route.query.id || '',
      headers: {
        token: util.local.get(Setting.tokenKey)
      },
      scope: 0,
      form: {
        id: this.$route.query.id || '',
        founder: 2,
        isOpen: 0, // 职站是否开启(0开启 1未开启 默认0)
        maximumNumber: '',
        carouselUrl: '',
        coverUrl: '',
        activityFileList: [], // 赛事附件
        initiator: '',
        isNeedCode: 0,
        invitationCode: '',
        maximumNumber: 0,
        signUpStartTime: '',
        signUpEndTime: '',
        playStartTime: '',
        playEndTime: '',
        projectDescribe: '',
        projectName: '',
        publishStatus: 0,
      },
      pickerOptions: {
        disabledDate: time => {
          return this.$route.query.id ? false : time.getTime() < new Date().getTime() - 86400000;
        }
      },
      fileName: '',
      signupTime: [],
      playTime: [],
      sponsorList: [""],
      fileList: [],
      submiting: false,
      pass: false,
      updateTime: 0,
    };
  },
  components: {
    quill,
    Upload,
    breadcrumb,
  },
  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',
          closeOnClickModal: false
        }).then(() => {
          this.save(this.form.publishStatus)
        }).catch(() => {
          next()
        })
      } else {
        next()
      }
    } else {
      next()
    }
  },
  mounted () {
    this.getData()
  },
  methods: {
    getData () {
      const { id } = this.form
      id && this.$post(`${this.api.findByIdActivity}?id=${id}`).then(({ data }) => {
        if (data.signUpStartTime) this.signupTime = [data.signUpStartTime, data.signUpEndTime]
        if (data.playStartTime) this.playTime = [data.playStartTime, data.playEndTime]
        this.sponsorList = data.initiator.split(",")
        // 附件
        const fileList = data.activityFileList
        if (fileList) {
          fileList.map(e => {
            e.name = e.fileName
            e.url = e.filePath
          })
        } else {
          data.activityFileList = []
        }
        this.form = data
        this.$nextTick(() => {
          this.updateTime = 0
        })
      }).catch(err => { })
    },
    handleExceed (files, fileList) {
      util.warningMsg(`当前限制选择 1 个文件，如需更换，请删除上一个文件再重新选择！`);
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleRemove () {
      Oss.del(this.form.coverUrl)
      this.form.coverUrl = ''
    },
    handleCarouselRemove () {
      Oss.del(this.form.carouselUrl)
      this.form.carouselUrl = ''
    },
    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
      })
    },
    // 封面自定义上传
    async handleRequestLg ({ file }) {
      this.form.carouselUrl && Oss.del(this.form.carouselUrl)
      Oss.upload(file).then(res => {
        this.form.carouselUrl = res.url
      })
    },
    // 附件上传成功
    uploadAnnexSuccess (file) {
      const url = file.url
      const data = {
        activityId: this.form.id || '',
        fileName: file.name,
        name: file.name,
        filePath: url,
        url
      }
      this.form.activityFileList.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.activityFileList = 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
      form.initiator = this.sponsorList.filter(d => d).join();
      if (!form.projectName) return util.warningMsg("请填写项目名称");
      // 发布需要校验
      if (status) {
        if (!form.initiator) 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.projectDescribe) return util.warningMsg("请填写项目详情");
      }
      form.publishStatus = status
      form.id = this.$route.query.id
      if (this.submiting) return false
      this.submiting = true
      if (form.id) {
        this.$post(this.api.updateActivity, form).then(res => {
          this.backList()
          util.successMsg("修改成功");
        }).catch(err => {
          this.submiting = false
        });
      } else {
        this.$post(this.api.saveActivity, form).then(res => {
          this.backList()
          util.successMsg("创建成功");
        }).catch(err => {
          this.submiting = false
        });
      }
    },
    // 预览
    preview () {
      util.local.set('activity', this.form)
      window.open(this.$router.resolve('/activity/preview').href)
    },
    addSponsor () {
      this.sponsorList.push("");
    },
    delSponsor (index) {
      this.sponsorList.splice(index, 1);
    },
    backList () {
      this.pass = true
      this.updateTime = 0
      this.$router.back()
    },
    back () {
      this.pass = true
      // 更改了信息才需要提示
      if (this.updateTime) {
        this.$confirm(`编辑的内容未保存，是否保存？`, '提示', {
          type: 'warning',
          closeOnClickModal: false
        }).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/img/close.png') 0 0 / cover no-repeat;
            cursor: pointer;
        }
    }

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

.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;
        }
    }
}
.btns {
    display: flex;
    justify-content: center;
    text-align: center;
}
</style>