<template>
  <div class="wrap">
    <div class="login">
      <!-- <div class="notice-alert">
        <el-alert
          title="平台维护通知:我们计划于2024年9月6日(星期五)20:00至2024年9月7日(星期六)12:00进行系统维护升级工作。维护期间,平台将暂时关闭,所有用户将无法登录平台,全部服务将暂停使用。"
          type="warning" :closable="false">
        </el-alert>
      </div> -->
      <div class="form">
        <h6 class="title">欢迎使用请登录</h6>

        <ul class="tab">
          <li v-for="(item, i) in tabList" :key="i" :class="{ active: form.distinguish == item.id }"
            @click="typeClick(item)">{{ item.label }}</li>
        </ul>
        <el-form :model="form" :rules="rules" ref="form" style="margin-top: 20px">
          <!-- 账号 -->
          <div v-show="!verCodeLogin" class="items">
            <el-form-item class="flex-1" prop="account">
              <label class="label account"></label>
              <el-input v-model.trim="form.account" placeholder="请输入账号" @keyup.enter.native="submit"></el-input>
            </el-form-item>
          </div>
          <template v-if="verCodeLogin">
            <el-form-item prop="account" ref="phoneItem">
              <label class="label account"></label>
              <el-input v-model.trim="form.account" placeholder="请输入手机号/邮箱" @input="val => checkAccountByPhone(val, 0)"
                @keyup.enter.native="submit">
                <img v-if="verFormEnable" slot="suffix" class="correct-icon" src="@/assets/img/login/correct.svg"
                  alt="">
              </el-input>
              <p v-if="diaClientMsg" class="el-form-item__error">{{ diaClientMsg }}</p>
            </el-form-item>
            <el-form-item prop="code">
              <label class="label code"></label>
              <div class="ver-code">
                <el-input v-model="form.code" placeholder="请输入验证码" maxlength="6" :disabled="!verFormEnable"
                  @keyup.enter.native="submit"></el-input>
                <el-button type="text" @click="sendPhoneCodeLogin" :disabled="phoneDisabledLogin || !verFormEnable">{{
                  phoneBtnTextLogin
                }}
                </el-button>
              </div>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item class="relative" prop="password">
              <label class="password label"></label>
              <el-input type="password" placeholder="请输入密码" v-model.trim="form.password" @keyup.enter.native="submit" />
              <el-link class="resetPw" :underline="false" type="primary" @click="showResetPw">忘记密码</el-link>
            </el-form-item>
            <el-form-item prop="code">
              <label class="label code"></label>
              <el-input placeholder="请输入验证码" v-model.trim="form.code" @keyup.enter.native="submit">
              </el-input>
              <img @click="getVerImg" :src="verificationIMG" class="ver-img" alt="">
            </el-form-item>
          </template>
          <div class="bottom">
            <el-link :underline="false" type="primary" @click="switchType">{{ verCodeLogin ? '密码' : '验证码' }}登录</el-link>
            <!-- 只有手机号和验证码两个字段的注册 -->
            <el-link v-if="person" :underline="false" type="primary" @click="toAccount">没有账号,点击申请</el-link>
            <!-- 安财赛事注册 -->
            <el-link v-else-if="fromOffical" :underline="false" type="primary"
              @click="accountApplyMatchVisible = true">暂无账号?点击申请</el-link>
            <!-- 未登录的赛事点击报名进入后的注册 -->
            <el-link v-else-if="toMatch" :underline="false" type="primary"
              @click="accountApplyVisible = true">暂无账号?点击申请</el-link>
          </div>
          <el-button class="submit" type="primary" @click="submit">登录</el-button>
        </el-form>
      </div>
    </div>
    <el-dialog title="绑定手机号" :visible.sync="phoneVisible" :close-on-click-modal="false" width="30%">
      <div style='padding: 0 13px 20px 13px;'>
        依据国家政策法规,需绑定手机号进行网络实名才可登录使用本平台
      </div>
      <el-form label-width="60px">
        <el-form-item label="手机号">
          <el-input style="width: 100%;" placeholder="请输入手机号" v-model="phone" maxlength="11"
            @change="phoneChange"></el-input>
        </el-form-item>
        <el-form-item label="验证码">
          <div class="ver-code">
            <el-input v-model="phoneCode" placeholder="请输入验证码" maxlength="6"></el-input>
            <el-button style="top: 1px" type="text" @click="sendPhoneCode(1)"
              :disabled="binding === '' || phoneDisabled">{{
                phoneBtnText }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="phoneVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="phoneSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="请选择" :visible.sync="selectVisible" :close-on-click-modal="false" custom-class="select-dia"
      width="643px">
      <ul class="port">
        <li :class="{ active: selectedRole === 1 }" @click="selectRole(1)">
          <img src="@/assets/img/login/male.png" alt="">
          <p>学生端</p>
        </li>
        <li :class="{ active: selectedRole === 2 }" @click="selectRole(2)">
          <img src="@/assets/img/login/female.png" alt="">
          <p>教师管理端</p>
        </li>
      </ul>
    </el-dialog>
    <el-dialog title="请选择您要登录的用户" :visible.sync="userVisible" :close-on-click-modal="false" custom-class="user-dia"
      width="500px">
      <p class="tips">该{{ verCodeLogin ? '手机号已绑定' : '账号存在' }}以下用户信息</p>
      <ul class="users">
        <li :class="{ isEnable: !user.isEnable }" v-for="(user, i) in users" :key="i" @click="chooseUser(user)">
          <span>{{ user.typeName }},{{ user.schoolName }},{{ user.userName }},{{ user.workNumber }}{{
            user.isEnable
              ? ''
              : '(已禁用)' }}</span>
          <i class="el-icon-right"></i>
        </li>
      </ul>
    </el-dialog>
    <el-dialog :visible.sync="infoVisible" :close-on-click-modal="false" custom-class="info-dia" :show-close="false"
      width="400px">
      <div class="info-header">
        <i class="el-icon-warning"></i>
        提示
      </div>
      <div class="info-wrap">
        <p class="tips">该手机号已与以下用户绑定</p>
        <ul class="users">
          <li v-for="(user, i) in infos" :key="i">
            <span>{{ user.userName }}({{ user.schoolName }})</span>
          </li>
        </ul>
        <div class="info-footer">
          <el-button size="small" type="primary" @click="bindPhone">是本人,继续绑定</el-button>
          <el-button class="unbind" size="small" @click="unbindPhone">不是本人,解绑以上用户并绑定新用户</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog title="重设密码" :visible.sync="resetPwVisible" :close-on-click-modal="false" width="500px">
      <el-form class="dia-form" ref="pwForm" label-width="110px" :model="pwForm" :rules="pwRules">
        <el-form-item prop="phoneOrEmail" label="手机号/邮箱" ref="diaPhoneItem">
          <el-input placeholder="请输入手机号/邮箱" v-model.trim="pwForm.phoneOrEmail"
            @input="val => checkAccountByPhone(val, 1)">
            <img v-if="diaClientExist" slot="suffix" style="margin-top: -6px;" src="@/assets/img/login/correct.svg"
              alt="">
          </el-input>
          <p v-if="diaClientMsg" class="el-form-item__error">{{ diaClientMsg }}</p>
        </el-form-item>
        <el-form-item prop="code" label="验证码">
          <div class="ver-code">
            <el-input v-model="pwForm.code" placeholder="请输入验证码" maxlength="6" :disabled="!diaClientExist"></el-input>
            <el-button style="top: 1px" type="text" @click="sendCodePw" :disabled="phoneDisabled || !diaClientExist">{{
              phoneBtnText }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item prop="newPassword" label="登录密码">
          <el-input placeholder="请输入登录密码" type="password" maxlength="6" v-model="pwForm.newPassword"></el-input>
        </el-form-item>
        <el-form-item prop="newPasswordTwo" label="确认登录密码">
          <el-input placeholder="请再次输入登录密码" type="password" maxlength="6" v-model="pwForm.newPasswordTwo"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="diaClientExist" size="small" type="primary" @click="pwSubmit">确定</el-button>
        <el-button size="small" @click="resetPwVisible = false">取消</el-button>
      </span>
    </el-dialog>

    <el-dialog title="欢迎注册" :visible.sync="accountVisible" :close-on-click-modal="false" width="500px">
      <el-form class="dia-form" ref="accountForm" label-width="80px" :model="accountForm" :rules="accountRules">
        <el-form-item prop="phoneOrEmail" label="手机号">
          <el-input placeholder="请输入手机号" maxlength="11" v-model.trim="accountForm.phoneOrEmail"
            @input="checkAccountByPhoneReg"></el-input>
          <div v-if="regClientExist" class="flex a-center text-red">
            该手机号已注册,您可直接点
            <el-link class="m-l-5" :underline="false" type="primary" @click="accountVisible = false">此处登录</el-link>
          </div>
        </el-form-item>
        <el-form-item prop="code" label="验证码">
          <div class="ver-code">
            <el-input v-model="accountForm.code" placeholder="请输入验证码" maxlength="6" :disabled="regDisable"></el-input>
            <el-button style="top: 1px" type="text" @click="sendCode" :disabled="phoneDisabled || regDisable">{{
              phoneBtnText }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="!regDisable" size="small" type="primary" @click="accountSubmit">立即注册</el-button>
        <el-button size="small" @click="accountVisible = false">取消</el-button>
      </span>
    </el-dialog>
    <v-footer ref="footer"></v-footer>

    <AccountApply :visible.sync="accountApplyVisible" />
    <AccountApplyMatch :visible.sync="accountApplyMatchVisible" />
  </div>
</template>

<script>
import vFooter from '@/layouts/footer'
import { mapState, mapMutations, mapActions } from 'vuex'
import Util from '@/libs/util'
import Setting from "@/setting";
import AccountApply from './accountApply'
import AccountApplyMatch from './accountApplyMatch'
import CryptoJS from 'crypto-js'
import JSEncrypt from 'jsencrypt'
export default {
  data: function () {
    return {
      tabList: [
        {
          id: 0,
          label: '学生/老师登录'
        }, {
          id: 1,
          label: '学校管理员登录'
        }
      ],
      person: false,
      toMatch: localStorage.getItem('toMatch'),
      fromOffical: !!this.$route.query.q, // 来自安财赛事
      phoneReg: /^1[3456789]\d{9}$/,
      mailReg: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
      verificationIMG: '',
      form: {
        account: '', // 手机号验证码模式用这个字段
        password: '',
        code: '', // 验证码
        random: '', // 随机数
        platform: Setting.platformId,
        distinguish: 0,
      },
      rules: {
        account: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      },
      verFormEnable: false,
      verCodeLogin: false,
      phoneDisabledLogin: false,
      phoneTimerLogin: null,
      phoneBtnTextLogin: '发送验证码',

      phoneVisible: false,
      phone: '',
      phoneCode: '',
      phoneDisabled: false,
      phoneTimer: null,
      phoneOpener: '',
      phoneBtnText: '发送验证码',
      selectVisible: false,
      selectedRole: '',
      token: '',
      curUser: {},
      userVisible: false,
      users: [],
      accountIds: [],
      binding: '',
      infoVisible: false,
      infos: [],

      accountApplyVisible: false,
      accountApplyMatchVisible: false,
      accountVisible: false,
      regDisable: true,
      regClientExist: false,
      accountForm: {
        code: '',
        phoneOrEmail: '',
      },
      accountRules: {
        phoneOrEmail: [{ required: true, message: "请输入手机号/邮箱", trigger: "blur" }],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      },


      resetPwVisible: false,
      diaClientExist: false,
      diaClientMsg: '',
      pwForm: {
        code: '',
        newPassword: '',
        newPasswordTwo: '',
        phoneOrEmail: '',
      },
      pwRules: {
        phoneOrEmail: [{ required: true, message: "请输入手机号/邮箱", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        rePassword: [{ required: true, message: "请再次输入密码", trigger: "blur" }],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      },
    };
  },
  computed: {
    ...mapState('project', [
      'courseId'
    ])
  },
  components: {
    vFooter, AccountApply, AccountApplyMatch
  },
  mounted () {
    localStorage.removeItem('opened')
    this.getVerImg()
    // 页面离开的时候销毁手机和邮箱验证码定时器
    this.$once("hook:beforeDestroy", function () {
      clearInterval(this.phoneTimer)
      clearInterval(this.phoneTimerLogin)
      this.phoneTimer = null
      this.phoneTimerLogin = null
    })
  },
  methods: {
    ...mapMutations("user", [
      'SET_CUSTOMERNAME'
    ]),
    ...mapActions("user", [
      "setInfo"
    ]),
    getVerImg () { // 获取验证码图片
      this.form.random = Math.floor(Math.random() * 999999999);
      this.verificationIMG = this.api.verification + "?random=" + `${this.form.random}`;
    },
    // 重置验证规则
    handleRule () {
      this.rules.account[0].message = this.verCodeLogin ?
        '请输入手机号/邮箱' :
        '请输入账号'
    },
    // 切换标签
    typeClick (tab) {
      const { id } = tab
      const form = this.form
      // 切换了后,全部字段重置
      this.form = {
        workNumber: '',
        account: '',
        password: '',
        code: '',
        random: form.random,
        distinguish: id,
        platform: form.platform
      }
      if (id) this.verCodeLogin = false
      this.$refs.form.clearValidate()
      this.handleRule()
    },
    // 刷新官网
    reloadIndex () {
      try {
        window.opener && window.opener.location.reload()
      } catch (e) { }
    },
    // 选择用户回调
    chooseUser (user) {
      this.curUser = user
      user.isEnable && this.$post(`${this.api.getToken}?id=${user.id}&platform=${Setting.platformId}`).then(({ status, data }) => {
        if (status === 30001) { // 未实名
          this.phoneVisible = true
          this.getVerImg()
          form.code = ''
        } else if (data) {
          this.token = data.token
          user.typeName === '学生端' ? this.setLogin() : this.toMang()
        }
      }).catch(res => { })
    },
    // 处理登录成功
    setLogin () {
      Util.local.set(Setting.tokenKey, this.token, Setting.tokenExpires)
      this.getOss()
      Util.cookies.remove('serverLogin')
      this.reloadIndex()
      Util.successMsg('登录成功')
      const { toMatch } = this
      localStorage.removeItem('toMatch')
      this.$router.replace(this.courseId ?
        `/preCourse/details?id=${this.courseId}` :
        toMatch ?
          `/touristMatch/details?id=` + toMatch :
          '/station')
    },
    async getOss () {
      const A = (key, encryptedData) => {
        const keyHex = CryptoJS.enc.Base64.parse(key)
        const decrypted = CryptoJS.AES.decrypt(encryptedData, keyHex, {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.Pkcs7
        })
        return decrypted.toString(CryptoJS.enc.Utf8)
      }

      const R = (encryptedKey, privateKey) => {
        const decrypt = new JSEncrypt()
        decrypt.setPrivateKey(privateKey)
        const decryptedKey = decrypt.decrypt(encryptedKey)
        return decryptedKey
      }

      const res = await this.$get(this.api.encrypt)
      const RE = A(R(res.encryptedKey, res.privateKey), res.encryptedData).split('/')
      localStorage.setItem('osc', JSON.stringify(RE))
    },
    // 提交登录
    submit () {
      this.$refs.form.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(this.form))
          if (this.verCodeLogin) form.distinguish = 2
          this.$post(this.api.logins, form).then(({ status, data, message }) => {
            // 未绑定手机号,则弹框去绑定
            if (status == 30001) {
              this.phoneVisible = true
              this.getVerImg()
              form.code = ''
            } else if (status == 200) {
              const accounts = data.userAccounts
              // 如果返回的是数组,则弹框给用户选择登录哪个用户,否则,直接登录
              if (accounts instanceof Array) {
                this.users = accounts
                this.userVisible = true
              } else {
                this.token = data.token
                // 如果是客户,则需要选择登录的端
                if (data.customer) {
                  Util.cookies.set('customerName', data.customerName)
                  this.SET_CUSTOMERNAME(data.customerName)
                  this.selectVisible = true
                } else {
                  data.typeName === '学生端' ? this.setLogin() : this.toMang()
                }
              }
            } else {
              form.code = ''
              Util.errorMsg(message)
            }
          }).catch(res => {
            form.code = ''
            this.getVerImg()
          })
        }
      });
    },
    // 跳转到教师端
    toMang () {
      const { token } = this
      Util.local.set('oc_server_token', token, Setting.tokenExpires)
      // 从学生端登录到教师端的标识,教师端需要使用
      Util.cookies.set('serverLogin', true, {
        expires: new Date(Date.now() + 15 * 60 * 1000) // 15分钟后过期
      })
      this.reloadIndex()

      // 跳转到教师端的重定向页面
      location.href = Setting.isDev ?
        `http://${location.hostname}:8081/#/redirect?auth=${btoa(this.token)}` :
        `${location.origin}/admin/#/redirect?auth=${window.btoa(this.token)}`
    },
    // 选择端
    selectRole (val) {
      this.selectedRole = val
      if (val === 1) {
        this.setLogin()
      } else {
        this.toMang()
      }
    },
    // 验证手机号
    verifyPhone (phone) {
      if (!phone) {
        this.$message.error("请输入手机号")
        return false
      }
      if (!this.phoneReg.test(phone) && !this.mailReg.test(phone)) {
        this.$message.error("请输入正确的手机号/邮箱")
        return false
      }
      return true
    },

    // 忘记密码
    showResetPw () {
      this.pwForm = {
        code: '',
        newPassword: '',
        newPasswordTwo: '',
        phoneOrEmail: '',
      }
      this.diaClientExist = false
      this.resetPwVisible = true
      this.diaClientMsg = ''
    },

    // 重设密码发送验证码
    async sendCodePw () {
      const { phoneOrEmail } = this.pwForm
      if (!this.verifyPhone(phoneOrEmail)) return false
      const { message } = await this.$post(`${this.api.sendPhoneVerificationCode}?phoneOrEmail=${phoneOrEmail}&loginOrBind=1&platform=${Setting.platformId}`)
      Util.successMsg(message)
      this.phoneCountdown()
    },
    // 重设密码提交
    pwSubmit () {
      this.$refs.pwForm.validate(valid => {
        if (valid) {
          const form = this.pwForm
          if (form.password !== form.rePassword) return Util.errorMsg('两次输入的密码不一致,请重新输入!')
          form.platform = Setting.platformId
          this.$post(this.api.forgotPassword, form).then(res => {
            this.resetPwVisible = false
            Util.successMsg('密码重置成功!请重新登录。')
          }).catch(res => { })
        }
      })
    },

    // 手机号输入完回调。有账号才能继续操作。type:0手机验证码登录,1重置密码
    async checkAccountByPhone (val, type) {
      if (!this.phoneReg.test(val) && !this.mailReg.test(val)) {
        this.$refs[type ? 'diaPhoneItem' : 'phoneItem'].clearValidate()
        this.diaClientMsg = '请输入正确的手机号/邮箱'
        this[type ? 'diaClientExist' : 'verFormEnable'] = false
        return false
      }

      try {
        const { message } = await this.$get(`${this.api.forgotPreVerification}?phoneOrEmail=${val}&platform=${Setting.platformId}`)
        const exist = message === 'success' // 用户已存在
        this[type ? 'diaClientExist' : 'verFormEnable'] = exist
        this.diaClientMsg = exist ? '' : message
      } catch (e) {
        this[type ? 'diaClientExist' : 'verFormEnable'] = false
        this.diaClientMsg = e.message
      }
    },
    // 账号申请
    switchType () {
      this.verCodeLogin = !this.verCodeLogin
      this.$refs.form.clearValidate()
      this.form.code = ''
      this.handleRule()
    },

    // 发送验证码
    async sendCode () {
      const { phoneOrEmail } = this.accountForm
      // 校验用户手机号是否存在
      if (!this.verifyPhone(phoneOrEmail)) return false
      const { message } = await this.$post(`${this.api.sendPhoneVerificationCode}?phoneOrEmail=${phoneOrEmail}&loginOrBind=1&platform=6`)
      Util.successMsg(message)
      this.phoneCountdown()
    },

    // 账号申请
    toAccount () {
      this.accountForm = {
        code: '',
        phoneOrEmail: '',
      }
      this.regDisable = true
      this.regClientExist = false
      this.accountVisible = true
    },
    // 注册手机号输入完回调。没有账号才能继续操作
    async checkAccountByPhoneReg (val) {
      if (!this.phoneReg.test(val) && !this.mailReg.test(val)) return false

      try {
        const { message } = await this.$get(`${this.api.forgotPreVerification}?phoneOrEmail=${val}&platform=6`)
        const exist = message === 'success' // 用户已存在
        this.regDisable = !exist
        this.regClientExist = exist
      } catch (e) { }
    },
    // 账号申请提交
    accountSubmit () {
      this.$refs.accountForm.validate(valid => {
        if (valid) {
          const form = this.accountForm
          form.platform = 6
          this.$post(this.api.quickRegistration, form).then(res => {
            this.accountVisible = false
            Util.successMsg('注册成功!')
          }).catch(res => { })
        }
      })
    },

    // 验证码倒计时
    phoneCountdownLogin () {
      let count = 60
      if (!this.phoneTimerLogin) {
        this.phoneDisabledLogin = true
        this.phoneTimerLogin = setInterval(() => {
          if (count > 0) {
            count--
            this.phoneBtnTextLogin = `${count}秒后重试`
          } else {
            this.phoneDisabledLogin = false
            clearInterval(this.phoneTimerLogin)
            this.phoneTimerLogin = null
            this.phoneBtnTextLogin = `发送验证码`
          }
        }, 1000)
      }
    },
    // 发送验证码
    sendPhoneCodeLogin () {
      const phone = this.form.account
      if (!this.verifyPhone(phone)) return false
      this.$post(`${this.api.sendPhoneVerificationCode}?phoneOrEmail=${phone}&loginOrBind=0&platform=${Setting.platformId}`).then(({ message }) => {
        Util.successMsg(message)
        this.phoneCountdownLogin()
      }).catch(res => { })
    },
    // 继续绑定
    bindPhone () {
      this.infoVisible = false
      this.binding = true
      this.sendPhoneCode(1)
    },
    // 解除绑定
    unbindPhone () {
      this.infoVisible = false
      this.binding = false
      this.sendPhoneCode(0)
    },
    // 手机号失去焦点回调
    phoneChange () {
      this.$post(`${this.api.getOtherAccountByPhone}?phone=${this.phone}&platform=${Setting.platformId}`).then(({ userAccounts }) => {
        const list = userAccounts
        if (list && list.length) {
          list.map(e => {
            const { userName } = e
            if (userName.length > 1) e.userName = userName[0] + '*' + userName.substring(2)
          })
          this.infos = list
          this.accountIds = list.map(e => e.id)
          this.infoVisible = true
        } else {
          this.binding = true
        }
      }).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)
      }
    },
    // 发送验证码
    sendPhoneCode (bind) {
      const { phone } = this
      if (!this.verifyPhone(phone)) return false
      // 不解绑发送验证码
      if (bind) {
        this.$post(this.api.sendPhoneOrEmailCode, {
          platform: Setting.platformId,
          phone,
          types: 2
        }).then(({ message }) => {
          if (message.opener) {
            this.phoneCountdown()
            this.phoneOpener = message.opener
          } else {
            Util.errorMsg(message)
          }
        }).catch(res => { })
      } else {
        this.$post(`${this.api.sendPhoneVerificationCode}?phoneOrEmail=${phone}&loginOrBind=1&platform=${Setting.platformId}`).then(({ message }) => {
          Util.successMsg(message)
          this.phoneCountdown()
        }).catch(res => { })
      }
    },
    // 解绑
    unbind () {
      const { password, platform, schoolId, type, workNumber } = this.form
      this.$post(this.api.unbindAccounts, {
        accountIds: this.accountIds,
        code: this.phoneCode,
        password,
        phone: this.phone,
        platform,
        schoolId,
        type,
        workNumber,
      }).then(({ data }) => {
        this.token = data.token
        this.setLogin()
      }).catch(res => { })
    },
    // 绑定手机号
    phoneSubmit () {
      const { phone, phoneCode } = this
      if (!this.verifyPhone(phone)) return false
      if (!phoneCode) return Util.warningMsg('请输入验证码')
      const { workNumber, schoolId } = this.form
      if (this.binding) {
        this.$post(this.api.bindPhoneOrEmail, {
          mark: this.form.type,
          phone,
          types: 2,
          code: phoneCode,
          opener: this.phoneOpener,
          platform: Setting.platformId,
          account: workNumber,
          schoolId,
          accountId: this.curUser.id || '',
        }).then(({ token }) => {
          this.token = token
          this.setLogin()
        }).catch(res => { })
      } else {
        this.unbind()
      }
    }
  }
};
</script>

<style scoped lang="scss">
.wrap {
  min-height: 100%;
  background-color: #f3f6fa;

  .notice-alert {
    max-width: 436px;
    margin: 0 auto 20px;
  }
}

.ver-code {
  position: relative;

  .el-button {
    position: absolute;
    top: 10px;
    right: 10px;
  }
}

.login {
  min-height: calc(100vh - 43px);
  padding-top: calc((100vh - 584px) / 2);
  background: url(../../../assets/img/shapes/shape1.png) (0 123px) / auto no-repeat,
    url(../../../assets/img/shapes/shape2.png) (35px 238px) / auto no-repeat,
    url(../../../assets/img/shapes/shape3.png) (0 485px) / auto no-repeat,
    url(../../../assets/img/shapes/shape4.png) (right 50%) / auto no-repeat,
    url(../../../assets/img/shapes/shape5.png) (right 80%) / auto no-repeat,
    url(../../../assets/img/shapes/shape6.png) (right bottom) / auto no-repeat;

  .tab {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-bottom: 24px;
    border-bottom: 2px solid #e1e6f2;

    li {
      padding: 18px 0;
      // margin: 0 20px -1px 0;
      margin-bottom: -1px;
      font-size: 16px;
      color: #555;
      cursor: pointer;
      border-bottom: 4px solid transparent;

      &:last-child {
        margin-right: 0;
      }

      &.active {
        color: $main-color;
        border-bottom-color: $main-color;
      }
    }
  }

  .items {
    display: flex;
    align-items: center;
  }

  .form {
    width: 436px;
    padding: 38px 38px 60px;
    margin: 0 auto 0;
    border-radius: 6px;
    background-color: #fff;

    .title {
      margin-bottom: 25px;
      font-size: 26px;
      color: #0b1d30;
      letter-spacing: 4px;
    }
  }

  /deep/.el-form-item {
    margin-bottom: 20px;
  }

  /deep/.el-input__inner {
    position: relative;
    height: 52px;
    padding: 0 20px 0 34px;
    line-height: 50px;
    background-color: #fbfbfb;
    border-color: #e1e6f2;
    border-radius: 4px !important;

    &:focus {
      border-color: $main-color;
      box-shadow: 0 0 2px #4486e9;
    }
  }

  .resetPw {
    position: absolute;
    top: 10px;
    right: 10px;
  }

  .bottom {
    display: flex;
    justify-content: space-between;
  }

  .el-select {
    width: 100%;
  }

  .label {
    z-index: 1;
    position: absolute;
    top: 17px;
    left: 11px;
    width: 18px;
    height: 18px;
    background: url(../../../assets/img/login/account.png) 0 0/100% 100% no-repeat;
  }

  .correct-icon {
    width: 30px;
    margin: 11px 3px 0 0;
  }

  .school {
    background-image: url(../../../assets/img/login/school.png);
  }

  .workNumber {
    width: 17px;
    background-image: url(../../../assets/img/login/workNumber.png);
  }

  .password {
    top: 18px;
    background-image: url(../../../assets/img/login/password.png);
  }

  .code {
    top: 18px;
    background-image: url(../../../assets/img/login/code.png);
  }

  .ver-img {
    position: absolute;
    top: 2px;
    right: 2px;
  }

  /deep/.el-form-item__error {
    top: 105%;
    left: auto;
    right: 0;
    color: #ffa94e;
  }

  .submit {
    width: 100%;
    height: 48px;
    margin-top: 30px;
    line-height: 48px;
    padding: 0;
    font-size: 20px;
    background-color: $main-color;
    border-radius: 4px;
    border: 0;
  }
}

.copyright {
  padding: 18px 0;
  font-size: 12px;
  text-align: center;
  background-color: #f3f6fa;

  a {
    color: #b1b4b8;
    font-size: 12px;

    &:hover {
      opacity: 0.8;
    }
  }
}

.port {
  display: flex;
  justify-content: center;
  padding: 60px 0;

  li {
    text-align: center;
    cursor: pointer;

    &:first-child {
      margin-right: 86px;
    }

    &:hover img {
      opacity: 0.9;
    }

    &.active p,
    &:hover p {
      background-color: #9278ff;
    }
  }

  img {
    width: 122px;
    margin-bottom: 20px;
  }

  p {
    width: 88px;
    margin: 0 auto;
    line-height: 21px;
    color: #fff;
    background-color: #e8e3ff;
    border-radius: 4px;
  }
}

/deep/.select-dia {
  margin-top: calc((100vh - 383px) / 2) !important;
}

/deep/.user-dia {
  .tips {
    margin-bottom: 20px;
    text-align: center;
    color: #666;
  }

  .users {
    li {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 15px;
      margin-bottom: 10px;
      line-height: 40px;
      font-size: 14px;
      background-color: #ebeef5;
      cursor: pointer;

      &.isEnable {
        color: #c0c4cc;
        background-color: #f5f7fa;
        cursor: not-allowed;
      }

      &:last-child {
        margin-bottom: 0;
      }

      &:hover {
        background-color: #d3e0ff;
      }

      i {
        font-size: 16px;
      }
    }
  }
}

/deep/.info-dia {
  .el-dialog__header {
    border-bottom: 0;
  }

  .info-header {
    position: absolute;
    top: 20px;
    display: flex;
    align-items: center;
    font-size: 16px;
    color: #333;
  }

  .el-icon-warning {
    margin-right: 10px;
    color: #e6a23c;
    font-size: 24px;
  }

  .info-wrap {
    padding: 10px 33px;
  }

  .users {
    max-height: 125px;
    margin-top: 20px;
    overflow: auto;

    li {
      margin: 5px;
      font-size: 14px;
      color: #333;
    }
  }

  .info-footer {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
  }

  .el-button {
    width: 142px;
  }

  .unbind {
    white-space: normal;
    line-height: 1.6;
  }
}

/deep/.dia-form {
  .w-100 {
    width: 100%;
  }

  .tips {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .err-msg {
    font-size: 12px;
    color: #F56C6C;
    line-height: 1;
  }
}


@media (max-height: 680px) {
  .wrap .login {
    padding: 40px 0;
  }
}
</style>