<style lang="less" scoped>
  @import './Index.less';
</style>

<style lang="less">
  .registBox{
    .registForm{
      .formItem{
          .ivu-form-item-label {
            color: white;
          }
          input, select, button{
              border-radius: 0;
              font-size: 12px;
          }
          .ivu-btn-primary{
            background-color: #4d6b9d;
          }
          .ivu-select-selection{
            border-radius: 0;
          }
      }
    }
  }
</style>

<template>
    <div class="registDiv">
        <div class="registBox">
          <h3 style="text-align: center;margin-bottom: 5px;font-weight: 100;letter-spacing: 3px;font-size: 20px;color: white;">
              {{ $t('regist.title') }}
          </h3>
          <Form class="registForm" ref="registForm" :model="registForm" :rules="registRules" label-position="top" style="color: white;">
              <!-- <FormItem class="formItem" style="font-size: 12px; text-align: center;">
                  <label>{{ $t('醍摩豆ID')}}:</label> {{ teammodelID }}
              </FormItem> -->
              <FormItem class="formItem">
                  <span style="font-size: 14px;font-weight: 500;">{{$t('regist.form.text1')}}</span>
                  <br/>
                  <div>
                      <RadioGroup v-model="applyType">
                          <Radio label="phone" select>
                              <span style="font-size: 13px;">{{$t('regist.form.text2')}}</span>
                          </Radio>
                          <Radio label="email" >
                              <span style="font-size: 13px;">{{$t('regist.form.text3')}}</span>
                          </Radio>
                      </RadioGroup>
                  </div>
                  <span v-if="applyType == 'email' " style="width: 400px;display: block;text-align: center;font-size: 13px;color: rgb(244, 67, 54);">{{ $t('regist.form.remind')}}</span>
              </FormItem>
              <FormItem class="formItem" prop="account" >
                  <Row type="flex" justify="center" align="top">
                      <Col v-if="applyType == 'phone'" :span="9">
                          <CountryCode v-model="cCode"/>
                      </Col>
                      <Col :span="applyType == 'phone' ? 15 : 24">
                          <Input :placeholder="$t('regist.form.placeholder.' + applyType)" v-model="registForm.account"></Input>                                                                        
                      </Col>
                  </Row>
              </FormItem>
              <FormItem class="formItem" prop="pinCode">
                  <Row type="flex" justify="center" align="top">
                      <Col :span="9">
                          <Button  class="radius-right-0" style="font-size:12px; " long type="primary" @click="sendPinCode()" :disabled="countdown || pinCodeSwitch">
                              {{ sendBtnText }}
                          </Button>
                      </Col>
                      <Col :span="15">
                          <Input   class="radius-left-0 input-font-size-12" v-model="registForm.pinCode" :placeholder="$t('regist.form.placeholder.pindCode')"></Input>
                      </Col>
                  </Row>
              </FormItem>
              <FormItem class="formItem"  :label="$t('regist.form.text4')" prop="name">
                  <Input  v-model="registForm.name" ></Input>
              </FormItem>
              <FormItem class="formItem"  :label="$t('regist.form.text5')" prop="pw" >
                  <Input   type="password" password  v-model="registForm.pw" ></Input>
              </FormItem>
              <FormItem class="formItem"  :label="$t('regist.form.text6')" prop="pwCheck" >
                  <Input   type="password" password v-model="registForm.pwCheck" ></Input>
              </FormItem>
              <FormItem class="formItem">
                  <Checkbox v-model="agreePrivacy" style="font-size: 12px;">
                      {{ $t('regist.form.text8') }}
                      <a target="_blank" :href="descriptionURL"><b>{{ $t('regist.form.text9')}}</b></a>
                      {{ $t('regist.form.text10') }}
                      <a target="_blank" :href="privacyURL"><b>{{ $t('regist.form.text11')}}</b></a>
                  </Checkbox>
              </FormItem>
              <FormItem class="formItem">
                  <Button long  type="primary" @click="handleSubmit('registForm')" :disabled="!agreePrivacy" :loading="loading" style="margin-top:20px;">
                      <span>{{ $t('regist.btn.signUp') }}</span>
                  </Button>
              </FormItem>
          </Form>
        </div>
    </div>
</template>
<script>
import { User } from '@/service/User'
import CountryCode from '@/components/public/countryCode/Index.vue'
import { mapState, mapGetters } from 'vuex'

export default {
  components:{
    CountryCode
  },
  data() {
    const validAccount = (rule, value, callback) => {
      if (value === '') {
        if(this.applyType == 'phone'){
          callback(new Error( this.$t('error.input.phone')));
        } else {
          callback(new Error( this.$t('error.input.email')));
        }    
      } else {
        switch (this.applyType) {
          case 'email':
            let emailRule = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]+$/;
            if(value.search(emailRule) != -1){
              callback();
            } else {
              callback(new Error( this.$t('error.format.email')));
            }
            break;
          case 'phone':
            if(this.cCode === '') {
              callback(new Error( this.$t('error.input.countryCode')));
            } else if(!(/^[0-9]*$/.test(value))) {
              callback(new Error( this.$t('error.format.numeric')));
            } else {
              callback();
            }
            break;
        }
      }
    };
    const validPW = (rule, value, callback) => {
      if (!(/^(?=.*[a-zA-Z])(?=.*\d)[\S]{8,30}$/.test(value))) {
        callback(new Error(this.$t('error.format.pw')));
      } else {
        callback();
      }
    };
    const validPWCheck = (rule, value, callback) => {
      if(value == ''){
        callback(new Error(this.$t('error.input.pwCheck')));
      }
      else if(value != this.registForm.pw){
        callback(new Error(this.$t('error.input.pwCheckFail')));
      } else {
        callback();
      }
    };
    return {
      applyType: 'phone',
      cCode:'',
      teammodelID: '',
      agreePrivacy: '',
      sendText: '',
      lang: localStorage.getItem('local'),
      countdownSec: 60,
      verfTime: 0,
      countdown: false,
      registForm: {
          account: '',
          name: '',
          pw: '',
          pwCheck: '',
          pinCode:''
      },
      registRules: {
        account: [
          {validator: validAccount , trigger: 'blur' },
        ],
        name: [
          {required: true, message: () => this.$t('error.required') , trigger: 'blur' },
        ],
        pw: [
          {required: true, message: () => this.$t('error.required') , trigger: 'blur' },
          {validator: validPW , trigger: 'blur' }
        ],
        pwCheck: [
          {required: true, message: () => this.$t('error.required') , trigger: 'blur' },
          {validator: validPWCheck , trigger: 'blur' }
        ],
        pinCode: [
          {required: true, message: () => this.$t('error.required') , trigger: 'blur' },
        ],        
      },
      loading: false
    }
  },
  computed: {
    ...mapState({
      config: state => state.config
    }),
    ...mapGetters({
        loginSchooCode: 'user/getLoginSchooCode',
        srvAdr: 'config/getSrvAdr'
    }),
    descriptionURL: function () {
      let domain = 'https://account.habookaclass.biz'
      let path;
      if(this.srvAdr == 'China'){
        domain = 'https://account.teammodel.cn'
      }
      switch (this.lang.toLowerCase()) {
          case 'zh-tw':
              path =  '/html/description/zh_TW.html'
              break;
          case 'zh-cn':
              path = '/html/description/zh_CN.html'
              break;
          case 'en-us':
              path = '/html/description/en_US.html'
              break;
        }

        return domain + path
    },
    privacyURL: function () {
      let domain = 'https://account.habookaclass.biz'
      let path;
      if(this.srvAdr == 'China'){
        domain = 'https://account.teammodel.cn'
      }
      switch (this.lang.toLowerCase()) {
          case 'zh-tw':
              path = '/html/privacy/zh_TW.html'
              break;
          case 'zh-cn':
              path = '/html/privacy/zh_CN.html'
              break;
          case 'en-us':
              path = '/html/privacy/en_US.html'
              break;
      }

      return domain + path
    },
    sendBtnText: function(){ // 發送驗證信與驗證碼字串判斷
        let str = this.$t('regist.btn.send' + this.applyType)
        let timeStr = ''
        if(this.countdown) timeStr = '(' + this.verfTime + ')'

        return str + timeStr
    },
    pinCodeSwitch: function(){
      let disabledFlag = false
      if(this.registForm.account === '') disabledFlag = true
      if(this.applyType == 'phone' && this.cCode === '') disabledFlag = true
      return disabledFlag
    },
    accFormat: function(){
      let acc = this.registForm.account
      if(this.applyType == 'phone' && this.cCode == 886 && acc.indexOf(0) == 0) {
        acc = acc.substr(1)
      }

      return acc
    }
  },
  created() {
    this.verfTime = this.countdownSec;
    // this.teammodelID = Math.floor(new Date().getTime() / 1000)
  },
  methods: {
    handleSubmit: function(name){
      this.$refs[name].validate( async(valid) => {
        if (valid) {
          
          this.loading = true

          let data = {
            applyType: this.applyType,
            name: this.registForm.name,
            account: this.accFormat,
            pw: this.registForm.pw,
            country: this.cCode,
            pinCode: this.registForm.pinCode
          }

          this.$api.regist.crtAccount(data).then( async res => {
            if(res.error){
              let text;
              switch (res.error) {
                case 2:
                  text = this.$t('error.coreApi.error2.default')
                  break;
                case 3:
                  text = this.$t('error.coreApi.error3')
                  break;
              }

              this.$Message.warning({
                  content: text,
                  duration: 7,
                  closable: true
              })

              this.loading = false
            } else {
              let result = res

              // 登入大雲
              await this.$api.login.loginIES(result).then( res => {
                console.log(res, 'info')
                result = res
              })

              //設定權限並登入
              User.login(result).then(res => {
                if(res) {
                  this.loading = false
                  this.$router.push({ path: '/home' })
                }
              })
            }
          })
        }
      })
    },
    sendPinCode(){
      let data = {
        applyType: this.applyType,
        to: this.accFormat,
        lang: this.lang,
        hasUser: false,
        country: this.cCode
      }
      this.$api.SendPinCode(data).then(res => {
        let errorFlag = false
        if(res){
          errorFlag = true
          this.$Message.warning({
              content: this.$t('error.coreApi.error2.' + this.applyType),
              duration: 7,
              closable: true
          })
        } 

        if(!errorFlag){
          this.countdown = true
          this.reciprocal()
        }
      })
    },
    reciprocal () { // 調整倒數時間至可控
        this.verfTime -=1;
        if(this.verfTime==0){
          this.countdown = false
          this.verfTime = this.countdownSec;
        } else{
          //每秒執行一次,showTime()
          setTimeout(this.reciprocal,1000);
        }
    },
  }
}
</script>