<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">
      <div
        class="mobile-prefix"
        @click.stop="$emit('changeParams', { isShowMobilePrefix: !viewParams.isShowMobilePrefix })">
        <span class="selected-value">{{ mobilePrefix }}</span>
        <i class="iconfont icon-xiala1"/>
      </div>
      <input
        v-model="mobile"
        :placeholder="$t('login_register.placeholder_mobile')"
        readonly="readonly"
        onfocus="javascript:this.removeAttribute('readonly');"
        type="text"
        class="hl-input">
      <ul
        v-if="viewParams.isShowMobilePrefix"
        class="mobile-prefix-list">
        <li
          v-for="(item, index) in mobilePrefixArr"
          :key="index"
          class="prefix-item"
          @click="handleSelectPrefix(item)">
          {{ `(${item.code}) ${item.name}` }}
        </li>
      </ul>
    </div>
    <div class="form-item">
      <input
        v-model="smsCode"
        :placeholder="$t('login_register.placeholder_sms_code')"
        readonly="readonly"
        onfocus="javascript:this.removeAttribute('readonly');"
        maxlength="6"
        type="text"
        class="hl-input">
      <span
        class="get-code"
        @click="getSmsCode">
        {{ 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', 'FindByEmail')">{{ $t('login_register.find_pwd_by_email') }}</span>
    </div>
  </div>
</template>

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

const defaultPrefix = {
  cn: {
    code: '+86',
    id: '317',
    name: '中国'
  },
  en: {
    code: '+86',
    id: '317',
    name: 'China'
  }
}

export default {
  props: {
    viewParams: {
      type: Object,
      default: () => ({
        isShowMobilePrefix: false
      })
    }
  },
  data() {
    return {
      mobilePrefixObj: null,
      mobilePrefix: '',
      mobile: '',
      smsCode: '',
      password: '',
      showPassword: false,
      codeTimer: null,
      codeText: this.$t('login_register.btn_get_code'),
      btnLoginText: this.$t('login_register.btn_login'),
      tipMsg: {
        type: 'error',
        msg: ''
      },
      tipMsgStatus: false,
      dxLoaded: false,
      dxStatus: false,
      security_code: '',
      isLoading: false
    }
  },
  computed: {
    ...mapState(['locale', 'mobilePrefixArr'])
  },
  watch: {
    dxStatus(val) {
      // 验证成功
      if (val) {
        this.getSmsCode()
      }
    }
  },
  created() {
    // 默认china
    this.handleSelectPrefix(defaultPrefix[this.locale] || {})
    if (!this.mobilePrefixArr.length) {
      this.loadMobilePrefixData()
    }
  },
  destroyed() {
    this.clearTimer()
  },
  methods: {
    showTip(data) {
      this.tipMsg = { ...this.tipMsg, ...data }
      this.tipMsgStatus = true
    },
    handleSelectPrefix({ code, id, name }) {
      this.mobilePrefixObj = { code, id, name }
      this.mobilePrefix = `(${code}) ${name}`
      this.$emit('changeParams', { isShowMobilePrefix: false })
    },
    async loadMobilePrefixData() {
      try {
        const { code, data } = await this.$axios.$post(php_api_common_address, {
          range: 'B',
          prefix: 1
        })
        if (code || !data.length) return

        const prefixsArr = data.reduce((res, cur) => res.concat(cur.list), [])
        this.$store.commit('SET_MOBILE_PREFIX_ARR', prefixsArr)
      } catch (error) {}
    },
    checkMobile() {
      if (!myValidator.checkMobile(this.mobile)) {
        this.showTip({ msg: this.$t('login_register.check_phone') })
        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 getSmsCode() {
      if (this.codeTimer) return
      if (!this.checkMobile()) return

      this.tipMsgStatus = false

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

      const params = {
        countryId: this.mobilePrefixObj.id,
        mobile: this.mobile,
        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.checkMobile() || !this.checkCode() || !this.checkPwd()) return

      const params = {
        countryId: this.mobilePrefixObj.id,
        mobile: this.mobile,
        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>
