<template>
  <div class="user-auth page login" :class="!login ? 'register' : null">
    <div class="formBox" :class="hasValidationError || waiting ? 'hasValidationError' : null">
      <div class="side">
        <p v-if="login">
          <span>حساب کاربری ندارید ؟</span>
          <br />
          <span>برای ثبت نام روی دکمه زیر کلیک کنید</span>
        </p>
        <p v-else>
          <span>اگر قبلآ ثبت نام کرده اید برای ورود روی دکمه زیر کلیک کنید</span>
        </p>
        <button class="btn btn-secondary" @click.prevent="changeForm">{{ login ? 'ثبت نام' : 'ورود' }}</button>
      </div>
      <div class="main">
        <form v-if="login" class="form form_2" @submit.prevent="loginToSystem">
          <div class="title">
            <p>ورود به حساب کاربری</p>
          </div>
          <div class="formRow" :class="validation.username ? 'err' : null">
            <input
              v-model="loginData.username"
              type="text"
              name="email"
              autocomplete="email"
              placeholder="ایمیل یا کد ملی"
            />
            <p v-if="validation.username">{{ validation.username.msg }}</p>
          </div>
          <div class="formRow" :class="validation.password ? 'err' : null">
            <input
              v-model="loginData.password"
              type="password"
              name="password"
              autocomplete="password"
              placeholder="کلمه عبور"
            />
            <p v-if="validation.password">{{ validation.password.msg }}</p>
          </div>
          <div class="formRow">
            <label for="remember_me">
              <input id="remember_me" v-model="loginData.remember_me" type="checkbox" />
              <span>مرا به خاطر بسپار</span>
            </label>
          </div>
          <div class="btnRow">
            <el-button
              class="btn btn-secondary secondary-reverse custom-el-button"
              :loading="waiting"
              native-type="submit"
            >
              ورود
            </el-button>
            <nuxt-link :to="{ name: 'auth-resetpass' }">کلمه عبور را فراموش کرده اید؟</nuxt-link>
          </div>
        </form>

        <form v-else class="form form_2">
          <div v-if="waiting" class="msgBox">
            <div class="inner">
              <p>لطفا منتظر بمانید...</p>
            </div>
          </div>

          <div class="title">
            <p>ایجاد حساب کاربری</p>
          </div>
          <div class="formRow" :class="validation.first_name ? 'err' : null">
            <input
              v-model="registerData.first_name"
              type="text"
              name="first_name"
              autocomplete="false"
              placeholder="نام"
            />
            <p v-if="validation.first_name">{{ validation.first_name.msg }}</p>
          </div>
          <div class="formRow" :class="validation.last_name ? 'err' : null">
            <input
              v-model="registerData.last_name"
              type="text"
              name="last_name"
              autocomplete="false"
              placeholder="نام خانوادگی"
            />
            <p v-if="validation.last_name">{{ validation.last_name.msg }}</p>
          </div>
          <div class="formRow" :class="validation.national_code ? 'err' : null">
            <input v-model="registerData.national_code" type="text" placeholder="کد ملی" />
            <p v-if="validation.national_code">{{ validation.national_code.msg }}</p>
          </div>
          <div class="formRow" :class="validation.mobile_number ? 'err' : null">
            <input v-model="registerData.mobile_number" type="text" placeholder="شماره موبایل" />
            <p v-if="validation.mobile_number">{{ validation.mobile_number.msg }}</p>
          </div>
          <div class="formRow" :class="validation.tel_number ? 'err' : null">
            <input
              v-model="registerData.tel_number"
              type="text"
              name="phone"
              autocomplete="false"
              placeholder="شماره تلفن ثابت"
            />
            <p v-if="validation.tel_number">{{ validation.tel_number.msg }}</p>
          </div>
          <div class="formRow" :class="validation.email ? 'err' : null">
            <input v-model="registerData.email" type="text" name="email" autocomplete="false" placeholder="ایمیل" />
            <p v-if="validation.email">{{ validation.email.msg }}</p>
          </div>

          <div class="formRow" :class="validation.province_id ? 'err' : null">
            <el-select
              v-model="registerData.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">
            <el-select
              v-model="registerData.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 addressTextArea" :class="validation.address ? 'err' : null">
            <textarea v-model="registerData.address" name="address" rows="1" placeholder="آدرس"></textarea>
            <p v-if="validation.address">{{ validation.address.msg }}</p>
          </div>
          <div class="formRow" :class="validation.postal_code ? 'err' : null">
            <input
              v-model="registerData.postal_code"
              type="text"
              name="postal_code"
              autocomplete="false"
              placeholder="کد پستی"
            />
            <p v-if="validation.postal_code">{{ validation.postal_code.msg }}</p>
          </div>
          <div class="formRow" :class="validation.postal_code ? 'err' : null">
            <input
              v-model="registerData.store_name"
              type="text"
              name="store_name"
              autocomplete="false"
              placeholder="نام فروشگاه (اختیاری)"
            />
            <p v-if="validation.store_name">{{ validation.store_name.msg }}</p>
          </div>

          <div class="formRow" :class="validation.password ? 'err' : null">
            <input
              v-model="registerData.password"
              type="password"
              name="password"
              autocomplete="false"
              placeholder="کلمه عبور"
            />
            <p v-if="validation.password">{{ validation.password.msg }}</p>
          </div>
          <div class="formRow" :class="validation.password_confirmation ? 'err' : null">
            <input
              v-model="registerData.password_confirmation"
              type="password"
              name="password_confirmation"
              autocomplete="false"
              placeholder="تکرار کلمه عبور"
            />
            <p v-if="validation.password_confirmation">{{ validation.password_confirmation.msg }}</p>
          </div>

          <div class="btnRow">
            <el-button
              class="btn btn-secondary secondary-reverse custom-el-button"
              :loading="waiting"
              @click="register"
            >
              ثبت نام
            </el-button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'LoginRegisterPage',
  layout: 'user-auth',
  data() {
    return {
      login: true,
      switchTL: null,
      registerData: {
        first_name: '',
        last_name: '',
        email: '',
        national_code: '',
        province_id: '',
        city_id: '',
        province_name: '',
        city_name: '',
        address: '',
        postal_code: '',
        tel_number: '',
        mobile_number: '',
        password: '',
        password_confirmation: ''
      },
      loginData: {
        username: '',
        password: '',
        remember_me: false
      },
      hasValidationError: false,
      waiting: false,
      iranCities: [],
      iranProvinces: [],
      provinceCities: null,
      validation: {}
    }
  },
  computed: {
    selectedProvince() {
      return this.registerData.province_id
    },
    selectedCity() {
      return this.registerData.city_id
    }
  },
  watch: {
    selectedProvince(newVal, oldVal) {
      // step 1
      this.registerData.city_id = ''
      // step 2
      if (newVal)
        this.registerData.province_name = this.iranProvinces.filter(item => item.ProvinceID === newVal)[0].ProvinceName
      else this.registerData.province_name = ''
      // step 3
      if (newVal) this.provinceCities = this.iranCities.filter(item => item.ProvinceID === newVal)
      else this.provinceCities = null
    },
    selectedCity(newVal, oldVal) {
      if (newVal) this.registerData.city_name = this.iranCities.filter(item => item.CityID === newVal)[0].CityName
      else this.registerData.city_name = ''
    }
  },
  mounted() {
    // fetch province and city data
    this.$axios
      .post('/api/cross/getRouteManager', {
        url: '/api/GetProvince',
        db: 'verity'
      })
      .then(res => {
        this.iranProvinces = res.data.data
      })
      .catch(err => {
        this.$arpaError()
        console.log('provinces list fetch error -- ', err)
      })

    this.$axios
      .post('/api/cross/getRouteManager', {
        url: '/api/GetCity',
        db: 'verity'
      })
      .then(res => {
        this.iranCities = res.data.data
      })
      .catch(err => {
        this.$arpaError()
        console.log('cities list fetch error -- ', err)
      })

    // switch animation
    const sideWidth = $('.login .formBox .side').width()
    const sideHeight = $('.login .formBox .side').height()
    const _du = 0.7
    const _ease = 'power4.inOut'
    this.switchTL = this.$gsap
      .timeline({ paused: true })
      .to($('.login .formBox'), {
        height: () => {
          return window.innerWidth > 992 ? 1140 : 1280
        },
        duration: _du,
        ease: _ease
      })
      .to(
        $('.login .formBox .side'),
        {
          width: '100%',
          height: '100%',
          duration: _du,
          ease: _ease,
          onComplete: () => {
            this.login = !this.login
          }
        },
        0
      )
      .to(
        $('.login .formBox .main'),
        {
          marginRight: 0,
          marginLeft: () => {
            return window.innerWidth > 992 ? sideWidth : 0
          },
          duration: _du,
          ease: _ease
        },
        0
      )

      .to($('.login .formBox .side'), { right: 'auto', left: 0, duration: 0 })
      .to($('.login .formBox .side'), {
        width: () => {
          return window.innerWidth > 992 ? sideWidth : '100%'
        },
        height: () => {
          return window.innerWidth > 992 ? '100%' : sideHeight
        },
        duration: _du,
        ease: _ease,
        onReverseComplete: () => {
          this.login = !this.login
        }
      })

    const windowWidth = window.innerWidth
    $(window).resize(() => {
      if (window.innerWidth !== windowWidth) {
        if (window.innerWidth < 992) window.location.reload()
      }
    })

    /// / change form if route is fro registration
    if (this.$route.query?.action === 'register') this.changeForm()
  },
  methods: {
    changeForm() {
      this.validation = {}
      this.waiting = false
      this.login ? this.switchTL.play() : this.switchTL.reverse()
    },
    register() {
      if (this.waiting) {
        return this.$message({
          type: 'warning',
          message: 'لطفا منتظر بمانید'
        })
      }
      this.validation = {}
      this.hasValidationError = false
      this.waiting = true

      this.$axios
        .post('/api/auth/register/user', this.registerData)
        .then(response => {
          this.waiting = false

          const username = this.registerData.email
          const password = this.registerData.password
          const msgBoxTitle = 'ثبت نام موفق'
          const msgBoxTxt =
            'ثبت نام با موفیت انجام شد و کد تایید برای ایمیل و تلفن همراه شما ارسال شد. چنانچه طی 24 ساعت آینده ایمیل و شماره تماس خود را تایید نکنید ثبت نام شما منقضی خواهد شد.'
          this.$alert(msgBoxTxt, msgBoxTitle, {
            confirmButtonText: 'ورود به حساب کاربری',
            callback: action => {
              this.loginData.username = username
              this.loginData.password = password
              this.loginToSystem()
            }
          })

          this.registerData = {
            first_name: '',
            last_name: '',
            email: '',
            national_code: '',
            province: '',
            city: '',
            address: '',
            postal_code: '',
            mobile_number: '',
            tel_number: '',
            password: '',
            password_confirmation: ''
          }
        })

        .catch(error => {
          if (error.response.status === 422) {
            this.validation = error.response.data.validation
            this.hasValidationError = true
            this.waiting = false
          } else
            this.$message({
              type: 'error',
              message: error.response.data.message
            })
        })
    },
    async loginToSystem() {
      if (this.waiting) {
        return this.$message({
          type: 'warning',
          message: 'لطفا منتظر بمانید'
        })
      }
      this.waiting = true
      this.validation = {}
      try {
        await this.$auth.loginWith('local', { data: this.loginData })
        this.waiting = false
        if (this.$auth.hasScope('user')) {
          if (this.$route.query?.path) this.$router.push({ name: this.$route.query.path })
          else this.$router.push({ name: 'account' })
        } else if (this.$auth.hasScope('admin')) this.$router.push({ name: 'admin' })
      } catch (e) {
        this.waiting = false
        if (e.response.status === 422) this.validation = e.response.data.validation
        else
          return this.$message({
            type: 'error',
            message: e.response.data.message
          })
      }
    }
  }
}
</script>
