<template>
  <div class="ilogin-layout">
    <div class="input-con login-input-con">
      <template v-if="!isCodeLogin">
        <div :key="'login'" class="input"><input autocomplete="off" v-model="phone" oninput="value=value.replace(/[^\d]/g,'')" maxlength='11' :placeholder="languagelAside.phone.placeholder" type="text"></div>
        <div class="input"><input autocomplete="off"  @keyup.enter="login" v-model="password" :placeholder="languagelAside.password.placeholder" maxlength='16' type="password"></div>
      </template>
      <template v-else>
        <div class="input phone-select" ref="quhaoMenu" >
          <div @click="showSelect=!showSelect">
            <span>{{codeActive[1]}}</span>
            <img :src="`${$cdn}images/quhao-jiantou.png`" >
          </div>
          <ul v-show="showSelect" >
            <li @click="selectItem(item)" v-for="(item,i) in selectCall" :key="i">
              {{language==='en'?item[2]:item[0]}}{{item[1]}}
            </li>
          </ul>
          <input :key="'codelogin'" readonly onfocus="this.removeAttribute('readonly')"  autocomplete="off" v-model="phone" oninput="value=value.replace(/[^\d]/g,'')" maxlength='11' :placeholder="languagelAside.phone.placeholder" type="text">
        </div>
        <div class="verification input codeLogin">
          <input :key="'authCode'" v-model="authCode" autocomplete="off" :placeholder="languagelAside.code.placeholder"  oninput="value=value.replace(/[^\d]/g,'')" maxlength='6'>
          <span v-if="!jishi" @click="getAuthCode">{{languagelAside.code.txt}}</span>
          <span v-else>{{language==='en'?`Resend after ${interTime}s`:`${interTime}s后重新发送`}}</span>
        </div>
      </template>
      <div class="sub-con">
        <div class="remember" :style="{'visibility':!isCodeLogin?'visible':'hidden'}"  @click="rememberMe=~rememberMe">
          <span>
            <img v-if="rememberMe" :src="`${$cdn}images/icon-click.png`" alt="">
          </span>
          <span>{{rememberName[language]}}</span>
        </div>
        <div class="changeCode" @click="changeLoginType">{{loginName[language]}}</div>
      </div>
      <div class="forget-font" @click="$bus.$emit('changName', {
        name: '密码重置',
        enName: 'Password Reset',
        id: 'iforget'
      })">{{forgetName[language]}}</div>
      <div class="login-con">
        <div class="temp-btn" @click="login">{{languagelAside.login}}</div>
        <div class="login-dec">{{languagelAside.loginsub1}}<span @click="$bus.$emit('changName', {
            name: '立即注册',
            enName: 'Sign in',
            id: 'iregister'
          })">{{languagelAside.loginsub2}}</span></div>
      </div>
    </div>
    <!-- <div class="qrcode">
      <img v-if="codeImg" :src="codeImg?`${$serverName}${codeImg}`:''" alt="">
      <div class="qrcode-con">
        <img class="scan-img" :src="`${$cdn}images/icon-qrcode.png`" alt="">
        <div class="login-dec">打开四维看看app扫一扫登录</div>
      </div>
    </div> -->
  </div>
</template>
<script>
import {mapState} from 'vuex'
import selectCall from '@/util/country.js'

import { reg, encodeStr } from '@/util'
import { Base64 } from 'js-base64'

export default {
  props: ['active', 'current'],
  computed: {
    ...mapState({
      language: state => state.language.current,
      langToast: state => state.language.home.toast,
      languagelAside: state => state.language.home.home.loginAside,
      token: state => state.user.token
    })
  },
  data () {
    let remember = localStorage.getItem('remember') || ''
    let username = localStorage.getItem('username')
    let password = localStorage.getItem('password')

    return {
      phone: username,
      password: password,
      rememberMe: remember,
      codeImg: '',
      isFirst: true,
      t1: null,
      showSelect: false,
      codeActive: ['中国', '+86', 'China'],
      selectCall,
      authCode: '',
      isCodeLogin: false,
      interTime: 60,
      jishi: false,
      interl: null,
      rememberName: {
        '中': '记住密码',
        en: 'Remember password'
      },
      forgetName: {
        '中': '忘记密码',
        en: 'Forgot password'
      },
      loginName: {
        '中': '验证码登录',
        en: 'Verification code login'
      }
    }
  },
  mounted () {
    document.addEventListener('click', (e) => {
      if (this.$refs.quhaoMenu) {
        if (!this.$refs.quhaoMenu.contains(e.target)) {
          this.showSelect = false
        }
      }
    })
  },
  watch: {
    active (newVal) {
      setTimeout(() => {
        this.isCodeLogin = false
        this.loginName = {
          '中': '验证码登录',
          en: 'Verification code login'
        }
      }, 700)
    }
  },
  beforeDestroy () {
    clearInterval(this.t1)
    this.t1 = null
  },
  methods: {
    selectItem (item) {
      this.showSelect = false
      this.codeActive = item
    },
    changeLoginType () {
      this.isCodeLogin = !this.isCodeLogin
      this.loginName = !this.isCodeLogin ? {
        '中': '验证码登录',
        en: 'Verification code login'
      } : {
        '中': '账号密码登录',
        en: 'Password login'
      }
    },
    async getAuthCode () {
      if (!reg.phone.test(this.phone)) {
        return
      }
      let resp = await this.$http
        .post('/sso/user/checkUser', {phoneNum: this.phone})

      if (resp.data.code !== 0) {
        return this.$toast.show('warn', this.langToast[resp.data.code])
      }
      let res = await this.$store.dispatch('getAuthCode', {
        phone: this.phone,
        code: Number(this.codeActive[1].substr(1))
      })
      if (res) {
        this.interl && clearInterval(this.interl)
        this.interl = null
        this.jishi = true
        this.interl = setInterval(() => {
          this.interTime--
          if (this.interTime <= 0) {
            this.jishi = false
            this.interTime = 60
            clearInterval(this.interl)
            this.interl = null
          }
        }, 1000)
      }
    },
    async login () {
      let params = ''
      if (this.isCodeLogin) {
        await this.submit()
      } else {
        let check = value => {
          for (let i = 0, len = value.length; i < len; i++) {
            if (!value[i].val) {
              return this.$toast.show('warn', (this.language === 'en' ? value[i].En : value[i].name) + this.langToast['7'])
            }
          }
          return true
        }
        let checkStr = [
          {
            name: '手机',
            En: 'Phone number',
            val: this.phone
          },
          {
            name: '密码',
            En: 'Password',
            val: this.password
          }
        ]
        if (!check(checkStr)) {
          return
        }
        localStorage.setItem('remember', this.rememberMe)
        if (this.rememberMe) {
          localStorage.setItem('username', this.phone)
          localStorage.setItem('password', this.password)
        } else {
          localStorage.setItem('username', '')
          localStorage.setItem('password', '')
        }

        params = {
          phoneNum: this.phone,
          password: encodeStr(Base64.encode(this.password)),
          randomcode: '1234',
          rememberMe: Boolean(this.rememberMe)
        }
        await this.$store.dispatch('login', params)
      }
      clearInterval(this.t1)
      this.t1 = null
      if (this.token) {
        this.$bus.$emit('hideAside')
        this.$bus.$emit('hasLogin')
      }
    },
    async submit () {
      let check = value => {
        for (let i = 0, len = value.length; i < len; i++) {
          if (!value[i].val) {
            return this.$toast.show('warn', (this.language === 'en' ? value[i].En : value[i].name) + this.langToast['7'])
          }
        }
        return true
      }
      let checkStr = [
        {
          name: '手机',
          En: 'Phone number',
          val: this.phone
        },
        {
          name: '验证码',
          En: 'Verification code',
          val: this.authCode
        }
      ]
      if (!check(checkStr)) {
        return
      }
      // let country = Number(this.codeActive[1].substr(1))
      let params = {
        phoneNum: this.phone,
        msgAuthCode: this.authCode
      }

      await this.$store.dispatch('codeLogin', params)
    },
    async getQrCode () {
      let res = await this.$http({
        method: 'get',
        url: '/sso/user/createLoginQrCode'
      })
      this.codeImg = res.data.data.url
      this.isFirst = false
      let params = {
        uuid: res.data.data.uuid
      }
      this.t1 = setInterval(async () => {
        let data = await this.$http({
          method: 'post',
          data: params,
          url: '/sso/user/sendUserInfo'
        })
        let response = data.data
        if (response.code === 0) {
          let {token, childName = '', to = ''} = response.data
          this.$store.commit('saveToken', token)

          if (token && to !== 0) {
            this.$store.commit('DEVICELOGIN', childName)
            this.$bus.$emit('hideAside')
            this.$router.replace({name: 'scene', query: {first: true}})
          } else {
            this.$bus.$emit('hideAside')
            this.$bus.$emit('hasLogin')
            this.$store.commit('DEVICELOGIN', '')
            this.$store.dispatch('getInfo', {url: '/user/getUserInfo', name: 'info'})
            this.$store.dispatch('getCart')
          }
          return false
        }
      }, 3000)
    }
  }
}
</script>

<style lang="scss" scoped>
  @import './style.scss';
</style>
