<template>
    <div>
        <el-card shadow="hover" class="m-b-20">
            <div class="flex-between">
                <el-page-header @back="back" :content="'创建赛事'"></el-page-header>
            </div>
        </el-card>
        <el-card shadow="hover" class="m-b-20">
            <el-form label-width="170px" label-suffix=":" size="small">
                <el-form-item label="竞赛封面（选填）">
                    <el-upload
                        class="avatar-uploader"
                        accept=".jpg,.png,.jpeg,.gif"
                        :on-remove="handleRemove"
                        :on-error="uploadError"
                        :on-success="uploadSuccess"
                        :before-remove="beforeRemove"
                        :limit="1"
                        :on-exceed="handleExceed"
                        :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-remove="handleLgRemove"
                        :on-error="uploadError"
                        :on-success="uploadLgSuccess"
                        :before-remove="beforeRemove"
                        :limit="1" :on-exceed="handleExceed"
                        :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 label="比赛范围">
                  <div>
                    <el-radio v-model="form.competitionScope" :label="0">本校内</el-radio>
                  </div>
                  <div>
                    <el-radio v-model="form.competitionScope" :label="1">全平台</el-radio>
                  </div>
                  <div>
                    <el-radio v-model="form.competitionScope" :label="2">指定区域、院校</el-radio>
                    <el-button v-if="form.competitionScope === 2" type="primary" size="mini" @click="showRange">选择院校</el-button>
                    <span style="margin-left: 20px">{{ rangeName }}</span>
                  </div>
                </el-form-item>
                <el-form-item label="竞赛名称">
                    <div class="d-inline-block">
                        <el-input placeholder="请输入竞赛名称" v-model="form.name" clearable></el-input>
                    </div>
                </el-form-item>
                <el-form-item 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" @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" @click="addOrganizer">
                                <i class="el-icon-plus"></i>
                                <span>添加</span>
                            </button>
                        </div>
                    </div>
                    <button v-if="!undertakerList.length" class="add-btn" @click="addOrganizer">
                        <i class="el-icon-plus"></i>
                        <span>添加</span>
                    </button>
                </el-form-item>
                <el-form-item 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 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 label="竞赛详情">
                    <quill :border="true" v-model="form.description" :height="400" />
                </el-form-item>
                <el-form-item label="附件">
                  <el-upload
                      :on-remove="handleAnnexRemove"
                      :on-error="uploadError"
                      :before-upload="beforeUpload"
                      :on-success="uploadAnnexSuccess"
                      :limit="5"
                      :on-exceed="handleExceedAnnex"
                      :action="this.api.fileupload"
                      :headers="headers"
                      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-item>
                    <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-form-item>
            </el-form>
        </el-card>

        <el-dialog title="请勾选院校" :visible.sync="rangeVisible" width="580px" custom-class="range-dia" :close-on-click-modal="false">
          <el-cascader
            ref="range"
            v-model="range"
            :options="ranges"
            :props="props"
            clearable
            filterable></el-cascader>
          <span slot="footer" class="dialog-footer">
            <el-button size="small" @click="rangeVisible = false">取 消</el-button>
            <el-button size="small" type="primary" @click="rangeSubmit">确 定</el-button>
          </span>
        </el-dialog>

        <el-dialog title="预览" :visible.sync="previewVisible" width="1080px" custom-class="preview-dia" :close-on-click-modal="false">
          <div class="match">
            <div class="info">
              <h6 class="title">{{ form.name }}</h6>
              <div class="meta">最近编辑时间：{{ form.updateTime }}</div>
            </div>

            <div class="l-title" id="part1"><img src="@/assets/img/label.png" alt=""> 竞赛信息</div>
            <div v-if="form.description" class="texts ql-editor" v-html="form.description"></div>
            <template v-if="form.contestAnnexList">
              <h6 class="p-title">附件下载</h6>
              <ul class="files">
                <li v-for="(item, i) in form.contestAnnexList" :key="i">
                  <el-link class="file-name" type="primary" @click="previewFile(item)">{{ item.fileName }}</el-link>
                  <el-link type="primary" :underline="false" @click="download(item)">下载</el-link>
                </li>
              </ul>
            </template>
          </div>
        </el-dialog>
    </div>
</template>

<script>
import util from "@/libs/util";
import quill from "@/components/quill";
import Setting from "@/setting";

export default {
    name: "add",
    data() {
        const that = this
        return {
            headers: {
                token: util.local.get(Setting.tokenKey)
            },
            fileName: '',
            form: {
              id: '',
              platformSource: 1, // 平台来源(0:中台，1：职站)
              ztOpen: 0, // 中台是否开启(0开启 1未开启 默认0)
              name: '',
              sponsor: '',
              undertaker: '',
              competitionScope: 0, // 大赛范围(0:本校内 1:全平台 2:指定区域、院校)
              contestRangeList: [], // 大赛范围选择
              contestAnnexList: [], // 赛事附件
              coverUrl: '',
              carouselUrl: '',
              publishStatus: 0,
              signUpStartTime: '',
              signUpEndTime: '',
              playStartTime: '',
              playEndTime: '',
              description: '',
            },
            signupTime: '',
            playTime: '',
            sponsorList: [""],
            undertakerList: [""],
            pickerOptions: {
                disabledDate: time => {
                    return time.getTime() < new Date().getTime() - 86400000;
                }
            },
            provinceList: this.$store.state.provinceList,
            rangeVisible: false,
            range: [],
            ranges: [],
            rangeName: '',
            // 选择区域懒加载
            props: {
              multiple: true,
              checkStrictly: true,
              lazy: true,
              lazyLoad (node, resolve) {
                const { level, value } = node
                // 省份
                if (!level) {
                  that.$get(that.api.queryProvince).then(({ list }) => {
                    const data = []
                    list.map(e => {
                      data.push({
                        value: e.provinceId,
                        label: e.provinceName
                      })
                    })
                    resolve(data)
                  }).catch(res => {})
                } else if (level === 1) {
                  // 城市
                  that.$get(that.api.queryCity, {
                    provinceId: value
                  }).then(({ list }) => {
                    const data = []
                    list.map(e => {
                      data.push({
                        provinceId: value,
                        value: e.cityId,
                        label: e.cityName
                      })
                    })
                    resolve(data)
                  }).catch(res => {})
                } else if (level === 2) {
                  // 学校
                  that.$get(that.api.getSchoolsByProvince, {
                    provinceId: node.data.provinceId,
                    cityId: value,
                    schoolName: ''
                  }).then(({ list }) => {
                    const data = []
                    list.map(e => {
                      data.push({
                        value: e.schoolId,
                        label: e.schoolName,
                        leaf: true
                      })
                    })
                    resolve(data)
                  }).catch(res => {})
                } else {
                  resolve([])
                }
              }
            },
            submiting: false,
            updateTime: 0,
            previewVisible: false
        };
    },
    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() {
      
    },
    methods: {
      // 选择范围
      showRange() {
        this.rangeVisible = true
      },
      // 范围确定
      rangeSubmit() {
        // 处理提交需要的id
        const data = []
        this.range.map(e => {
          data.push({
            provinceId: e[0] || '',
            cityId: e[1] || '',
            schoolId: e[2] || '',
            type: e.length > 2 ? 0 : 1
          })
        })
        this.form.contestRangeList = data

        // 处理显示的name
        const checked = this.$refs.range.getCheckedNodes()
        const name = []
        checked.map(e => {
          name.push(e.label)
        })
        this.rangeName = name.join('、')

        this.rangeVisible = false
      },
      handleExceed(files, fileList) {
          util.warningMsg(`当前限制选择 1 个文件，如需更换，请删除上一个文件再重新选择！`);
      },
      handleExceedAnnex(files, fileList) {
          util.warningMsg(`当前限制选择 5 个文件，如需更换，请删除一个文件再重新选择！`);
      },
      uploadSuccess(res) {
        const { coverUrl } = this.form
        coverUrl && this.$del(`${this.api.fileDeletion}?keys=${coverUrl}`).then(res => {}).catch(res => {})
        this.form.coverUrl = res.data.filesResult.fileUrl
      },
      uploadLgSuccess(res) {
        const { carouselUrl } = this.form
        carouselUrl && this.$del(`${this.api.fileDeletion}?keys=${carouselUrl}`).then(res => {}).catch(res => {})
        this.form.carouselUrl = res.data.filesResult.fileUrl
      },
      // 附件上传成功
      uploadAnnexSuccess(res) {
        const file = res.data.filesResult
        this.form.contestAnnexList.push({
          fileName: this.fileName,
          filePath: file.fileUrl || file.fileId
        })
      },
      // 附件上传前
      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
        }
      },
      uploadError(err, file, fileList) {
        this.$message({
          message: "上传出错，请重试！",
          type: "error",
          center: true
        })
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      handleRemove(file, fileList) {
        this.$del(`${this.api.fileDeletion}?keys=${this.form.coverUrl}`).then(res => {
          this.form.coverUrl = ''
        }).catch(res => {})
      },
      handleLgRemove(file, fileList) {
        this.$del(`${this.api.fileDeletion}?keys=${this.form.carouselUrl}`).then(res => {
          this.form.carouselUrl = ''
        }).catch(res => {})
      },
      handleAnnexRemove(file, fileList) {
        debugger
        this.$del(`${this.api.fileDeletion}?keys=${this.coverUrl}`).then(res => {
          this.carouselUrl = ''
        }).catch(res => {})
      },
      // 预览
      preview() {
        this.previewVisible = true
      },
      // 预览附件
      previewFile(item) {
        const { filePath } = item
        const suffix = filePath.substr(filePath.lastIndexOf('.') + 1)
        window.open((util.isDoc(suffix) || suffix === 'pdf' ? 'https://view.officeapps.live.com/op/view.aspx?src=' : '') + item.filePath)
      },
      // 下载附件
      download(item) {
        util.downloadFile(item.fileName, item.filePath)
      },
      // 提交
      save(status) {
          if (this.submiting) return false;
          const { form } = this
          form.sponsor = this.sponsorList.filter(d => d).join();
          form.undertaker = this.undertakerList.filter(d => d).join();
          if (form.competitionScope == 2 && !form.contestRangeList.length) return util.warningMsg('请选择区域、院校')
          if (!form.name) return util.warningMsg("请填写竞赛名称");
          if (status == 1) {
              if (!form.sponsor) 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 && status == 1) return util.warningMsg("请选择竞赛时间");
          if (playStartTime && playStartTime < signUpEndTime) return util.warningMsg("竞赛时间不能早于报名结束时间");
          if (!form.description && status == 1) return util.warningMsg("请填写竞赛详情");

          this.submiting = true
          form.publishStatus = status
          if (this.form.id) {
              this.$put(this.api.editContest, form).then(res => {
                  this.submiting = false;
                  util.successMsg("修改成功");
                  this.$router.back();
              })
                  .catch(err => {
                      this.submiting = false;
                  });
          } else {
              this.$post(this.api.addContest, form).then(res => {
                  this.submiting = false;
                  util.successMsg("创建成功");
                  this.$router.back();
              })
                  .catch(err => {
                      this.submiting = false;
                  });
          }
      },
      back() {
        const updateTime = this.updateTime
        // 更改了信息才需要提示
        if (updateTime) {
          this.$confirm(`编辑的内容未保存，是否保存？`, '提示', {
            type: 'warning'
          }).then(() => {
            this.save(0)
          }).catch(() => {
            this.backPage()
          })
        } else {
          this.backPage()
        }
      },
      backPage(){
        this.$router.back()
      },
      addSponsor() {
          this.sponsorList.push("");
      },
      delSponsor(index) {
          this.sponsorList.splice(index, 1);
      },
      addOrganizer() {
          this.undertakerList.push("");
      },
      delOrganizer(index) {
          this.undertakerList.splice(index, 1);
      }
    }
};
</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;
    }
}
.match {
  .l-title{
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    font-size: 14px;
    color: #333;
    img{
      margin-right: 5px;
    }
  }
  .title{
      width: 67%;
      margin: 0 auto;
      font-size: 28px;
      text-align: center;
      color: #0B1D30;
  }
  .info .meta{
      padding: 16px 0;
      font-size: 12px;
      color: #999;
      text-align: center;
  }
  .texts {
    margin-bottom: 30px;
  }
  .files {
    li {
      display: flex;
      align-items: center;
      margin: 10px 0;
    }
    .file-name {
      margin-right: 10px;
    }
  }
}
</style>