<template>
  <el-dialog :title="title" :visible.sync="showModal">
    <div>
      <form class="form form_3 stuffModal" @submit.prevent="change">
        <div class="formRow" :class="[validation.email && 'err', validation.mobile && 'err']">
          <el-input v-model="input" :placeholder="inputPlaceholder"> </el-input>
          <p v-if="validation.email">{{ validation.email.msg }}</p>
          <p v-if="validation.mobile">{{ validation.mobile.msg }}</p>
        </div>
        <div class="formRow">
          <el-button
            class="btn btn-primary custom-el-button"
            type="primary"
            native-type="submit"
            :loading="posting"
            :disabled="input.length < 1"
          >
            تغییر
          </el-button>
        </div>
      </form>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'ChangeEmailOrMobileModal',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    type: {
      required: true,
      type: String
    }
  },
  data() {
    return {
      input: '',
      posting: false,
      validation: {}
    }
  },
  computed: {
    showModal: {
      get() {
        return this.show
      },
      set(value) {
        this.$emit('closeModal')
      }
    },
    title() {
      if (this.type === 'mobile') return 'تغییر شماره موبایل'
      if (this.type === 'email') return 'تغییر ایمیل'
      else return ''
    },
    inputPlaceholder() {
      if (this.type === 'mobile') return 'شماره موبایل خود را وارد کنید'
      if (this.type === 'email') return 'ایمیل خود را وارد کنید'
      else return ''
    }
  },
  methods: {
    async change() {
      try {
        this.posting = true
        this.validation = {}

        let res
        if (this.type === 'email') {
          res = await this.$axios.put('/api/user/changeEmail', { email: this.input })
        }
        if (this.type === 'mobile') {
          res = await this.$axios.put('/api/user/changeMobile', { mobile: this.input })
        }
        this.posting = false
        this.$message({
          type: 'success',
          message: res.data.message
        })
        this.$auth.fetchUser()
        this.showModal = false
      } catch (err) {
        this.posting = false
        if (err.response.status === 422) this.validation = err.response.data.validation
        else {
          this.$message({
            type: 'error',
            message: 'مشکلی در بروزرسانی اطلاعات پیش آمده'
          })
        }
      }
    }
  }
}
</script>
