<template>
  <div class="v-component wx-login-setpwd">
    <div class="title">{{title}}</div>
    <confirm-input :target-value="pwd" @success="fillPwd" v-if="step === 1"></confirm-input>
    <confirm-input :target-value="againPwd" @success="fillRePwd" v-else></confirm-input>
    <Spin size="large" fix class="loading" v-if="loading"></Spin>
  </div>
</template>

<script>
import ConfirmInput from '../confirm-input'
import org from '../../apis/org'
import validate from '../../utils/validate.js'
export default {
  name: 'WxLoginSetpwd',
  data () {
    return {
      step: 1,
      pwd: '',
      againPwd: '',
      loading: false
    }
  },
  computed: {
    title () {
      return this.step === 1 ? '设置交易密码' : '确认交易密码'
    }
  },
  created () {
    this.init()
  },
  methods: {
    init () {
      this.step = 1
      this.pwd = ''
      this.againPwd = ''
    },
    fillPwd (code) {
      if (!validate.isTradePwd(code)) {
        this.$Message.error('请设置6位数字交易密码')
        this.init()
        return
      }
      this.pwd = code
      this.step = 2
    },
    fillRePwd (code) {
      if (code !== this.pwd) {
        this.$Message.error('两次密码不一致，请重新设置')
        this.init()
        return 
      }
      this.againPwd = code
      this.setPwd()
    },
    async setPwd () {
      try {
        this.loading = true
        await org.setPwd(this.pwd)
        this.$emit('set-pwd-success')
      } catch (e) {
        this.init()
        this.loading = false
      }
    }
  },
  components: {
    ConfirmInput
  }
}
</script>