<template>
  <user-dashboard-container page-class="profile" panel-title="ویرایش پروفایل">
    <div class="row">
      <div class="col-12 col-lg-6">
        <form class="form form_3" @submit.prevent="upload">
          <div class="formRow" :class="validation.first_name ? 'err' : null">
            <label for="verity_businessCode">کد مشتری (وریتی):</label>
            <input
              id="verity_businessCode"
              type="text"
              :value="user.verity_businessCode"
              disabled
              name="verity_businessCode"
              placeholder="..."
            />
            <p v-if="validation.verity_businessCode">{{ validation.verity_businessCode.msg }}</p>
          </div>
          <div class="formRow" :class="validation.first_name ? 'err' : null">
            <label for="panatech_businessCode">کد مشتری (پاناتک):</label>
            <input
              id="panatech_businessCode"
              type="text"
              :value="user.panatech_businessCode"
              disabled
              name="panatech_businessCode"
              placeholder="..."
            />
            <p v-if="validation.panatech_businessCode">{{ validation.panatech_businessCode.msg }}</p>
          </div>
          <div class="formRow" :class="validation.first_name ? 'err' : null">
            <label for="first_name">نام:</label>
            <input id="first_name" v-model="user.first_name" type="text" name="first_name" placeholder="نام" />
            <p v-if="validation.first_name">{{ validation.first_name.msg }}</p>
          </div>
          <div class="formRow" :class="validation.last_name ? 'err' : null">
            <label for="last_name">نام خانوادگی:</label>
            <input id="last_name" v-model="user.last_name" type="text" name="last_name" placeholder="نام خانوادگی" />
            <p v-if="validation.last_name">{{ validation.last_name.msg }}</p>
          </div>
          <div class="formRow" :class="validation.national_code ? 'err' : null">
            <label for="national_code">کد ملی:</label>
            <input
              id="national_code"
              v-model="user.national_code"
              type="text"
              name="national_code"
              placeholder="کد ملی"
            />
            <p v-if="validation.national_code">{{ validation.national_code.msg }}</p>
          </div>

          <div class="formRow" :class="validation.mobile_number ? 'err' : null">
            <label for="mobile">
              <i>شماره موبایل:</i>
              <span v-if="user.mobile_confirmed" class="cs confirmed">(تایید شده)</span>
              <span v-else class="cs">(تایید نشده)</span>
            </label>
            <input id="mobile" v-model="user.mobile_number" type="text" name="mobile" placeholder="شماره موبایل" />
            <p v-if="validation.mobile_number">{{ validation.mobile_number.msg }}</p>
          </div>

          <div class="formRow" :class="validation.email ? 'err' : null">
            <label for="email">
              <i>ایمیل:</i>
              <span v-if="user.email_confirmed" class="cs confirmed">(تایید شده)</span>
              <span v-else class="cs">(تایید نشده)</span>
            </label>
            <input id="email" v-model="user.email" type="text" name="email" placeholder="ایمیل" />
            <p v-if="validation.email">{{ validation.email.msg }}</p>
          </div>

          <div class="formRow" :class="validation.tel_number ? 'err' : null">
            <label for="tel_number">شماره تلفن ثابت:</label>
            <input
              id="tel_number"
              v-model="user.tel_number"
              type="text"
              name="tel_number"
              placeholder="شماره تلفن ثابت:"
            />
            <p v-if="validation.tel_number">{{ validation.tel_number.msg }}</p>
          </div>

          <div class="formRow" :class="validation.province_id ? 'err' : null">
            <label>استان:</label>
            <el-select v-model="user.province_id" filterable placeholder="استان را انتخاب کنید" style="width: 100%">
              <el-option
                v-for="item in iranProvinces"
                :key="item.ProvinceID"
                :label="item.ProvinceName"
                :value="item.ProvinceID"
              >
              </el-option>
            </el-select>
            <p v-if="validation.province_id">{{ validation.province_id.msg }}</p>
          </div>

          <div class="formRow" :class="validation.city_id ? 'err' : null">
            <label>شهر:</label>
            <el-select
              v-model="user.city_id"
              filterable
              :placeholder="provinceCities ? 'شهر را انتخاب کنید' : 'ابتدا استان را انتخاب کنید'"
              style="width: 100%"
            >
              <el-option v-for="item in provinceCities" :key="item.CityID" :label="item.CityName" :value="item.CityID">
              </el-option>
            </el-select>
            <p v-if="validation.city_id">{{ validation.city_id.msg }}</p>
          </div>

          <div class="formRow" :class="validation.address ? 'err' : null">
            <label for="address">آدرس:</label>
            <textarea id="address" v-model="user.address" name="address" rows="5"></textarea>
            <p v-if="validation.address">{{ validation.address.msg }}</p>
          </div>

          <div class="formRow" :class="validation.postal_code ? 'err' : null">
            <label for="postal_code">کد پستی:</label>
            <input id="postal_code" v-model="user.postal_code" type="text" name="postal_code" placeholder="کد پستی" />
            <p v-if="validation.postal_code">{{ validation.postal_code.msg }}</p>
          </div>
          <div class="formRow" :class="validation.store_name ? 'err' : null">
            <label for="store_name">نام فروشگاه (اختیاری):</label>
            <input
              id="store_name"
              v-model="user.store_name"
              type="text"
              name="store_name"
              placeholder="نام فروشگاه (اختیاری)"
            />
            <p v-if="validation.store_name">{{ validation.store_name.msg }}</p>
          </div>

          <div class="btnRow">
            <el-button
              class="btn btn-primary custom-el-button"
              type="primary"
              native-type="submit"
              :loading="postingProfile"
            >
              بروزرسانی
            </el-button>
          </div>
        </form>
      </div>

      <div class="col-12 col-lg-6">
        <form class="form form_3" style="margin-bottom: 50px" @submit.prevent="changePass">
          <div class="formRow" :class="validation.password ? 'err' : null">
            <label for="password">کلمه عبور:</label>
            <input id="password" v-model="newPass.password" type="password" name="password" placeholder="کلمه عبور" />
            <p v-if="validation.password">{{ validation.password.msg }}</p>
          </div>
          <div class="formRow" :class="validation.password_confirmation ? 'err' : null">
            <label for="password_confirmation">تکرار کلمه عبور:</label>
            <input
              id="password_confirmation"
              v-model="newPass.password_confirmation"
              type="password"
              name="password_confirmation"
              placeholder="تکرار کلمه عبور"
            />
            <p v-if="validation.password_confirmation">{{ validation.password_confirmation.msg }}</p>
          </div>

          <div class="btnRow">
            <el-button
              class="btn btn-primary custom-el-button"
              type="primary"
              native-type="submit"
              :loading="postingPassword"
            >
              تغییر کلمه عبور
            </el-button>
          </div>
        </form>
      </div>
    </div>
  </user-dashboard-container>
</template>

<script>
export default {
  name: 'AccountEditProfile',
  layout: 'user',
  async asyncData({ $axios, $auth, error }) {
    try {
      const iranProvinces = await $axios.post('/api/cross/getRouteManager', {
        url: '/api/GetProvince',
        db: 'verity'
      })
      const iranCities = await $axios.post('/api/cross/getRouteManager', {
        url: '/api/GetCity',
        db: 'verity'
      })
      return {
        iranCities: iranCities.data.data,
        iranProvinces: iranProvinces.data.data
      }
    } catch (e) {
      error({ status: 404, message: 'There is a problem here' })
    }
  },
  data() {
    return {
      user: JSON.parse(JSON.stringify(this.$auth.user)),
      iranCities: null,
      iranProvinces: null,
      newPass: {
        password: '',
        password_confirmation: ''
      },
      postingPassword: false,
      postingProfile: false,
      currentEmail: this.$auth.user.email,
      currentMobile: this.$auth.user.mobile_number,
      validation: {}
    }
  },
  computed: {
    selectedProvince() {
      return this.user.province_id
    },
    selectedCity() {
      return this.user.city_id
    },
    provinceCities() {
      return this.iranCities?.filter(item => item.ProvinceID === this.user.province_id)
    }
  },
  watch: {
    selectedProvince(newVal, oldVal) {
      // step 1
      this.user.city_id = ''
      // step 2
      if (newVal)
        this.user.province_name = this.iranProvinces?.filter(item => item.ProvinceID === newVal)[0].ProvinceName
      else this.user.province_name = ''
    },
    selectedCity(newVal, oldVal) {
      if (newVal) this.user.city_name = this.iranCities?.filter(item => item.CityID === newVal)[0].CityName
      else this.user.city_name = ''
    }
  },
  methods: {
    upload() {
      const newEmail = this.user.email !== this.currentEmail
      const newMobile = this.user.mobile_number !== this.currentMobile

      const uploadFunc = async () => {
        try {
          this.postingProfile = true
          this.validation = {}
          await this.$axios.put('/api/user/update_profile', this.user)
          this.postingProfile = false
          this.$auth.fetchUser()
          this.$message({
            type: 'success',
            message: 'اطلاعات با موفقیت بروزرسانی شد'
          })
          if (newEmail || newMobile) this.$router.push({ name: 'account-verify' })
        } catch (err) {
          this.postingProfile = false
          if (err.response.status === 422) this.validation = err.response.data.validation
          else {
            this.$message({
              type: 'error',
              message: err.response.data.message
            })
          }
        }
      }

      if (newEmail || newMobile) {
        const title = 'هشدار'
        const msg = 'با تغییر شماره تلفن همراه یا آدرس ایمیل نیاز به تایید دوباره اطلاعات خود دارید.'
        this.$confirm(msg, title, {
          confirmButtonText: 'ادامه',
          cancelButtonText: 'لغو',
          type: 'warning'
        })
          .then(() => {
            uploadFunc()
          })
          .catch(() => {
            this.$message({
              type: 'warning',
              message: 'بروزرسانی پروفایل لغو شد'
            })
          })
      } else uploadFunc()
    },
    changePass() {
      this.postingPassword = true
      this.validation = {}
      const data = {
        _id: this.user._id,
        password: this.newPass.password,
        password_confirmation: this.newPass.password_confirmation
      }

      this.$axios
        .put('/api/user/update_password', data)
        .then(res => {
          this.$message({
            type: 'success',
            message: 'کلمه عبور با موفقیت بروزرسانی شد'
          })
          this.$auth.logout()
          this.$router.push({ name: 'auth-login-register' })
          this.postingPassword = false
        })
        .catch(err => {
          this.postingPassword = false
          if (err.response.status === 422) this.validation = err.response.data.validation
          else {
            this.$message({
              type: 'error',
              message: err.response.data.message
            })
          }
        })
    }
  }
}
</script>
