<template>
  <div>
    <el-dialog title="修改密码" :visible.sync="dialog" width="450px" :close-on-click-modal="false" top="50px">
      <el-form ref="form" :model="form" :rules="formRules" label-width="80px" class="bind-phone">
        <el-form-item label="旧密码：" label-width="150px" prop="old_password" :rules="formRules.password">
          <el-input v-model="form.old_password" placeholder="请输入旧密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码：" label-width="150px" prop="new_password" :rules="formRules.password">
          <el-input placeholder="请输入新密码" @keyup.enter.native="handleSubmit" v-model="form.new_password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer text-center">
        <el-button @click="dialog = false">取 消</el-button>
        <el-button type="danger" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      dialog: !!this.value,
      form: {
        old_password: '',
        new_password: ''
      }
    }
  },
  methods: {
    async handleSubmit () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const data = await this.$fetch('/api/auth/user/set_me_password', this.form)
          if (data.code === 200) {
            await this.$store.dispatch('user/logout')
            this.$router.push(`/login`)
          }
        } else {
          console.log('error submit!!')
        }
      })
    }
  },
  watch: {
    dialog (val) {
      if (!val) this.$emit('input', val)
    }
  }
}
</script>

<style lang="scss" scoped>
.top-tip {
  margin-top: -20px;
  margin-bottom: 20px;
}
</style>
