<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('/register')">{{ $t('login.l9') }}</div>
    </div>
    <div class="title">
      <!-- 欢迎来到极度证券 -->
      {{ $t('login.l17') }}
    </div>
    <div class="tabs flex">
      <div class="tab" :class="{'active': type == 1}" @click="changeType(1)">
        <!-- 手机号码 -->
        {{ $t('login.l-p') }}
        <div class="line" v-if="type == 1"></div>
      </div>
      <div class="tab" :class="{'active': type == 2}" @click="changeType(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="password" :class="{focus: passwordFocus}">
        <!-- 请输入密码 -->
        <el-input :readonly="readonly" @focus="passwordFocus = true" @blur="passwordFocus = false" autocomplete="off" :placeholder="$t('login.l3')" :type="showPassword" v-model="form.password">
          <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-input>
      </el-form-item>
    </el-form>
    <div class="forget flex">
      <div class="href" @click="$router.push('/find-password')">
        <!-- 忘记密码? -->
        {{ $t('login.l4') }}
      </div>
    </div>
    <div class="btn-box" @click="submit">
      <!-- 登录 -->
      {{ $t('login.l') }}
    </div>
    <selectCountry :val="phoneCountry" ref="country" @back="selectCountryBack"/>
  </div>
</template>
<script>
import { emailList } from "@/utils/config";
import { login } from "@/api/login";
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: "",
      },
      type: '1',
      showPassword: 'password',
      loading: false,
      dialogVisible: false,
      readonly: true,
      accountFocus: false,
      passwordFocus: false,
      emailList: emailList,
      phoneCountry: {
        "name": "China (中国)",
        "code": "cn",
        "area_code": "86"
      },
      rules: {
      },
    };
  },
  created () {
    if (localStorage.getItem('accountH5')) {
      this.form.account = JSON.parse(localStorage.getItem('accountH5'))
    }
    if (localStorage.getItem('loginTypeH5')) {
      this.type = JSON.parse(localStorage.getItem('loginTypeH5'))
    }
    if (localStorage.getItem('phoneCountryH5')) {
      this.phoneCountry = JSON.parse(localStorage.getItem('phoneCountryH5'))
    }
  },
  mounted() {
    setTimeout(() => {
      this.readonly = false
    }, 200)
  },
  methods: {
    submit() {
      if (this.loading) {
        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
        }
        var emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if (!emailReg.test(this.form.account.trim())) {
          // 邮箱格式不正确
          this.$toast(this.$t('login.email-reg'));
          return
        }
        account = this.form.account.trim()
      }
      if (!this.form.password.trim()) {
        // 请输入密码
        this.$toast(this.$t('login.l3'));
        return
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.fullscreenLoading = true
          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')
              localStorage.setItem('phoneCountryH5', JSON.stringify(this.phoneCountry))
              localStorage.setItem('loginTypeH5', JSON.stringify(this.type))
              localStorage.setItem('accountH5', JSON.stringify(this.form.account))
              this.$notify({
                // message: '登入成功',
                message: this.$t('login.l10'),
                type: 'success'
              });
              var rejectUrl = this.$route.query.rejectUrl
              this.$router.replace(rejectUrl || '/')
            })
            .finally(() => {
              this.fullscreenLoading = false;
              this.loading = false;
            })
            .catch(() => {});
        } else {
          return false;
        }
      });
    },
    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'
    },
    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)
    },
    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
    },
    changeType(type) {
      if (this.type == type) {
        return
      }
      this.type = type
      this.form.account = ''
      this.form.password = ''
      this.readonly = true
      setTimeout(() => {
        this.readonly = false
      }, 200)
    }
  },
};
</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;
}
.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;
}
.forget {
  text-align: right;
  justify-content: flex-end;
  padding-top: 4px;
  font-size: 16px;
  font-weight: 500;
  color: #000000;
}
.href {
  cursor: pointer;
}
.btn-box {
  margin-top: 33px;
  margin-bottom: 30px;
  cursor: pointer;
  color: #FEFFFF;
  background: #000000;
  border-radius: 6px;
  line-height: 44px;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
}
</style>