<template>
  <a-card>
    <a-col
      :xs="{span: 24}"
      :sm="{span: 20}"
      :xl="{span: 16}">
      <a-divider>头像</a-divider>
      <p>TODO</p>
      <a-divider>重置密码</a-divider>
      <a-form
        :form="reset.form"
        @submit="handleSubmit">
        <a-form-item
          label="新密码"
          :label-col="{span: 6}"
          :wrapper-col="{span: 18}">
          <a-input
            type="text"
            autocomplete="true"
            v-decorator="[
              'password',
              {rules: [
                {required: true, message: '请输入新密码'},
                {min: 8, message: '密码长度在8个字符以上'},
                {validator: notAllNumberValidator, message: '密码不能全为数字'},
              ], validateTrigger: 'blur'}
            ]">
          </a-input>
        </a-form-item>
        <a-form-item
          label="确认新密码"
          :label-col="{span: 6}"
          :wrapper-col="{span: 18}">
          <a-input
            type="password"
            autocomplete="true"
            v-decorator="[
              'password_retry',
              {rules: [
                {required: true, message: '请再次输入新密码'},
                {validator: samePasswordValidator, message: '两次输入的密码不一致'}
              ], validateTrigger: 'blur'}
            ]">
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSubmit" style="float: right">
            保存
          </a-button>
        </a-form-item>
      </a-form>
    </a-col>
  </a-card>
</template>

<script>
  import api from '../../api/user'

  export default {
    name: 'UserSetting',
    data () {
      return {
        reset: {
          form: this.$form.createForm(this),
        }
      }
    },
    mounted () {

    },
    methods: {
      handleSubmit (e) {
        e.preventDefault()
        this.reset.form.validateFields((error, data) => {
            if (!error) {
              api.resetPassword(data.password)
                .then(() => {
                  this.$notification.success({
                    message: '成功',
                    description: '修改密码成功，请重新登陆',
                  })
                  this.$router.push({ name: 'login' })
                })
            }
          }
        )
      },
      notAllNumberValidator (rule, value, callback) {
        if (/^[0-9]+.?[0-9]*$/.test(value)) {
          callback('password cant be all numbers')
          return false
        }
        callback()
        return true
      },
      samePasswordValidator (rule, value, callback) {
        if (value !== this.reset.form.getFieldValue('password')) {
          callback('two passwords are different')
          return false
        }
        callback()
        return true
      }
    }
  }

</script>

<style scoped lang="less">

</style>