<template>
  <div>
    <p class="form-title">{{ $t('login_register.find_password') }}</p>
    <p
      v-show="tipMsgStatus"
      :class="`form-msg ${tipMsg.type}`">
      <i :class="`iconfont ${tipMsg.type == 'error' ? 'icon-Shapex' : 'icon-all_tips'}`"/>{{ tipMsg.msg }}
    </p>
    <div class="form-item">
      <input
        v-model="email"
        :placeholder="$t('login_register.placeholder_email')"
        readonly="readonly"
        onfocus="javascript:this.removeAttribute('readonly');"
        type="text"
        class="hl-input"
        @input="handleListenEmailInput"
        @focus="handleListenEmailInput"
        @blur="handleBlurEmailInput"
        @keyup.enter="handleEmailInputKey('enter')"
        @keyup.up="handleEmailInputKey('up')"
        @keyup.down="handleEmailInputKey('down')">
      <ul
        v-if="emailArr.length"
        class="email-tip-list">
        <li
          v-for="(item,index) in emailArr"
          :key="index"
          :class="{'email-item':true,'active':item.isActive}"
          @mousedown="handleSelectEmail(index)">{{ item.email }}</li>
      </ul>
    </div>
    <div class="form-item">
      <input
        v-model="smsCode"
        :placeholder="$t('login_register.placeholder_email_code')"
        readonly="readonly"
        onfocus="javascript:this.removeAttribute('readonly');"
        maxlength="6"
        type="text"
        class="hl-input">
      <span
        class="get-code"
        @click="getCode">
        {{ codeText }}
      </span>
    </div>
    <div class="form-item">
      <input
        v-model="password"
        :type="showPassword ? 'text' : 'password'"
        :placeholder="$t('login_register.pwd_rules')"
        readonly="readonly"
        onfocus="javascript:this.removeAttribute('readonly');"
        class="hl-input">
      <i
        :class="`pwd-eye iconfont ${showPassword ? 'icon-zhengyan' : 'icon-biyan'}`"
        @click="showPassword = !showPassword"/>
    </div>
    <div class="form-item">
      <button
        :loading="isLoading"
        class="form-button"
        @click="commit">{{ btnLoginText }}</button>
    </div>
    <div class="skip-item">
      <span
        class="skip-button"
        @click="$emit('handleSkipView', 'FindBySms')">{{ $t('login_register.find_pwd_by_mobile') }}</span>
    </div>
  </div>
</template>

<script>
import {
  php_api_user_verification,
  php_api_user_find_pwd
} from '~/common/apis.js'
import { myValidator } from '~/common/utils.js'

export default {
  data() {
    return {
      emailSuffixArr: [
        '@qq.com',
        '@gmail.com',
        '@163.com',
        '@yahoo.com',
        '@hotmail.com'
      ],
      emailArr: [],
      email: '',
      smsCode: '',
      password: '',
      showPassword: false,
      smsTimer: null,
      countTime: 60,
      codeText: this.$t('login_register.btn_get_code'),
      btnLoginText: this.$t('login_register.login_ok'),
      tipMsg: {
        type: 'error',
        msg: ''
      },
      tipMsgStatus: false,
      dxLoaded: false,
      dxStatus: false,
      security_code: '',
      isLoading: false
    }
  },
  watch: {
    dxStatus(val) {
      // 验证成功
      if (val) {
        this.getCode()
      }
    }
  },
  created() {},
  destroyed() {
    this.clearTimer()
  },
  methods: {
    showTip(data) {
      this.tipMsg = { ...this.tipMsg, ...data }
      this.tipMsgStatus = true
    },
    handleListenEmailInput() {
      if (this.email.trim().length === 0) {
        this.emailArr = []
        return false
      }
      if (this.email.indexOf('@') !== -1) {
        let emailA = this.email.split('@')[0]
        if (emailA.length > 0) {
          let emailArr = []
          this.emailSuffixArr.forEach((val, i, arr) => {
            let tmp = {}
            tmp.email = `${emailA}${val}`
            if (this.email === tmp.email) {
              tmp.isActive = true
            } else {
              tmp.isActive = false
            }
            emailArr.push(tmp)
          })
          this.emailArr = emailArr
        } else {
          this.emailArr = []
        }
      } else {
        let emailArr = []
        this.emailSuffixArr.forEach((val, i, arr) => {
          let tmp = {
            email: `${this.email}${val}`,
            isActive: false
          }
          emailArr.push(tmp)
        })
        this.emailArr = emailArr
      }
    },
    handleBlurEmailInput() {
      this.emailArr = []
    },
    handleEmailInputKey(which) {
      switch (which) {
        case 'enter':
          this.emailArr.some((val, i, arr) => {
            if (val.isActive) {
              this.email = val.email
              return true
            }
          })
          this.emailArr = []
          break
        case 'up':
          this.keySelectEmail(which)
          break
        case 'down':
          this.keySelectEmail(which)
          break
        default:
          break
      }
    },
    handleSelectEmail(index) {
      this.email = this.emailArr[index].email
      this.emailArr = []
    },
    keySelectEmail(which) {
      let count = this.emailArr.length
      if (count === 0) {
        return false
      }
      let last = count - 1
      let curIndex = -1
      this.emailArr.some((val, i, arr) => {
        if (val.isActive) {
          curIndex = i
          return true
        }
      })
      if (which === 'up') {
        if (curIndex === -1) {
          curIndex = 0
        } else if (curIndex === 0) {
          curIndex = last
        } else {
          --curIndex
        }
      } else if (which === 'down') {
        if (curIndex === -1) {
          curIndex = 0
        } else if (curIndex === last) {
          curIndex = 0
        } else {
          ++curIndex
        }
      }
      let emailArr = []
      this.emailArr.forEach((val, i, arr) => {
        if (curIndex === i) {
          val.isActive = true
        } else {
          val.isActive = false
        }
        emailArr.push({ ...val })
      })
      this.emailArr = emailArr
    },
    checkEmail() {
      if (!myValidator.checkEmail(this.email)) {
        this.showTip({ msg: this.$t('login_register.check_email') })
        return false
      }
      return true
    },
    checkCode() {
      if (!myValidator.checkCode(this.smsCode)) {
        this.showTip({ msg: this.$t('login_register.check_sms_code') })
        return false
      }
      return true
    },
    checkPwd() {
      if (!myValidator.checkPwd(this.password)) {
        this.showTip({ msg: this.$t('login_register.pwd_rules') })
        return false
      }
      return true
    },
    bindDxEvent() {
      _dx.hooliCaptcha.on('verifySuccess', security_code => {
        this.security_code = security_code
        this.dxStatus = true
      })
    },
    getDxCode() {
      if (_dx) {
        if (!this.dxLoaded) {
          this.dxLoaded = true
          this.bindDxEvent()
        }
        _dx.hooliCaptcha.reload()
        _dx.hooliCaptcha.show()
      } else {
        // dx加载失败 直接跳过验证
        this.dxStatus = true
      }
    },
    async getCode() {
      if (this.codeTimer) return
      if (!this.checkEmail()) return

      this.tipMsgStatus = false

      if (!this.dxStatus) {
        this.getDxCode()
        return
      }

      const params = {
        email: this.email,
        token: this.security_code,
        status: '2'
      }
      try {
        const { code, data, msg } = await this.$axios.$post(
          php_api_user_verification,
          params
        )
        if (code) {
          this.showTip({ msg: msg || this.$t('login_register.network_wrong') })
        } else {
          this.dealCountDown()
        }
      } catch (error) {
        this.showTip({ msg: msg || this.$t('login_register.network_wrong') })
      }
    },
    clearTimer() {
      if (this.codeTimer) {
        window.clearTimeout(this.codeTimer)
        this.codeTimer = null
      }
    },
    dealCountDown() {
      let times = 60
      let countTime = () => {
        if (times > 0) {
          this.codeText = `${times}s`
          times--
          this.codeTimer = setTimeout(countTime, 1000)
        } else {
          this.clearTimer()
          this.codeText = this.$t('login_register.get_code_again')
          this.codeBtnDisable = false
          this.dxStatus = false
        }
      }
      countTime()
    },
    async commit() {
      if (!this.checkEmail() || !this.checkCode() || !this.checkPwd()) return

      const params = {
        email: this.email,
        code: this.smsCode,
        pwd: this.password
      }
      this.isLoading = true
      try {
        const { code, data, msg } = await this.$axios.$post(
          php_api_user_find_pwd,
          params
        )
        if (!code) {
          this.btnLoginText = this.$t('login_register.find_success')
          this.$Utils.MyCookie.setCookie(
            'loginUserInfo',
            encodeURIComponent(JSON.stringify(data)),
            7,
            true
          )
          location.reload()
        } else {
          this.isLoading = false
          this.showTip({ msg: msg || this.$t('login_register.network_wrong') })
        }
      } catch (error) {
        this.isLoading = false
        this.showTip({ msg: this.$t('login_register.network_wrong') })
      }
    }
  }
}
</script>
