<template>
    <div class="wrap">
        <div class="login">
            <div class="form">
                <h6 class="title">欢迎使用请登录</h6>
                <ul class="tab">
                    <li v-for="(item,index) in tabList" :key="index" :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="!form.distinguish">
                        <el-form-item class="school-select" prop="schoolId">
                            <label class="label school"></label>
                            <el-select v-model="form.schoolId" clearable filterable placeholder="请选择学校">
                                <el-option v-for="(item, i) in schoolList" :key="i" :label="item.schoolName" :value="item.schoolId"></el-option>
                            </el-select>
                        </el-form-item>
                      <div class="items">
                        <el-form-item prop="type" style="width: 35%;margin-right: 15px">
                            <label class="label workNumber"></label>
                            <el-select v-model="form.type" placeholder="请选择类型" @change="typeChange">
                                <el-option label="学生学号" :value="1"></el-option>
                                <el-option label="老师工号" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="workNumber">
                            <label class="label account"></label>
                            <el-input v-model.trim="form.workNumber" :placeholder="'请输入' + (form.type ? '学生学号' : '老师工号')" @keyup.enter.native="submit"></el-input>
                        </el-form-item>
                      </div>
                    </div>
                    <!-- 手机号登录 -->
                    <el-form-item v-show="form.distinguish === 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>
                    <template v-if="form.distinguish === 2">
                      <el-form-item prop="account">
                        <label class="label account"></label>
                        <el-input v-model.trim="form.account" placeholder="请输入手机号/邮箱" @keyup.enter.native="submit"></el-input>
                      </el-form-item>
                      <el-form-item prop="code">
                        <label class="label code"></label>
                          <div class="flex">
                              <el-input v-model="form.code" placeholder="请输入验证码" maxlength="6" @keyup.enter.native="submit"></el-input>
                              <el-button style="margin-left: 10px" type="text" @click="sendPhoneCodeLogin" :disabled="phoneDisabledLogin">{{ phoneBtnTextLogin }}
                              </el-button>
                          </div>
                      </el-form-item>
                    </template>
                    <template v-if="form.distinguish !== 2">
                      <el-form-item prop="password">
                          <label class="password label"></label>
                          <el-input
                              type="password"
                              placeholder="请输入密码"
                              v-model.trim="form.password"
                              @keyup.enter.native="submit"
                          >
                          </el-input>
                      </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 v-show="!form.distinguish" class="default-check">
                      <el-checkbox v-model="setDefault">设置为默认学校</el-checkbox>
                    </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 ref="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 style="display: flex;">
                        <el-input v-model="phoneCode" placeholder="请输入验证码" maxlength="6"></el-input>
                        <el-button style="margin-left: 10px" type="text" @click="sendPhoneCode(1)" :disabled="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">该手机号已绑定以下用户信息</p>
            <ul class="users">
              <li v-for="(user, i) in users" :key="i" @click="chooseUser(user)">
                <span>{{ user.schoolName }}，{{ user.userName }}，{{ user.workNumber }}</span>
                <i class="el-icon-right"></i>
              </li>
            </ul>
        </el-dialog>
        <v-footer ref="footer"></v-footer>
    </div>
</template>

<script>
import vFooter from "@/layouts/footer";
import { mapMutations, mapActions } from "vuex";
import util from "@/libs/util";
import Setting from "@/setting";
import axios from "axios"
export default {
    data: function() {
        return {
            tabList: [
              {
                id: 0,
                label: '学号/工号登录'
              }, {
                id: 1,
                label: '学校管理员登录'
              }, {
                id: 2,
                label: '手机号/邮箱'
              }
            ],
            setDefault: !!util.local.get('schoolId'), // 本地缓存里有学校id，则默认勾选
            verificationIMG: '',
            schoolList: [],
            form: {
              schoolId: '',
              workNumber: '',
              account: '',
              password: '',
              code: '', // 验证码
              random: '', // 随机数
              distinguish: 0, // 区分手机号账号登录,1为账号登录,2为手机号或邮箱登录
              type: 1, // 平台端区分：0->教师端 1->学生端 2->无端
              platform: Setting.platformId
            },
            rules: {
              schoolId: [{ required: true, message: "请选择学校", trigger: "change" }],
              workNumber: [{ required: true, message: "请输入学生学号", trigger: "blur" }],
              account: [{ required: false, message: "请输入账号", trigger: "blur" }],
              password: [{ required: true, message: "请输入密码", trigger: "blur" }],
              code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
            },
            phoneDisabledLogin: false,
            phoneTimerLogin: null,
            phoneBtnTextLogin: '发送验证码',

            phoneVisible: false,
            phone: '',
            phoneCode: '',
            phoneDisabled: false,
            phoneTimer: null,
            phoneOpener: '',
            phoneBtnText: '发送验证码',
            selectVisible: false,
            selectedRole: '',
            token: '',
            userVisible: false,
            users: [],
            accountIds: [],
            binding: true
        };
    },
    components: {
        vFooter
    },
    mounted() {
        this.getVerImg()
        this.getSchool()
        // 页面离开的时候销毁手机和邮箱验证码定时器
        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"
        ]),
        getSchool() {
          this.$get(this.api.querySchool, {
            provinceId: '',
            cityId: ''
          }).then(res => {
            this.schoolList = res.list
            // 取本地缓存里的学校id
            const schoolId = util.local.get('schoolId')
            if (schoolId) this.form.schoolId = schoolId
          }).catch(res => {})
        },
        getVerImg() { // 获取验证码图片
          this.form.random = Math.floor(Math.random() * 999999999);
          this.verificationIMG = this.api.verification + "?random=" + `${this.form.random}`;
        },
        // 切换标签
        typeClick(tab) {
            const { id } = tab
            const form = this.form
            // 切换了后，全部字段重置
            this.form = {
              schoolId: form.schoolId,
              workNumber: '',
              account: '',
              password: '',
              code: '',
              random: form.random,
              distinguish: id,
              type: 1,
              platform: form.platform
            }
            this.$refs.form.clearValidate()
            // 切换了登录方式后，校验规则要变化
            const rules = this.rules
            rules.schoolId[0].required = id === 0
            rules.workNumber[0].required = id === 0
            rules.account[0].required = !!id
            this.rules.account[0].message = id === 1 ?
              '请输入账号' :
              '请输入手机号/邮箱'
        },
        // 学号工号切换
        typeChange(id) {
          this.rules.workNumber[0].message = id === 1 ?
            '请输入学生学号' :
            '请输入老师工号'
        },
        // 刷新官网
        reloadIndex() {
          window.opener && window.opener.location.reload()
        },
        // 选择用户回调
        chooseUser(user) {
          this.$post(`${this.api.getToken}?id=${user.id}`).then(({ data }) => {
            this.queryClient(data.token)
          }).catch(res => {})
        },
        // 查询是否是客户，如果是客户，则弹出选择端的页面去选择跳转到哪个端
        queryClient(token) {
          this.token = token
          axios.get(this.api.isClient, {
            headers: {
              token
            }
          }).then(({ data }) => {
            // 如果是客户
            if (data.customer) {
              this.SET_CUSTOMERNAME(data.customerName)
              this.selectVisible = true
            } else {
              this.setLogin()
            }
          }).catch(res => {})
        },
        // 处理登录成功
        setLogin() {
            util.local.set(Setting.tokenKey, this.token, Setting.tokenExpires)
            util.cookies.remove('serverLogin')
            this.reloadIndex()
            util.successMsg('登录成功')
            this.$router.replace('/station')
        },
        submit() { // 提交登录
            this.$refs.form.validate(valid => {
                if (valid) {
                    const form = JSON.parse(JSON.stringify(this.form))
                    const { distinguish } = form
                    if (!form.distinguish && this.setDefault) util.local.set('schoolId', form.schoolId) // 选的是学号工号登录，并且勾选了默认，则存入缓存
                    if (util.local.get('schoolId') && !this.setDefault) util.local.remove('schoolId') // 本地缓存了学校id，并且没有勾选默认，则删除缓存
                    if (distinguish) form.schoolId = ''
                    if (!distinguish) form.distinguish = 1
                    this.$post(this.api.logins, form).then(({ status, data, message }) => {
                        // 未绑定手机号，则弹框去绑定
                        if (status == 30001) {
                            this.phoneVisible = true
                            this.getVerImg()
                            form.code = ''
                        } else if (status == 200) {
                          // 如果返回的是数组，则弹框给用户选择登录哪个用户，否则，直接登录
                          if (data instanceof Array) {
                            this.users = data
                            this.userVisible = true
                          } else {
                            this.queryClient(data.token)
                          }
                        } else {
                            util.errorMsg(message)
                        }
                    }).catch(res => {
                        this.getVerImg()
                        form.code = ''
                    })
                }
            });
        },
        // 选择端
        selectRole(val) {
            this.selectedRole = val
            if (val === 1) {
                this.setLogin()
            } else {
                // 从学生端登录到教师端的标识，教师端需要使用
                util.cookies.set('serverLogin', true, {
                  expires: new Date(Date.now() + 15 * 60 * 1000) // 15分钟后过期
                })
                this.reloadIndex()
                // 跳转到教师端的重定向页面
                location.href = Setting.isDev ?
                  'http://192.168.31.125:8081/#/redirect?auth=' + btoa(this.token) :
                  `${location.origin}/admin/#/redirect?auth=${window.btoa(this.token)}`
            }
        },
        // 验证手机号
        verifyPhone(phone) {
          if (!phone) {
            util.warningMsg("请输入手机号")
            return false
          }
          if (!/^1[3456789]\d{9}$/.test(phone) && !/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(phone)) {
            util.warningMsg("请输入正确的手机号/邮箱")
            return false
          }
          return true
        },
        
        // 验证码倒计时
        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`).then(({ message }) => {
            util.successMsg(message)
            this.phoneCountdownLogin()
          }).catch(res => {})
        },
        // 手机号失去焦点回调
        phoneChange() {
          this.$post(`${this.api.getOtherAccountByPhone}?phone=${this.phone}&platform=${Setting.platformId}`).then(({ userAccounts }) => {
            const list = userAccounts
            if (list) {
              const msg = []
              list.map(e => {
                msg.push(`${e.userName}（${e.schoolName}，学号${e.workNumber}）`)
              })
              this.accountIds = list.map(e => e.id)
              this.$confirm(`该手机号已与${msg.join('；')}的用户绑定，是否为本人？选择否，则解绑以上用户信息，并授权手机号绑定新用户信息。`, '提示', {
                type: 'warning',
                confirmButtonText: '是',
                cancelButtonText: '否'
              }).then(() => {
                debugger
                this.binding = true
                this.sendPhoneCode(1)
              }).catch(() => {
                debugger
                this.binding = false
                this.sendPhoneCode(0)
              })
            }
          }).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`).then(({ 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(({ token }) => {
            this.token = token
            this.setLogin()
          }).catch(res => {})
        },
        // 绑定手机号
        phoneSubmit() {
          const { phone, phoneCode } = this
          if (!this.verifyPhone(phone)) return false
          if (!phoneCode) return util.warningMsg('请输入验证码')
          if (this.binding) {
            this.$post(this.api.bindPhoneOrEmail, {
              phone,
              types: 2,
              code: phoneCode,
              opener: this.phoneOpener,
              platform: Setting.platformId,
              account: this.form.workNumber
            }).then(({ token }) => {
              this.token = token
              this.setLogin()
            }).catch(res => {})
          } else {
            this.unbind()
          }
        }
    }
};
</script>

<style scoped lang="scss">
.wrap {
    min-height: 100%;
    background-color: #F3F6FA;
}
.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-between;
        align-items: center;
        margin-bottom: 24px;
        border-bottom: 2px solid #E1E6F2;
        li{
            padding: 18px 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: 1px solid #E1E6F2;
        border-radius: 4px !important;
    }
    .default-check {
      text-align: right;
    }
    .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;
    }
    .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: 1px;
        right: 1px;
    }
    /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: .8;
        }
    }
}
.port {
    display: flex;
    justify-content: center;
    padding: 60px 0;
    li {
        text-align: center;
        cursor: pointer;
        &:first-child {
            margin-right: 86px;
        }
        &:hover img {
            opacity: .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;
      &:last-child {
        margin-bottom: 0;
      }
      &:hover {
        background-color: #d3e0ff;
      }
      i {
        font-size: 16px;
      }
    }
  }
}
@media (max-height: 680px) {
    .wrap .login {
        padding: 40px 0;
    }
}
</style>