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

<style lang="less">
  .forgotBox{
    .validForm{
      .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="forgotDiv">
        <div class="forgotBox">
          <h3 style="text-align: center;margin-bottom: 5px;font-weight: 100;letter-spacing: 3px;font-size: 20px;color: white;">
              {{ $t('forgotPW.title') }}
          </h3>
          <Form v-show="restPWStep == 1" class="validForm" ref="sendForm" :model="sendForm" :rules="sendRules" label-position="top" @keydown.enter.native="handleSubmit('sendForm')" style="color: white;">
            <FormItem class="formItem">
              <span v-if="applyType == 'email' " style="display: block;text-align: center;font-size: 13px;color: rgb(244, 67, 54);">{{ $t('forgotPW.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('forgotPW.form.placeholder.' + applyType)" v-model="sendForm.account"></Input>                                                                        
                </Col>
              </Row>
            </FormItem>
            <FormItem class="formItem">
                <Button long  type="primary" @click="handleSubmit('sendForm')" :loading="loading">
                  <span>{{ $t('forgotPW.btn.sendPinCode.'+ applyType) }}</span>
                </Button>
            </FormItem>
            <FormItem class="formItem" style="text-align: center;">
              <Button style="color: #409eff;" type="text" @click="chgValidType()" >{{ $t('forgotPW.btn.noUse' + applyType) }}</Button>
            </FormItem>
          </Form>
          <Form v-show="restPWStep == 2" class="validForm" ref="resPwForm" :model="resPwForm" :rules="resPwRules" label-position="top" style="color: white;">
              <FormItem class="formItem" style="text-align: center;">
                {{'+' + cCode + '-' + accFormat}} <Button  type="primary" size="small" :disabled="countdown" @click="handleSubmit('sendForm')"> {{ sendBtnText }}</Button>
              </Formitem>
              <FormItem class="formItem">
                  <span v-if="applyType == 'email' " style="width: 400px;display: block;text-align: center;font-size: 13px;color: rgb(244, 67, 54);">{{ $t('forgotPW.form.remind')}}</span>
              </FormItem>
              <FormItem class="formItem" prop="pinCode" :label="$t('forgotPW.form.text1')">
                <Input  class="radius-left-0 input-font-size-12" v-model="resPwForm.pinCode"></Input>
              </FormItem>
              <FormItem class="formItem"  :label="$t('forgotPW.form.text2')" prop="pw" >
                <Input   type="password" password  v-model="resPwForm.pw" ></Input>
              </FormItem>
              <FormItem class="formItem"  :label="$t('forgotPW.form.text3')" prop="pwCheck" >
                <Input   type="password" password v-model="resPwForm.pwCheck" ></Input>
              </FormItem>
              <FormItem class="formItem">
                  <Button long  type="primary" @click="handleSubmit('resPwForm')" :loading="loading" style="margin-top:20px;">
                      <span>{{ $t('forgotPW.btn.send') }}</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.resPwForm.pw){
        callback(new Error(this.$t('error.input.pwCheckFail')));
      } else {
        callback();
      }
    };
    return {
      applyType: 'phone',
      restPWStep: 1, // 發送驗證碼 1, 重置密碼 2
      cCode:'',
      teammodelID: '',
      sendText: '',
      lang: localStorage.getItem('local'),
      countdownSec: 60,
      verfTime: 0,
      countdown: false,
      sendForm:{
        account: '',
      },
      sendRules:{
        account: [
          {validator: validAccount , trigger: 'blur' },
        ],
      },
      resPwForm: {
          pw: '',
          pwCheck: '',
          pinCode:''
      },
      resPwRules: {
        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'
    }),
    sendBtnText: function(){ // 發送驗證信與驗證碼字串判斷
        let str = this.$t('forgotPW.btn.sendPinCode.' + this.applyType)
        let timeStr = ''
        if(this.countdown) timeStr = '(' + this.verfTime + ')'

        return str + timeStr
    },
    accFormat: function(){
      let acc = this.sendForm.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: {
    chgValidType: function(){
      if(this.applyType == 'phone') {
        this.applyType = 'email'
      } else {
        this.applyType = 'phone'
      }
    },
    handleSubmit: function(name){
      this.$refs[name].validate( async(valid) => {
        if (valid) {
          let data = {}
          this.loading = true
          switch (name) {
            case 'sendForm':
              data = {
                applyType: this.applyType,
                to: this.accFormat,
                lang: this.lang,
                hasUser: true,
                country: this.cCode
              }
              this.$api.SendPinCode(data).then(res => {
                let errorFlag = false
                this.loading = false
                if(res){
                  errorFlag = true
                  this.$Message.warning({
                    content: this.$t('error.coreApi.error1.' + this.applyType),
                    duration: 7,
                    closable: true
                  })
                } 

                if(!errorFlag){
                  this.restPWStep = 2
                  this.countdown = true
                  this.reciprocal()
                }
              })
            break;
            case 'resPwForm':
              data = {
                applyType: this.applyType,
                account: this.accFormat,
                pw: this.resPwForm.pw,
                country: this.cCode,
                pinCode: this.resPwForm.pinCode
            }
            
            this.$api.forgetPW.resetPW(data).then( async res => {
              this.loading = false
              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
                })
              } 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.$router.push({ path: '/home' })
                  }
                })
              }
            })
              break;
          }
        }
      })
    },
    reciprocal () { // 調整倒數時間至可控
        this.verfTime -=1;
        if(this.verfTime==0){
          this.countdown = false
          this.verfTime = this.countdownSec;
        } else{
          //每秒執行一次,showTime()
          setTimeout(this.reciprocal,1000);
        }
    },
  }
}
</script>