<template>
  <div class="aui-wrapper aui-page__login">
    <div class="aui-content__wrapper">
      <el-row>
        <el-col class="aui-content" :span="24" :offset="5">
          <!--<div class="login-header">-->
            <!--<h2 class="login-brand">{{ $t('brand.lg') }}</h2>-->
          <!--</div>-->
          <div class="login-body">
            <!--<h3 class="login-title">{{ $t('login.title') }}</h3>-->
            <img src="~@/assets/img/logo.png" style="width:50%;margin-bottom: 40px;">
            <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" status-icon>
              <el-form-item v-if="showUsername" prop="username">
                <el-input v-model="dataForm.username" :placeholder="$t('login.username')">
                  <span slot="prefix" class="el-input__icon">
                    <svg class="icon-svg" aria-hidden="true"><use xlink:href="#icon-user"></use></svg>
                  </span>
                </el-input>
              </el-form-item>
              <el-form-item v-if="showOnPhone" prop="phoneNumber">
                <el-input  v-model="dataForm.phoneNumber" placeholder="请输入手机号">
                </el-input>
              </el-form-item>
              <el-form-item v-if="showUsername" prop="password">
                <el-input v-model="dataForm.password" type="password" show-password :placeholder="$t('login.password')">
                  <span slot="prefix" class="el-input__icon">
                    <svg class="icon-svg" aria-hidden="true"><use xlink:href="#icon-lock"></use></svg>
                  </span>
                </el-input>
              </el-form-item>
              <el-form-item prop="validCode">
                <el-row :gutter="20">
                  <el-col :span="14">
                    <el-input v-model="dataForm.validCode" :placeholder="$t('login.captcha')">
                      <span slot="prefix" class="el-input__icon">
                        <svg class="icon-svg" aria-hidden="true"><use xlink:href="#icon-safetycertificate"></use></svg>
                      </span>
                    </el-input>
                  </el-col>
                  <el-col :span="10" class="login-captcha">
                    <img :src="captchaPath" @click="getCaptcha()">
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item v-if="showOnPhone" prop="validsmsCode" >
                <el-input v-model="dataForm.validsmsCode"  placeholder="请输入验证码">
                  <template #append> <div class="verView" @click="verCodeClick()">{{codeTitle}}</div></template>        
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="dataFormSubmitHandle()" class="w-percent-100">{{ $t('login.title') }}</el-button>
              </el-form-item>
              <div class="do">
                <div v-if="showOnPhone" class="phone" @click="onUserName()">用户名登录</div>
                <div v-if="showUsername" class="phone" @click="onPone()">手机号登录</div>
                <!-- <a href="../../../onenettest.html"  class="phone" > 证书登录</a> -->
                <div  class="phone" @click="CertLogin()">证书登录</div>
              </div>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import debounce from 'lodash/debounce'
import { messages } from '@/i18n'
import { getUUID } from '@/utils'
import {
  IsAddonAvailable,
  GetSignAndToken,
  GetSignAndTokenCb,
} from './onenethelper'
export default {
  data () {
    return {
      i18nMessages: messages,
      showOnPhone: false,
      showUsername: true,
      show:false,
      codeTitle:"获取验证码",
      time_count:60,
      timer:null,
      captchaPath: '',
      dataForm: {
        username: '',
        password: '',
        deviceId: '',
        validCode: '',
        phoneNumber:'',
        validsmsCode:'',
      }
    }
  },
  computed: {
    dataRule () {
      return {
        username: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        password: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        validCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
        validsmsCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入手机号码', trigger: 'blur' }
        ],
      }
    }
  },
  created () {
    this.getCaptcha()
  },
  methods: {
    // 获取验证码
    getCaptcha () {
      this.dataForm.deviceId = getUUID()
      this.captchaPath = `${window.SITE_CONFIG['apiURL']}/validata/code/${this.dataForm.deviceId}`
    },
    // 获取手机验证码
    verCodeClick () {
      if(!this.show){
      this.$http.post('/idaas/sso/smsvalidate',{
        phoneNumber:this.dataForm.phoneNumber,
        deviceId:this.dataForm.deviceId,
        validCode:this.dataForm.validCode,
      }).then(({ data: res }) => {
          // this.show = true
            if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              if(res.code==0) {
                if(!this.timer) {
                  this.timer = setInterval ( () => {
                    if(this.time_count>0) {
                    this.time_count--
                    this.codeTitle = this.time_count +'秒后重新获取'
                  }
                  else {
                    this.codeTitle = '获取验证码'
                    clearInterval(this.timer)
                    this.timer = null
                    this.time_count = 60
                    this.show = false
                  }
                  },1000)
                 
                }
              }
        }).catch(() => {})
    }
    },
    onUserName () {
      this.showUsername = true
      this.showOnPhone = false
    },
    // 手机号登录
    onPone () {
      this.showOnPhone = true
      this.showUsername = false
    },
    CertLogin () {
      if(IsAddonAvailable()) {
              this.$http.post('/webservice/generatorchallenge', {}).then(({ data: res }) => {
          if (res.data.code ==0) {
             GetSignAndToken(res.data.msg)
              if(GetSignAndTokenCb()) {
                      this.$http.post('/webservice/verifyIdentityTicket', {
                        challenge: res.data.msg,//随机挑战数
                        identityTicket:GetSignAndTokenCb(),//组合令牌数据
                        appServerID:'0'//服务器ID
                      }).then(({ data: res }) => {
                          if (res.expiresIn==7200) { 
                               // 发送用户登录成功MQ消息
                                this.$http.get('/mq/user/login').then(({ data: res }) => {
                                  if (res.code !== 0) {
                                    return this.$message.error(res.msg)
                                  }
                                }).catch(() => {})
                            Cookies.set('token', res.sessionToken)
                            this.$router.replace({ name: 'home' })
                          }
                      })
              }
            // form1.T8.value = res.data.msg//获取随机挑战数
          }
        })

      }
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        if(this.showOnPhone) {
          this.$http.post('idaas/sso/smslogin', {
            deviceId:this.dataForm.deviceId,
            phoneNumber:this.dataForm.phoneNumber,
            validCode:this.dataForm.validCode,
            validsmsCode:this.dataForm.validsmsCode,
          })
          .then(({ data: res }) => {
          if (res.code !== 0) {
            this.getCaptcha()
            return this.$message.error(res.msg)
          }
          Cookies.set('token', res.sessionToken)
          // 发送用户登录成功MQ消息
           this.$http.get('/mq/user/login').then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
          }).catch(() => {})
          if(localStorage.getItem('pathCopyshow') && localStorage.getItem('pathCopy')) {
            this.$router.push(localStorage.getItem('pathCopy'))
          }
          else{
            this.$router.replace({ name: 'home' })
          }
        }).catch(() => {})
          
        }else {
          this.$http.post('/idaas/sso/login', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            this.getCaptcha()
            return this.$message.error(res.msg)
          }
          Cookies.set('token', res.sessionToken)
          
          // 发送用户登录成功MQ消息
          this.$http.get('/mq/user/login').then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
          }).catch(() => {})
          if(localStorage.getItem('pathCopyshow') && localStorage.getItem('pathCopy')) {
            this.$router.push(localStorage.getItem('pathCopy'))
          }
          else{
            this.$router.replace({ name: 'home' })
          }
        }).catch(() => {})
        }
       
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
<style scoped>
.aui-page__login .aui-content{
  padding: 0!important;
}
.do {
            margin-top: 24px;
            display: flex;
            align-items: center;
            justify-content: space-between;
          
}
.cert {
              cursor: pointer;
              display: flex;
              align-items: center;
              font-size: 16px;
              color: #3E8EF7;
              margin-right: 24px;
}
.phone {
              font-family: MicrosoftYaHei;
              font-size: 16px;
              font-weight: normal;
              font-stretch: normal;
              letter-spacing: 0px;
              color: #3E8EF7;
              cursor: pointer;
              margin-left: 24px;
            }
.verView {
  color: #3E8EF7;
 cursor: pointer;
}
</style>