<template>
  <div class="page">
    <div class="header flex">
      <div class="back">
        <backIcon/>
      </div>
    </div>
    <div class="title">
      <!-- 忘记您的密码了吗? -->
      {{ $t('login.l18') }}
    </div>
    <div class="tip">
      <!-- 没关系, 极度帮您找回来. -->
      {{ $t('login.l19') }}
    </div>
    <div class="tabs flex">
      <div class="tab" :class="{'active': type == 1}" @click="type = 1">
        <!-- 手机号码 -->
        {{ $t('login.l-p') }}
        <div class="line" v-if="type == 1"></div>
      </div>
      <div class="tab" :class="{'active': type == 2}" @click="type = 2">
        <!-- 邮箱 -->
        {{ $t('setting.l11') }}
        <div class="line" v-if="type == 2"></div>
      </div>
    </div>
    <el-form autocomplete="off" class="login-box" :rules="rules" :model="form" ref="form">
      <el-form-item prop="account" v-if="type == 1" :class="{focus: accountFocus}">
        <!-- 请输入手机号码 -->
        <el-input autocomplete="off" @focus="accountFocus = true" @blur="accountFocus = false" :placeholder="$t('login.l1')" type="number" v-model="form.account">
          <template slot="prepend">
            <div class="area-box" @click="countryShow">
              +{{ phoneCountry.area_code }}<van-icon name="arrow-down" />
            </div>
          </template>
          <div slot="suffix" class="suffix">
            <van-icon name="clear" @click="form.account = ''" v-if="form.account" />
          </div>
        </el-input>
      </el-form-item>
      <!-- 请输入邮箱地址 -->
      <el-autocomplete
        popper-class="email-autocomplete"
        :class="{focus: accountFocus}"
        @focus="accountFocus = true"
        @blur="accountFocus = false"
        autocomplete="off"
        :debounce="0"
        ref="email"
        v-if="type == 2"
        v-model="form.account"
        :fetch-suggestions="querySearch"
        :placeholder="$t('login.l2')">
        <template slot-scope="{ item }">
          <div class="email-li flex" @click.stop="handleSelect(item)">
            <div class="query">{{ getAccoutName() }}</div>
            <div>@</div>
            <div>{{ item }}</div>
          </div>
        </template>
        <div slot="suffix" class="suffix">
          <van-icon name="clear" @click="clearEmail" v-if="form.account" />
        </div>
      </el-autocomplete>
      <el-form-item prop="verifyCode" :class="{focus: codeFocus}">
        <div class="code-box flex">
          <!-- 请输入验证码 -->
          <el-input autocomplete="off" @focus="codeFocus = true" @blur="codeFocus = false" type="number" :placeholder="$t('register.l12')" v-model="form.verifyCode">
          </el-input>
          <div class="send" @click="getVerifyCode">{{ sendText }}{{ isNaN(Number(sendText)) ? '' : 's' }}</div>
        </div>
      </el-form-item>
      <!-- 请设置密码 -->
      <el-autocomplete
        popper-class="password-autocomplete"
        :readonly="readonly"
        :class="{focus: passwordFocus}"
        @focus="passwordFocus = true"
        @blur="passwordFocus = false"
        autocomplete="off"
        placement="top-start"
        :debounce="0"
        :type="showPassword"
        ref="password"
        v-model="form.password"
        :fetch-suggestions="querySearch1"
        :placeholder="$t('register.l2')">
        <template>
          <div class="rule-box" @click.stop="">
            <div class="rule flex" :class="{active: rule1}">
              <img class="check" v-show="!rule1" src="/img/login/check.png" alt="极度证券">
              <img class="check" v-show="rule1" src="/img/login/checked.png" alt="极度证券">
              <div>
                <!-- 8-20个字符 -->
                {{ $t('register.l17') }}
              </div>
            </div>
            <div class="rule flex" :class="{active: rule2}">
              <img class="check" v-show="!rule2" src="/img/login/check.png" alt="极度证券">
              <img class="check" v-show="rule2" src="/img/login/checked.png" alt="极度证券">
              <div>
                <!-- 至少1个数字 -->
                {{ $t('register.l18') }}
              </div>
            </div>
            <div class="rule flex" :class="{active: rule3}">
              <img class="check" v-show="!rule3" src="/img/login/check.png" alt="极度证券">
              <img class="check" v-show="rule3" src="/img/login/checked.png" alt="极度证券">
              <div>
                <!-- 至少1个字母 -->
                {{ $t('register.l19') }}
              </div>
            </div>
          </div>
        </template>
        <div slot="suffix" class="suffix">
          <img class="eye" @click="showPassword = 'text'" v-show="showPassword == 'password'" src="/img/icon/eye.png?1" alt="极度证券">
          <img class="eye" @click="showPassword = 'password'" v-show="showPassword == 'text'" src="/img/icon/eye_no.png?1" alt="极度证券">
        </div>
      </el-autocomplete>
    </el-form>
    <div class="btn-box" @click="submit">
      <!-- 重置密码 -->
      {{ $t('login.l11') }}
    </div>
    <selectCountry :val="phoneCountry" ref="country" @back="selectCountryBack"/>
  </div>
</template>
<script>
import { emailList, emailReg } from "@/utils/config";
import { recoverPassword, getVerifyCode } from "@/api/login";
import { setSession } from '@/utils/sessionStorage'
import selectCountry from "@/components/selectCountry";
export default {
  components: {
    selectCountry
  },
  data() {
    return {
      form: {
        account: "",
        phone: "",
        password: "",
        verifyCode: '',
      },
      type: '1',
      showPassword: 'password',
      loading: false,
      sendText: this.$t('register.l11'),
      sendDisable: false,
      timer: null,
      dialogVisible: false,
      readonly: true,
      accountFocus: false,
      passwordFocus: false,
      codeFocus: false,
      emailList: emailList,
      phoneCountry: {
        "name": "China (中国)",
        "code": "cn",
        "area_code": "86"
      },
      rules: {
      },
    };
  },
  computed: {
    rule1() {
      return /^.{8,20}$/.test(this.form.password.trim())
    },
    rule2() {
      return /\d/.test(this.form.password.trim())
    },
    rule3() {
      return /[a-zA-Z]/.test(this.form.password.trim())
    }
  },
  watch: {
    type() {
      this.form.account = ''
      clearInterval(this.timer)
      this.sendText = this.$t('register.l11')
      this.sendDisable = false
      this.readonly = true
      setTimeout(() => {
        this.readonly = false
      }, 200)
    }
  },
  mounted() {
    setTimeout(() => {
      this.readonly = false
    }, 200)
  },
  methods: {
    submit() {
      if (this.loading) {
        return;
      }
      if (this.type == 1) {
        if (!this.form.account.trim()) {
          // 请输入手机号码
          this.$toast(this.$t('login.l1'));
          return
        }
      }
      if (this.type == 2) {
        if (!this.form.account.trim()) {
          // 请输入邮箱地址
          this.$toast(this.$t('login.l2'));
          return
        }
        if (!emailReg.test(this.form.account.trim())) {
          // 邮箱格式不正确
          this.$toast(this.$t('login.email-reg'));
          return
        }
      }
      if (!this.form.verifyCode.trim()) {
        // 请输入验证码
        this.$toast(this.$t('register.l12'));
        return
      }
      if (!this.form.password.trim()) {
        // 请输入密码
        this.$toast(this.$t('login.l3'));
        return
      }
      var passwordReg = /^(?=.*[a-zA-Z])(?=.*\d).{8,20}$/;
      if (!passwordReg.test(this.form.password.trim())) {
        // 8-20位字符, 必须包括数字和字母
        this.$toast(this.$t('login.password-reg'));
        return
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loading = true;
          recoverPassword({
            password: this.form.password,
            verifyCode: this.form.verifyCode,
          })
            .then((res) => {
              this.$notify({
                // message: '密码重置成功',
                message: this.$t('login.l15'),
                type: 'success'
              });
              this.$router.replace('/login')
            })
            .finally(() => {
              this.loading = false;
            })
            .catch(() => {});
        } else {
          return false;
        }
      });
    },
    getVerifyCode() {
      if (this.sendDisable) {
        return
      }
      var account = ''
      if (this.type == 1) {
        if (!this.form.account.trim()) {
          // 请输入手机号码
          this.$toast(this.$t('login.l1'));
          return
        }
        account = this.phoneCountry.area_code + this.form.account.trim()
      }
      if (this.type == 2) {
        if (!this.form.account.trim()) {
          // 请输入邮箱地址
          this.$toast(this.$t('login.l2'));
          return
        }
        if (!emailReg.test(this.form.account.trim())) {
          // 邮箱格式不正确
          this.$toast(this.$t('login.email-reg'));
          return
        }
        account = this.form.account.trim()
      }
      this.sendDisable = true
      getVerifyCode({
        account,
        type: this.type == 1 ? 'phone' : 'email',
        action: 'recoverPassword',
        language: this.language
      })
        .then((res) => {
          this.timerStart()
          setSession('phoneToken', res.token)
        })
        .catch(() => {
          this.sendDisable = false
        })
    },
    timerStart() {
      this.sendText = 60
      this.timer = setInterval(() => {
        if (this.sendText <= 1) {
          this.sendText = this.$t('register.l11')
          this.sendDisable = false
          clearInterval(this.timer)
          this.timer = null
        } else {
          this.sendText--
        }
      }, 1000)
    },
    countryShow() {
      this.$refs['country'].reset()
    },
    selectCountryBack(val) {
      this.phoneCountry = val
    },
    querySearch(queryString, cb) {
      if (!queryString.trim()) {
        cb([])
        return
      }
      var restaurants = this.emailList;
      var results = restaurants.filter(item => {
        var str = (this.form.account.split('@')[1]) || '';
        if (item.indexOf(str) !== -1 && str != item) {
          return {value: item}
        }
        return false
      })
      cb(results)
    },
    querySearch1(queryString, cb) {
      cb([{}])
    },
    clearEmail() {
      this.form.account = ''
      this.$nextTick(() => {
        this.$refs['email'].focus()
      })
    },
    handleSelect(item) {
      var str = (this.form.account.split('@')[0]) || '';
      this.form.account = str + '@' + item
      this.$refs['email'].focus()
    },
    getAccoutName() {
      var str = (this.form.account.split('@')[0]) || '';
      return str
    }
  },
};
</script>
<style lang="less" scoped>
.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 2;
  padding: 11px 20px 10px 15px;
  font-size: 16px;
  color: #242424;
  background-color: #fff;
}
.page {
  padding: 78px 22px 38px;
  position: relative;
}
.title {
  font-size: 28px;
  font-weight: 600;
  line-height: 33px;
  padding-bottom: 12px;
}
.tip {
  font-size: 16px;
  color: #6C6C6C;
  padding-bottom: 24px;
}
.tabs {
  font-size: 16px;
  color: #6C6C6C;
  column-gap: 30px;
  .tab {
    position: relative;
    cursor: pointer;
    padding: 13px 0;
    &.active {
      font-weight: 600;
      color: #000;
    }
  }
  .line {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 2px;
    background-color: #000;
  }
}
.area-box {
  width: 70px;
  font-size: 16px;
  line-height: 1;
  text-align: center;
  color: #000;
  border-right: 1px solid #B9B9B9;
}
.code-box {
  padding-right: 4px;
  .el-input {
    flex: 1;
  }
  .send {
    min-width: 96px;
    line-height: 38px;
    text-align: center;
    background: #FFFFFF;
    box-shadow: 0px 2px 5px 0px rgba(188,192,193,0.31);
    border-radius: 6px;
    color: #000000;
    cursor: pointer;
    font-size: 14px;
    padding: 0 6px;
  }
}
.suffix {
  height: 46px;
  cursor: pointer;
  display: flex;
  align-items: center;
  padding-right: 11px;
}
.van-icon {
  color: #000;
  font-size: 16px;
  cursor: pointer;
}
.eye {
  display: block;
  width: 20px;
}
.rule-box {
  padding: 0 16px;
  .rule {
    column-gap: 6px;
    &.active {
      color: #000;
    }
  }
  .check {
    width: 14px;
  }
}
.btn-box {
  margin-top: 43px;
  cursor: pointer;
  color: #FEFFFF;
  background: #000000;
  border-radius: 6px;
  line-height: 44px;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
}
</style>