<template>
  <!-- 赛事报名-账号申请 -->
  <div>
    <el-dialog title="账号申请" :visible.sync="accountVisible" :close-on-click-modal="false" width="500px"
      @close="accountClose" @closed="closeDia">
      <el-form class="dia-form" ref="accountForm" label-width="110px" :model="accountForm" :rules="accountRules">
        <el-form-item prop="schoolId" label="所属院校">
          <el-select class="w-100" v-model="accountForm.schoolId" filterable placeholder="请选择院校" @change="schoolChange">
            <el-option v-for="(item, i) in schoolList" :key="i" :label="item.schoolName"
              :value="item.schoolId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="workNumber" label="学号">
          <el-input placeholder="申请后无法修改，请确认填写正确" v-model="accountForm.workNumber"
            @change="workNumberChange"></el-input>
        </el-form-item>
        <el-form-item prop="userName" label="姓名">
          <el-input placeholder="请输入姓名" v-model="accountForm.userName" :disabled="formEnable"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input placeholder="请输入手机号" maxlength="11" v-model.trim="accountForm.phone"
            :disabled="formEnable"></el-input>
        </el-form-item>
        <el-form-item prop="code" label="验证码">
          <div class="ver-code">
            <el-input v-model="accountForm.code" placeholder="请输入验证码" maxlength="6" :disabled="formEnable"></el-input>
            <el-button style="top: 1px" type="text" @click="sendCode" :disabled="phoneDisabled && formEnable">{{
              phoneBtnText }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item prop="password" label="登录密码">
          <el-input placeholder="请输入登录密码" type="password" maxlength="6" v-model="accountForm.password"
            :disabled="formEnable"></el-input>
        </el-form-item>
        <el-form-item prop="rePassword" label="确认登录密码">
          <el-input placeholder="请再次输入登录密码" type="password" maxlength="6" v-model="accountForm.rePassword"
            :disabled="formEnable"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="!formEnable" size="small" type="primary" @click="accountSubmit">申请</el-button>
        <el-button size="small" @click="accountVisible = false">取消</el-button>
      </span>
    </el-dialog>

    <!-- 购买弹框 -->
    <el-dialog title="温馨提示" :visible.sync="buyVisible" width="400px" center :close-on-click-modal="false">
      <div class="buy">
        <p class="tips">您所选择的院校暂未在本平台开通组织账号，请通知院校老师联系下方二维码客服咨询。</p>
        <img src="@/assets/img/wechat-code.jpeg" alt="">
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Setting from '@/setting'
import Util from '@/libs/util'
export default {
  props: ['visible'],
  data () {
    const workNumberPass = (rule, value, callback) => {
      const val = this.accountForm.workNumber
      if (val === '') {
        callback(new Error('请输入学号'))
      } else {
        const pattern = /^[A-Za-z0-9]*$/
        if (pattern.test(val)) {
          callback()
        } else {
          callback(new Error('请输入正确学号格式'))
        }
      }
    }
    const phonePass = (rule, value, callback) => {
      const val = this.accountForm.phone
      if (val === '') {
        callback(new Error('请输入手机号'))
      } else {
        if (this.phoneReg.test(val)) {
          callback()
        } else {
          callback(new Error('请输入正确手机号格式'))
        }
      }
    }
    return {
      accountVisible: false,
      formEnable: true,
      schoolList: [],
      accountForm: {
        schoolId: '',
        account: '',
        code: '',
        password: '',
        rePassword: '',
        phone: '',
        userName: '',
        workNumber: '',
        uniqueIdentification: Date.now()
      },
      accountRules: {
        schoolId: [{ required: true, message: "请选择所属院校", trigger: "change" }],
        userName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        workNumber: [{ required: true, validator: workNumberPass, trigger: "blur" }],
        phone: [{ required: true, validator: phonePass, trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        rePassword: [{ required: true, message: "请再次输入密码", trigger: "blur" }],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      },
      phoneDisabled: false,
      phoneTimer: null,
      phoneOpener: '',
      phoneBtnText: '发送验证码',
      buyVisible: false,
      submiting: false,
    };
  },
  watch: {
    visible () {
      this.accountVisible = this.visible
    }
  },
  mounted () {
    this.$store.state.match.toMatch && this.getSchool()
  },
  methods: {
    // 获取学校列表
    getSchool () {
      this.$get(this.api.querySchool, {
        provinceId: '',
        cityId: ''
      }).then(({ list }) => {
        this.setSchool(list)
      }).catch(res => { })
    },
    // 学号输入完回调。学校和学号都输入完后，调这个接口查询是否有存在的学生，如果没有，才能继续输入，如果有，不让添加
    workNumberChange () {
      const form = this.accountForm
      form.schoolId && form.workNumber && this.$get(`${this.api.enquireAboutSchoolStudents}?schoolId=${form.schoolId}&workNumber=${form.workNumber}&applyFor=1`).then(({ account }) => {
        if (account) this.form = account
        this.formEnable = !!account
      }).catch(res => {
        this.formEnable = true
      })
    },
    // 学校选择回调
    schoolChange (schoolId) {
      this.$get(this.api.getCustomerBySchoolId, {
        schoolId
      }).then(res => {
        if (!res) {
          this.accountVisible = false
          this.buyVisible = true
        }
      }).catch(res => { })
    },

    // 发送验证码
    sendCode () {
      const { phone } = this.accountForm
      // 校验用户手机号是否存在
      phone && this.$get(`${this.api.checkPhoneOrEmailExist}?phone=${phone}&type=1&email=`).then(res => {
        if (res) return Util.errorMsg('手机号已存在，请更换手机号！')
        if (!this.verifyPhone(phone)) return false
        this.$post(`${this.api.sendPhoneVerificationCode}?phoneOrEmail=${phone}&loginOrBind=1&platform=${Setting.platformId}`).then(({ message }) => {
          Util.successMsg(message)
          this.phoneCountdown()
        }).catch(res => { })
      }).catch(res => { })
    },
    // 验证码倒计时
    phoneCountdown () {
      let count = 60
      if (!this.phoneTimer) {
        this.phoneDisabled = true
        this.phoneTimer = setInterval(() => {
          if (count > 0) {
            count--
            this.phoneBtnText = `${count}秒后重试`
          } else {
            this.phoneDisabled = false
            clearInterval(this.phoneTimer)
            this.phoneTimer = null
            this.phoneBtnText = `发送验证码`
          }
        }, 1000)
      }
    },
    // 账号申请提交
    accountSubmit () {
      this.$refs.accountForm.validate(valid => {
        if (valid) {
          const form = this.accountForm
          if (form.password !== form.rePassword) return Util.errorMsg('两次输入的密码不一致，请重新输入！')
          // 平台id-端id-schoolId-workNumber组成账号
          form.account = `${Setting.platformId}-1-${form.schoolId}-${form.workNumber}`
          this.$post(this.api.studentAccountApplication, form).then(res => {
            this.accountVisible = false
            Util.successMsg('账号申请已提交，需管理员审核，请10分钟后再登录')
          }).catch(res => { })
        }
      })
    },
    // 账号申请关闭
    accountClose () {
      this.accountForm = {
        schoolId: '',
        account: '',
        code: '',
        password: '',
        rePassword: '',
        phone: '',
        userName: '',
        workNumber: '',
        uniqueIdentification: Date.now()
      }
    },
    // 弹框关闭回调
    closeDia () {
      this.$emit('update:visible', false)
    }
  }
};
</script>

<style lang="scss" scoped></style>