<template>
<div class="zh_login">
	<div class="zh_login_logo"><img src="../../../static/img/logo-2.png" /><div>服务热线：010-53932350</div></div>
	<div class="zh_login_box">
		<div class="zh_login_in">
			<div class="zh_login_from" v-if="this.confirm == 1">
				<div class="zh_login_h">确认登陆</div>
				<el-form ref="loginForm" :model="loginForm"  auto-complete="on" label-position="left">
					<el-form-item class="zh_txt">
						<el-input
						  v-model="loginForm.iphoneNumber"
						  placeholder="请输入手机号"
						  name="iphoneNumber"
						  type="text"
						  auto-complete="on"
              :disabled="true"
						/>
      				</el-form-item>
	  				<div class="zh_tips"><span></span></div>
					<el-form-item prop="verificationCode" class="zh_txt">
						<el-input
						  :type="passwordType"
						  v-model="loginForm.verificationCode"
						  placeholder="请输入验证码"
						  name="verificationCode"
						  auto-complete="on"
						  @keyup.enter.native="handleLogin"
              style="width: 60%;float: left"
            />
            <el-button type="primary"  style="width: 40%;float: left" @click="getMessageAgain">{{innerText}}</el-button>
					</el-form-item>
					<div class="zh_tips"><span></span></div>
					<div class="zh_goPwd"></div>

					<el-button type="primary" class="zh_loginBtn" @click.native.prevent="getCheckCode('ruleForm')">确认</el-button>
					<div class="zh_tips"></div>
				</el-form>

				<el-dialog :title="$t('login.thirdparty')" :visible.sync="showDialog" append-to-body>
					{{ $t('login.thirdpartyTips') }}
				<social-sign />
				</el-dialog>

			</div>

      <div class="zh_login_from" v-if="this.confirm != 1">
        <div class="zh_login_h">登录远程诊断平台</div>
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" auto-complete="on" label-position="left">
          <el-form-item prop="username" class="zh_txt">
            <el-input
              v-model="loginForm.username"
              :placeholder="$t('请输入用户名')"
              name="username"
              type="text"
              auto-complete="on"
            />
          </el-form-item>
          <div class="zh_tips"><span></span></div>
          <el-form-item prop="password" class="zh_txt">
            <el-input
              :type="passwordType"
              v-model="loginForm.password"
              :placeholder="$t('请输入密码')"
              name="password"
              auto-complete="on"
              @keyup.enter.native="handleLogin" />
          </el-form-item>
          <div class="zh_tips"><span></span></div>
          <div class="zh_goPwd">忘记密码请联系管理员</div>

          <el-button type="primary" class="zh_loginBtn" @click.native.prevent="handleLogin">登录</el-button>
          <div class="zh_tips"></div>
          <div class="zh_reg">随时随地远程诊断，<a href="####">申请试用</a></div>
        </el-form>

        <el-dialog :title="$t('login.thirdparty')" :visible.sync="showDialog" append-to-body>
          {{ $t('login.thirdpartyTips') }}
          <social-sign />
        </el-dialog>

      </div>
		</div>
	</div>
	<div class="zh_login_footer">
		<!-- <p>北京中世康恺科技有限公司</p> -->
		<p>京ICP备 17059019号 &copy;2018-2019</p>
	</div>
</div>

</template>

<script>
  import { isvalidUsername } from '@/utils/validate'
  import { setMenuData } from '@/utils/index'
  import LangSelect from '@/components/LangSelect'
  import SocialSign from './socialsignin'
  import Axios from 'axios'
  import qs from 'qs'
  import {loginRequest,checkCode,messageAgain} from '@/api/request'
  export default {
    components: { LangSelect, SocialSign, Axios, qs },
    name: 'login',
    data() {
      // 设置默认显示中文
      this.$store.dispatch('setLanguage', 'zh')
      const validateUsername = (rule, value, callback) => {
        // if (!isvalidUsername(value)) {
        //   callback(new Error('请输入您的用户名'))
        // } else {
        //   callback()
        // }
        if (!isvalidUsername) {
          callback(new Error('请输入用户名'))
        } else {
          callback()
        }
      }
      const validatePassword = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('请输入您的密码'))
        } else {
          callback()
        }
      }
      const validateiphoneNumberd = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('请输入您的手机号'))
        } else {
          callback()
        }
      }
      const validateverificationCode = (rule, value, callback) => {
        if (value.length < 3) {
          callback(new Error('请输入您的验证码'))
        } else {
          callback()
        }
      }
      return {
        isShow: true,
        confirm: 0,
        innerText:'获取验证码',
        loginForm: {
          username: '',
          password: '',
          iphoneNumber:'',
          verificationCode:''
        },
        loginRules: {
          username: [{ required: true, trigger: 'blur', validator: validateUsername,type: 'string' }],
          password: [{ required: true, trigger: 'blur', validator: validatePassword,type: 'string' }],
          iphoneNumber: [{ required: true, trigger: 'blur', validator: validateiphoneNumberd,type: 'string' }],
          verificationCode: [{ required: true, trigger: 'blur', validator: validateverificationCode,type: 'string' }],
        },
        passwordType: 'password',
        loading: false,
        showDialog: false,
        rulse: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur',type: 'string' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur',type: 'string' }
          ],
          iphoneNumber:[
            { required: true, message: '请输入手机号', trigger: 'blur',type: 'string' }
          ],
          verificationCode:[
            { required: true, message: '请输入验证码', trigger: 'blur',type: 'string' }
          ]
        },
        showLogin: false,
        phone:'',
        handleId:''
      }
    },
    methods: {
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = ''
        } else {
          this.passwordType = 'password'
        }
        var v = document.getElementById('ps')

        if (this.isShow) {
          v.type = 'text'
          this.isShow = false
        } else {
          v.type = 'password'
          this.isShow = true
        }
      },
      //重新发送验证码
      getMessageAgain(){
        messageAgain({
          handle_id: this.handleId
        }).then(data => {
          if (data.code == '0000'){
            this.handleId = data.handle_id
            let timer=null;
            clearInterval(timer);//这句话至关重要
            let time=60;
            let that=this;//习惯
            timer=setInterval(function(){
              if(time<=0){
                that.innerText="";
                that.innerText="点击重新发送";
                that.disabled=false;
                clearInterval(timer)
                console.log(timer)
              }else {
                that.disabled=true;
                that.innerText="";
                that.innerText="剩余时间"+(time)+"秒";
                time--;
              }
            },1000);
          }
        }).catch(err =>{
          this.$message.error(err.message);
        })
      },
      _needChangePassword(data) {
        if(data && data['pregPwd'] == 0) {
          this.$message({
            message: '密码复杂度过低，请修改密码！最低8位并且包含大小写字母、数字与特殊字符',
            type: 'error'
          })
          this.$router.push({ path: '/my/setpassword' })
          return true
        }
        return false
      },
      //验证码·
      getCheckCode(){
        var that = this
        this.$refs.loginForm.validate(valid => {
          var formObj = this
          if (valid) {
            console.log(this.handleId)
            checkCode(
              {
                handle_id: this.handleId,
              code: this.loginForm.verificationCode
            }
            ).then(data => {
              if (data.code === '0000') {
                var loginUser = data.info
                  loginUser.avatar = ''
                  loginUser.sessionid = data.sessionid
                  loginUser.isAdmin = data.info.is_admin
                  setMenuData('loginUser', JSON.stringify(loginUser))
                  console.log(33333)
                // 登录成功·
                // 登录成功后，将远程、本地、患者菜单分开
                var localSysPlatMenuArr = []
                var remoteSysPlatMenuArr = []
                var patientSysPlatMenuArr = []
                if (loginUser.permission && loginUser.permission != null) {
                  // 64022a6a4b32abae(本地)  814dc08e8183952d(远程)
                  for (var i = 0; i < loginUser.permission.length; i++) {
                    var upns = loginUser.permission[i]
                    //本院报告
                    if (upns.id === '80ddb7d09ebc44b4') {
                      localSysPlatMenuArr.push(upns)
                    }
                    //远程诊断
                    if (upns.id === '0aa9d7b2fdf7268e') {
                      remoteSysPlatMenuArr.push(upns)
                    }
                    //患者登记
                    if (upns.id === '0eac42ef01de23ff'){
                      patientSysPlatMenuArr.push(upns)
                    }
                  }
                }
                // 将本地菜单或远程菜单或患者登记，放入缓存
                setMenuData('localSysPlatMenuArr', JSON.stringify(localSysPlatMenuArr))
                setMenuData('remoteSysPlatMenuArr', JSON.stringify(remoteSysPlatMenuArr))
                setMenuData('patientSysPlatMenuArr', JSON.stringify(patientSysPlatMenuArr))
                console.log('测试缓存',remoteSysPlatMenuArr)
                // 默认显示本地系统
                var locSign = null
                if ((typeof locSign === 'undefined') || locSign == null) {
                  if (localSysPlatMenuArr.length > 0) {
                    setMenuData('sys_plat_sign', 'local')
                    console.log('router local --> ' + localSysPlatMenuArr[0].url)
                    if(!that._needChangePassword(data))
                      that.$router.push({ path: localSysPlatMenuArr[0].url })
                  } else if (remoteSysPlatMenuArr.length > 0) {
                    setMenuData('sys_plat_sign', 'remote')
                    console.log('router remote --> ' + remoteSysPlatMenuArr[0].url)
                    if(!that._needChangePassword(data))
                      that.$router.push({ path: remoteSysPlatMenuArr[0].url })
                  } else if (patientSysPlatMenuArr.length > 0) {
                    setMenuData('sys_plat_sign', 'patient')
                    console.log('router patient --> ' + patientSysPlatMenuArr[0].url)
                    if(!that._needChangePassword(data))
                      that.$router.push({ path: patientSysPlatMenuArr[0].url })
                  } else {
                    // 无菜单权限
                    that.$message.error('该用户暂无可用权限')
                  }
                }
              } else {
                // 登录失败
                // alert("登录失败");
                console.log('login fail!')
                formObj.loading = false
                formObj.$message({
                  message: '验证码输入错误',
                  type: 'error'
                })
              }
              return true
            }).catch(error => {
              this.$message.error(error.message);
            })
          }else{
            console.log('error submit!!')
            return false
          }
        })
      },
      getTime(){

      },
      handleLogin() {
        var that = this
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            var formObj = this
            loginRequest(
              {
                userName: this.loginForm.username,
                pwd: this.loginForm.password
              }
            ).then(data => {
              if (data.code === '0000') {
                var loginUser = data.info
                if (data.phone !='') {
                  this.confirm = 1
                  this.loginForm.iphoneNumber = data.phone
                  this.handleId = data.handle_id
                  let timer=null;
                  clearInterval(timer);//这句话至关重要
                  let time=60;
                  let that=this;//习惯
                  timer=setInterval(function(){
                    if(time<=0){
                      that.innerText="";
                      that.innerText="点击重新发送";
                      that.disabled=false;
                      clearInterval(timer)
                      console.log(timer)
                    }else {
                      that.disabled=true;
                      that.innerText="";
                      that.innerText="剩余时间"+(time)+"秒";
                      time--;
                    }
                  },1000);
                  that.$message({
                    message: '请输入用户登录验证码 ',
                    type: 'warn'
                  })
                  return
                }
                if (data.sessionid) {
                  loginUser.avatar = ''
                  loginUser.sessionid = data.sessionid
                  loginUser.isAdmin = data.info.is_admin
                  setMenuData('loginUser', JSON.stringify(loginUser))
                  console.log(33333)
                }
                // 登录成功
                // 登录成功后，将远程、本地、患者菜单分开
                var localSysPlatMenuArr = []
                var remoteSysPlatMenuArr = []
                var patientSysPlatMenuArr = []
                if (loginUser.permission && loginUser.permission != null) {
                  // 64022a6a4b32abae(本地)  814dc08e8183952d(远程)
                  for (var i = 0; i < loginUser.permission.length; i++) {
                    var upns = loginUser.permission[i]
                    //本院报告
                    if (upns.id === '80ddb7d09ebc44b4') {
                      localSysPlatMenuArr.push(upns)
                    }
                    //远程诊断
                    if (upns.id === '0aa9d7b2fdf7268e') {
                      remoteSysPlatMenuArr.push(upns)
                    }
                    //患者登记
                    if (upns.id === '0eac42ef01de23ff'){
                      patientSysPlatMenuArr.push(upns)
                    }
                  }
                }
                // 将本地菜单或远程菜单或患者登记，放入缓存
                setMenuData('localSysPlatMenuArr', JSON.stringify(localSysPlatMenuArr))
                setMenuData('remoteSysPlatMenuArr', JSON.stringify(remoteSysPlatMenuArr))
                setMenuData('patientSysPlatMenuArr', JSON.stringify(patientSysPlatMenuArr))
                console.log('测试缓存',remoteSysPlatMenuArr)
                // 默认显示本地系统
                var locSign = null
                if ((typeof locSign === 'undefined') || locSign == null) {
                  if (localSysPlatMenuArr.length > 0) {
                    setMenuData('sys_plat_sign', 'local')
                    console.log('router local --> ' + localSysPlatMenuArr[0].url)
                    if(!that._needChangePassword(data))
                      that.$router.push({ path: localSysPlatMenuArr[0].url })
                  } else if (remoteSysPlatMenuArr.length > 0) {
                    setMenuData('sys_plat_sign', 'remote')
                    console.log('router remote --> ' + remoteSysPlatMenuArr[0].url)
                    if(!that._needChangePassword(data))
                      that.$router.push({ path: remoteSysPlatMenuArr[0].url })
                  } else if (patientSysPlatMenuArr.length > 0) {
                    setMenuData('sys_plat_sign', 'patient')
                    console.log('router patient --> ' + patientSysPlatMenuArr[0].url)
                    if(!that._needChangePassword(data))
                      that.$router.push({ path: patientSysPlatMenuArr[0].url })
                  } else {
                    // 无菜单权限
                    that.$message.error('该用户暂无可用权限')
                  }
                }
              } else {
                // 登录失败
                // alert("登录失败");
                console.log('login fail!')
                if (this.handleId != ''){
                  formObj.loading = false
                }else{
                  formObj.loading = true
                }
                formObj.$message({
                  message: '登录失败，用户名或密码不正确 ',
                  type: 'error'
                })
              }
              return true
            })
              .catch(function(error) {
                that.$message.error(error.message);
              })
            if (this.handleId != ''){
              this.loading = false
              return false
            }else{
              this.loading = true
              return true
            }

          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      afterQRScan() {
        // const hash = window.location.hash.slice(1)
        // const hashObj = getQueryObject(hash)
        // const originUrl = window.location.origin
        // history.replaceState({}, '', originUrl)
        // const codeMap = {
        //   wechat: 'code',
        //   tencent: 'code'
        // }
        // const codeName = hashObj[codeMap[this.auth_type]]
        // if (!codeName) {
        //   alert('第三方登录失败')
        // } else {
        //   this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
        //     this.$router.push({ path: '/' })
        //   })
        // }
      }
    },
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

  $bg:#283443;
  $light_gray:#eee;
  $cursor: #fff;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input{
      color: $cursor;
      &::first-line {
        color: $light_gray;
      }
    }
  }

  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;
      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;
        &:-webkit-autofill {
          -webkit-box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }
    }
    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  background-color: $bg;
  .login-form {
    position: absolute;
    left: 0;
    right: 0;
    width: 520px;
    max-width: 100%;
    padding: 35px 35px 15px 35px;
    margin: 120px auto;
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .title-container {
    position: relative;
    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
    .set-language {
      color: #fff;
      position: absolute;
      top: 5px;
      right: 0px;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .thirdparty-button {
    position: absolute;
    right: 35px;
    bottom: 28px;
  }
}

.zh_login{ width:100%; height:710px; position:fixed; left:0; top:50%; margin-top:-365px; }
.zh_login_logo{ max-width:960px; height:36px; padding:18px 20px 16px; margin:auto; }
.zh_login_logo img{ height:36px; float:left; }
.zh_login_logo div{ float:right; line-height:36px; font-size:1rem; color:#999; }
.zh_login_box{ width:100%; height:370px; padding:100px 0; background:url(../../../static/img/banner.png) no-repeat center #D6E3E9; }
.zh_login_in{ max-width:960px; padding:0 20px; margin:auto; }
.zh_login_in .zh_login_from{ width:280px; float:right; padding:30px; background-color:#FFF; box-shadow:0 0 4px #BBB; border-radius:3px; }
.zh_login_in .zh_login_from .zh_login_h{ margin-bottom:25px; font-size:1.2rem; color:#666; }
.zh_login_in .zh_login_from .zh_txt{ height:36px; font-size:1rem; box-shadow:0 0 3px #EEE; border-radius:0px; margin-bottom:0; margin-top:5px; }
.zh_login_in .zh_login_from .zh_txt input{ width:90%; height:34px; margin-top:1px; line-height:36px; padding:0 5%; box-shadow: none; border:none; font-size:1rem; -webkit-appearance:none; outline:none; }
.zh_login_in .zh_login_from .zh_txt input::placeholder{ color:#BBB; }
.zh_login_in .zh_login_from .zh_tips{ height:15px; line-height:20px; }
.zh_login_in .zh_login_from .zh_tips span{ font-size:.8rem; color:#F00; }
.zh_login_in .zh_login_from .zh_goPwd{ text-align:right; height:30px; text-align:right; font-size:.8rem; color:#AAA; }
.zh_login_in .zh_login_from .zh_loginBtn{ width:100%; height:40px; background-color:#334154; border:none; color:#FFF; font-size:1rem; box-shadow:0 0 4px #334154; border-radius:3px; cursor:pointer; }
.zh_login_in .zh_login_from .zh_reg{ height:40px; line-height:40px; text-align:center; font-size:.9rem; color:#999; background:linear-gradient(#FDFDFD, #F0F0F0) #CCC; border:1px solid #DDD; box-shadow:0 0 3px #EEE; border-radius:3px; }
.zh_login_in .zh_login_from .zh_reg a{ color:#0BD0D8; text-decoration:none; }
.zh_login_in .zh_login_from .zh_reg a:hover{ text-decoration:underline; }
.zh_login_footer{ max-width:960px; margin:15px auto; }
.zh_login_footer p{ font-size:.8rem; color:#999; text-align:center; line-height:180%; }

</style>
