<template>
    <div>
        <el-card v-if="!id" shadow="hover" class="m-b-20">
            <div class="flex-between">
                <el-page-header @back="back" :content="'创建项目'"></el-page-header>
            </div>
        </el-card>
        <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"
                        :on-success="uploadSuccess"
                        :limit="1"
                        :action="this.api.fileupload"
                        :headers="headers"
                        name="file"
                    >
                        <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"
                        :on-success="uploadLgSuccess"
                        :limit="1"
                        :action="this.api.fileupload"
                        :headers="headers"
                        name="file"
                    >
                        <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="附件">
                  <el-upload
                      :before-upload="beforeUpload"
                      :on-success="uploadAnnexSuccess"
                      :limit="5"
                      :action="this.api.fileupload"
                      :headers="headers"
                      :file-list="fileList"
                      name="file"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">
                      <p>支持扩展名：.rar .zip .doc .docx .pdf .jpg...</p>
                    </div>
                  </el-upload>
                </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" v-auth="'/activity/list:管理:大赛详情:预览'">预览</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";
export default {
    data() {
        return {
            id: this.$route.query.id || '',
            headers: {
                token: util.local.get(Setting.tokenKey)
            },
            scope: 0,
            form: {
              id: this.$route.query.id || '',
              founder: 1,
              isOpen: 0, // 职站是否开启(0开启 1未开启 默认0)
              maximumNumber: '',
              carouselUrl: '',
              coverUrl: '',
              activityFileList: [], // 赛事附件
              initiator: '',
              isNeedCode: 0,
              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,
            updateTime: 0,
        };
    },
    components: {
      quill,
    },
    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 = ''
          }
        }
    },
    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) {
            const files = []
            fileList.map(e => {
              files.push({
                name: e.fileName,
                url: e.filePath
              })
            })
            this.fileList = files
          } else {
            data.activityFileList = []
          }

          this.form = data
          this.$nextTick(() => {
            this.updateTime = 0
          })
        }).catch(err => {})
      },
      uploadSuccess(res) {
        this.form.coverUrl = res.data.filesResult.fileUrl
      },
      uploadLgSuccess(res) {
        this.form.carouselUrl = res.data.filesResult.fileUrl
      },
      // 附件上传成功
      uploadAnnexSuccess(res) {
        const file = res.data.filesResult
        const { id } = this.form
        const data = {
          activityId: id || '',
          fileName: this.fileName,
          filePath: file.fileUrl || file.fileId
        }
        this.form.activityFileList.push(data)
      },
      // 附件上传前
      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) {
        
      },
      // 随机邀请码
      randomInv() {
        let result = ''
        for (let i = 0; i < 4; i++) {
          result += Math.floor(Math.random() * 10);
        }
        this.form.completeCompetitionSetup.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 (form.id) {
              this.$post(this.api.updateActivity, form).then(res => {
                  this.updateTime = 0
                  this.$router.back()
                  util.successMsg("修改成功");
              }).catch(err => {});
          } else {
              this.$post(this.api.saveActivity, form).then(res => {
                  this.updateTime = 0
                  this.$router.back()
                  util.successMsg("创建成功");
              }).catch(err => {});
          }
      },
      // 预览
      preview() {
        util.local.set('activity', this.form)
        window.open(this.$router.resolve('/matchPreview').href)
      },
      addSponsor() {
          this.sponsorList.push("");
      },
      delSponsor(index) {
          this.sponsorList.splice(index, 1);
      },
      back() {
        // 更改了信息才需要提示
        const { updateTime } = this.$refs['step' + this.step]
        console.log("🚀 ~ file: index.vue:142 ~ back ~ updateTime", updateTime)
        if (this.step < 4 && updateTime) {
          this.$confirm(`编辑的内容未保存，是否保存？`, '提示', {
            type: 'warning'
          }).then(() => {
            this.save(0)
          }).catch(() => {
            this.backPage()
          })
        } else {
          this.backPage()
        }
      },
      backPage() {
        this.$router.push(`/activity?page=${this.$store.state.activity.page}`)
      }
    }
};
</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>