<template>
  <div class="page" v-loading.body.fullscreen="fullscreenLoading" element-loading-background="rgba(255, 255, 255, 0)">
    <div class="header flex">
      <div class="back">
        <backIcon/>
      </div>
      <!-- 登录 -->
      <div class="href" @click="$router.push('/login')">{{ $t('login.l') }}</div>
    </div>
    <div class="title">
      <!-- 欢迎来到极度证券 -->
      {{ $t('login.l17') }}
    </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" type="number" @focus="codeFocus = true" @blur="codeFocus = false" :placeholder="type == 1 ? $t('register.l') : $t('register.l1')" 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>
      <div class="label" @click="codeShow = !codeShow">
        <!-- 邀请码(可选) -->
        {{ $t('register.l15') }}<i v-if="!recommendCodeDisabled" class="el-icon-caret-bottom" :class="{active: codeShow}"></i></div>
      <el-form-item v-if="codeShow || recommendCodeDisabled" :class="{focus: recommendFocus}">
        <!-- 请输入邀请码(选填) -->
        <el-input :disabled="recommendCodeDisabled" @focus="recommendFocus = true" @blur="recommendFocus = false" autocomplete="off" :placeholder="$t('register.l3')" v-model="form.recommend_code">
        </el-input>
      </el-form-item>
      <!-- <el-form-item prop="password1">
        <el-input placeholder="再次确认密码" :type="showPassword1" v-model="form.password1">
          <div slot="suffix" class="suffix">
           <img class="eye" @click="showPassword1 = 'text'" v-show="showPassword1 == 'password'" src="/img/icon/eye.png" alt="极度证券">
           <img class="eye" @click="showPassword1 = 'password'" v-show="showPassword1 == 'text'" src="/img/icon/eye_no.png" alt="极度证券">
          </div>
        </el-input>
      </el-form-item> -->
    </el-form>
    <div class="btn-box" @click="submit">
      <!-- 创建账号 -->
      {{ $t('register.l14') }}
    </div>
    <div class="href1" @click="checked = !checked">
      <img v-show="!checked" class="check" src="/img/auth/check.png" alt="极度证券">
      <img v-show="checked" class="check" src="/img/auth/checked.png" alt="极度证券">
      <div>
        {{ $t('register.l6') }}<span class="active" @click.stop="$router.push('/statement/user')">{{ $t('register.l7') }}</span>{{ $t('register.l8') }}<span class="active" @click.stop="$router.push('/statement/privacy')">{{ $t('register.l9') }}</span>
      </div>
        <!-- 我已阅读并同意极度证券的<span class="active" @click="$router.push('/statement/user')">《用户协议》</span>和<span class="active" @click="$router.push('/statement/privacy')">《隐私条款》</span> -->
    </div>
    <selectCountry :val="phoneCountry" ref="country" @back="selectCountryBack"/>
  </div>
</template>
<script>
import { emailList, emailReg } from "@/utils/config";
import { Register, getVerifyCode, login } from "@/api/login";
import { setSession, getSession, delSession } from '@/utils/sessionStorage'
import { setCookie } from "@/utils/cookie";
import bus from '@/utils/bus'
import selectCountry from "@/components/selectCountry";
export default {
  components: {
    selectCountry
  },
  data() {
    return {
      form: {
        account: "",
        phone: "",
        password: "",
        recommend_code: '',
        // password1: '',
        verifyCode: '',
      },
      checked: false,
      codeShow: false,
      type: '1',
      showPassword: 'password',
      showPassword1: 'password',
      loading: false,
      sendText: this.$t('register.l11'),
      sendDisable: false,
      timer: null,
      dialogVisible: false,
      readonly: true,
      recommendCodeDisabled: false,
      accountFocus: false,
      passwordFocus: false,
      codeFocus: false,
      recommendFocus: 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)
    }
  },
  created () {
    var code = (this.$route.params.code || '')
    if (code) {
      setSession('recommend_code', JSON.stringify(code))
    } else {
      code = getSession('recommend_code') ? JSON.parse(getSession('recommend_code')) : ''
    }
    this.recommendCodeDisabled = !!code
    this.form.recommend_code = code
  },
  mounted() {
    if (this.isLogin) {
      this.$store.commit('SET_LOGIN', false)
      this.$store.commit('setAccountList', [])
      this.$store.commit('setCashInfo', {})
      bus.$emit('socketInit')
    }
    setTimeout(() => {
      this.readonly = false
    }, 200)
  },
  methods: {
    submit() {
      if (this.loading) {
        return;
      }
      if (!this.checked) {
        // 请阅读并同意《用户协议》和《隐私条款》
        this.$toast(this.$t('register.l16'));
        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()
      }
      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
      }
      // if (this.form.password1.trim() !== this.form.password.trim()) {
      //   this.$toast('密码输入不一致');
      //   return
      // }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.fullscreenLoading = true
          Register({
            account: account,
            password: this.form.password,
            recommend_code: this.form.recommend_code,
            verifyCode: this.form.verifyCode,
            area_code: this.phoneCountry.area_code
          })
            .then((res) => {
              this.$notify({
                // message: '注册成功',
                message: this.$t('register.l13'),
                type: 'success'
              });
              delSession('recommend_code')
              login({
                account: account,
                password: this.form.password,
                client: this.getClient(),
              }).then((res) => {
                bus.$emit('socketInit')
                this.$store.commit('SET_LOGIN', true)
                this.$store.commit('setToken', res.token)
                setCookie("userToken", res.token)
                this.$store.dispatch('getUserInfo', true)
                this.$store.dispatch('getProductUserList')
                this.$router.replace('/')
              })
              .finally(() => {
                this.fullscreenLoading = false;
                this.loading = false;
              })
              .catch(() => {
                this.$router.replace('/login')
              });
            }).catch(() => {
              this.fullscreenLoading = false;
              this.loading = false;
            });
        } 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: 'Register',
        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
    },
    getClient() {
      var webLog = {}
      try {
      var userAgent = navigator.userAgent
      // 获取微信版本
      var m1 = userAgent.match(/MicroMessenger.*?(?= )/)
      if (m1 && m1.length > 0) {
        webLog.wechat = m1[0]
      }
      if (userAgent.includes('Windows')) {
        webLog.device = 'Windows'
      }
      // 苹果手机
      if (userAgent.includes('iPhone') || userAgent.includes('iPad')) {
        // 获取设备名
        if (userAgent.includes('iPad')) {
          webLog.device = 'iPad'
        } else {
          webLog.device = 'iPhone'
        }
        // 获取操作系统版本
        m1 = userAgent.match(/iPhone OS .*?(?= )/)
        if (m1 && m1.length > 0) {
          webLog.system = m1[0]
        }
      }
      // 安卓手机
      if (userAgent.includes('Android')) {
        // 获取设备名
        m1 = userAgent.match(/Android.*; ?(.*(?= Build))/)
        if (m1 && m1.length > 1) {
          webLog.device = m1[1]
        }
        // 获取操作系统版本
        m1 = userAgent.match(/Android.*?(?=;)/)
        if (m1 && m1.length > 0) {
          webLog.system = m1[0]
        }
      }
      } catch(err) {
      }
      return webLog.device || 'Mobile'
    },
    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;
  justify-content: space-between;
  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: 25px;
}
.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;
}
.href {
  cursor: pointer;
}
.label {
  color: #7D8080;
  font-size: 14px;
  padding-top: 2px;
  padding-bottom: 12px;
  cursor: pointer;
  .el-icon-caret-bottom {
    transition: transform 0.4s;
    &.active {
      transform: rotateZ(-180deg);
    }
  }
}
.rule-box {
  padding: 0 16px;
  .rule {
    column-gap: 6px;
    &.active {
      color: #000;
    }
  }
  .check {
    width: 14px;
  }
}
.btn-box {
  margin-top: 22px;
  margin-bottom: 26px;
  cursor: pointer;
  color: #FEFFFF;
  background: #000000;
  border-radius: 6px;
  line-height: 44px;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
}
.href1 {
  display: flex;
  align-items: flex-start;
  color: #989898;
  font-size: 11px;
  cursor: pointer;
  line-height: 12px;
  justify-content: center;
  .check {
    width: 12px;
    margin-right: 3px;
  }
  .active {
    color: var(--color-);
  }
}
</style>