<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 v-if="hasPer">
          <div v-if="step === 1 || (id && !editing)" :class="['type-wrap', {pd: !id}]">
            <div class="p-title">大赛发布类型</div>
            <el-form label-width="100px" label-suffix=":" size="small" :disabled="!editing && id != ''">
              <el-form-item label="请选择类型">
                <el-radio v-for="(item, i) in releaseTypes" :key="i" v-model="releaseType" :label="item.id">{{ item.name }}</el-radio>
              </el-form-item>
            </el-form>
            <el-button v-if="!editing && id" class="edit" type="primary" @click="editing = 1" v-auth="'/match/list:管理:大赛详情:编辑'">编辑</el-button>
          </div>
          <el-card v-if="step !== 4" shadow="hover" class="m-b-20" style="position: relative;margin-top: 20px">
            <ul :class="['steps', {pointer: !editing && id}]">
              <li :class="{active: step === 1,done: step > 1}" @click="toStep(1)">
                <span class="circle">1</span>
                <p class="text">大赛信息填写</p>
              </li>
              <template v-if="releaseType">
                <li :class="{active: step === 2,done: step > 2}" @click="toStep(2)">
                  <span class="circle circle2">2</span>
                  <p class="text">赛程与规则设置</p>
                </li>
                <li :class="{active: step === 3,done: step > 3}" @click="toStep(3)">
                  <span class="circle circle3">3</span>
                  <p class="text">比赛内容设置</p>
                </li>
              </template>
              <li :class="{done: step > 3}">
                <span class="circle circle4">{{ releaseType ? 4 : 2 }}</span>
                <p class="text">发布{{ !editing && id ? '成功' : '' }}</p>
              </li>
            </ul>
          </el-card>
        </div>
        <el-button v-else-if="!editing && id" class="edit" type="primary" @click="editing = 1" v-auth="'/match/list:管理:大赛详情:编辑'">编辑</el-button>
        <div class="page">
          <div class="page-content">
            <step1 v-show="step === 1" ref="step1" :editing.sync="editing" @next="next" />
            <step2 v-if="step === 2" ref="step2" :editing.sync="editing" :setupId.sync="setupId" @next="next" />
            <step3 v-if="step === 3" ref="step3" :editing.sync="editing" :setupId.sync="setupId" :competitionId.sync="competitionId" @next="next" />
            <step4 v-if="step === 4" />

            <div v-if="step !== 4 && showBtns" class="btns">
              <!-- 处于编辑状态(列表点编辑按钮进来默认是查看状态，不可编辑，点了编辑按钮才可编辑)，或者新增，才显示这几个按钮 -->
              <div v-if="editing || !id" class="m-r-10">
                <el-button v-if="!publishStatus" @click="save(0)">保存{{ releaseType ? '草稿' : '' }}</el-button>
                <el-button v-if="step === 2 || step === 3" type="primary" @click="prev">上一步</el-button>
                <el-button v-if="releaseType == 0" type="primary" @click="save(1)">发布</el-button>
                <el-button v-else type="primary" @click="save(id ? 1 : 0, 2)">保存并下一步</el-button>
              </div>
              <el-button type="danger" @click="preview" v-auth="'/match/list:管理:大赛详情:预览'">预览</el-button>
              <el-button @click="cancel">{{ editing ? '取消' : '返回' }}</el-button>
            </div>
          </div>
        </div>
    </div>
</template>

<script>
import util from "@/libs/util";
import quill from "@/components/quill";
import step1 from './step1'
import step2 from './step2'
import step3 from './step3'
import step4 from './step4'
import { Loading } from 'element-ui'
export default {
    name: "add",
    data() {
        return {
            id: this.$route.query.id || '',
            cache: this.$store.state.match.cache,
            hasPer: false,
            releaseTypes: [
              {
                id: 0,
                name: '仅发布信息'
              },
              {
                id: 1,
                name: '设置完整比赛'
              }
            ],
            publishStatus: 0,
            competitionId: this.$route.query.id || '',
            step: 1,
            submiting: false,
            updateTime: 0,
            setupId: '',
            releaseType: 0,
            editing: this.$route.query.id ? 0 : 1,
            showBtns: true,
            loadIns: null
        };
    },
    components: {
      quill,
      step1,
      step2,
      step3,
      step4
    },
    // 离开的时候判断是否有保存更改的信息,没有则拦截并提示
    beforeRouteLeave(to, from, next) {
      const { updateTime } = this.$refs['step' + this.step]
        if(updateTime){
            this.$confirm(`您所更改的内容未更新，是否更新？`, '提示', {
                type: 'warning'
            }).then(() => {
                this.save(this.step,to.path,next)
            }).catch(() => {
                next()
            })
        }else{
            next()
        }
    },
    mounted() {
      this.getPer()
    },
    methods: {
      // 如果是从第三步里的自定义项目入口进去后返回的，则要直接进入第三步
      resumeData() {
        if (this.cache) {
          this.step = 3
          this.editing = true
          this.showBtns = false
        }
      },
      // 查询客户增值模块（如果返回了true，则显示设置完整比赛选项）
      getPer() {
        this.$get(this.api.getCustomerOrder).then(({ show }) => {
          this.hasPer = show
          show || this.$parent.hideArch()
        }).catch(err => {})
      },
      // 展示loading
      showLoad() {
        this.loadIns = Loading.service()
      },
      // 隐藏loading
      hideLoad() {
        this.loadIns.close()
      },
      // 提交
      save(status, next = 0,cb) {
        console.log('status=>',status)
        console.log('cb=>',cb)
        console.log('this.step=>',this.step)
        this.$refs['step' + this.step].save(status, next, this.releaseType,cb)
      },
      // 上一步
      prev() {
        // 更改了信息才需要提示
        const { updateTime } = this.$refs['step' + this.step]
        if (updateTime) {
          this.$confirm(`编辑的内容未保存，是否保存？`, '提示', {
            type: 'warning'
          }).then(() => {
            this.save(0, 1)
          }).catch(() => {
            this.step--
          })
        } else {
          this.step--
        }
      },
      // 发布后的逻辑
      next(next, setupId, competitionId,type) {
        console.log('next==>',next)
        console.log('setupId==>',setupId)
        console.log('competitionId==>',competitionId)
        if (!next) {
          this.$router.push(`/match?page=${this.$store.state.matchPage}`)
        } else if (next === 2) {
          if (setupId) this.setupId = setupId
          if (competitionId) {
            this.$router.push('add?id=' + competitionId)
            this.id = competitionId
            this.competitionId = competitionId
          }
          this.step++
        } else if (next === 1) {
          this.step--
        } else  {
          console.log(99999999)
          if(typeof setupId === 'function') {
            setupId()
          }else if(typeof type === 'function') {
            type()
          }
        }
      },
      // 点击步骤条跳转
      toStep(i) {
        if (this.id && !this.editing) this.step = i
      },
      // 预览
      preview() {
        util.local.set('match', this.$refs.step1.form)
        window.open(this.$router.resolve('/match/preview').href)
      },
      // 取消
      cancel() {
        // 当前是编辑赛事，并且表单处于编辑状态，则返回到查看状态；查看状态，则返回到列表
        if (this.editing && this.$route.query.name) {
          // 更改了信息才需要提示
          const { updateTime } = this.$refs['step' + this.step]
          if (this.step < 4 && updateTime) {
            this.$confirm(`编辑的内容未保存，是否保存？`, '提示', {
              type: 'warning'
            }).then(() => {
              this.save(0, 3)
            }).catch(() => {
              this.editing = false
            })
          } else {
            this.editing = false
          }
        } else {
          this.$router.push(`/match?page=${this.$store.state.match.page}`)
        }
      },
      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(`/match?page=${this.$store.state.match.page}`)
      }
    }
};
</script>

<style scoped lang="scss">
.type-wrap {
  position: relative;
  margin-top: 20px;
  background: #fff;
  &.pd {
    padding: 15px;
  }
}
.edit {
  position: absolute;
  top: 30px;
  right: 30px;
}
.el-steps {
  justify-content: center;
}
.steps {
  display: flex;
  justify-content: center;
  &.pointer {
    li {
      cursor: pointer;
    }
  }
  li {
    position: relative;
    margin-right: 100px;
    text-align: center;
  }
  .circle {
    display: inline-flex;
    justify-content: center;
    align-items: center;
    width: 45px;
    margin: 0 auto 10px;
    line-height: 35px;
    font-size: 18px;
    color: #333;
    background: #f9f9f9;
    border: 5px solid #e1e1e1;
    border-radius: 50%;
    &:after {
      content: '';
      position: absolute;
      left: 64px;
      width: 146px;
      height: 3px;
      background: #e1e1e1;
    }
  }
  .active {
    .circle {
      color: #fff;
      border-color: #459ffb;
      background: #007EFF;
    }
    .text {
      color: #007EFF;
    }
  }
  .done {
    .circle {
      color: #fff;
      background: #9c86ff;
      border-color: #bbacff;
      &:after {
        background: #bbacff;
      }
    }
    .text {
      color: #9178ff;
    }
  }
  .circle2:after {
    left: 71px;
    width: 147px;
  }
  .circle4:after {
    display: none;
  }
}
.btns {
  display: flex;
  justify-content: center;
  text-align: center;
}
</style>