<template>
  <div class="w-100 h-100 d-fx fxd-c ai-c">
    <h2 class="f-27px lh-33px c-333333 fw-b t-c mt-42px">Create Account</h2>
    <form class="xw-402px w-100 mt-48px pl-16px bor-3px d-fx fxd-c ai-c" @submit.prevent="submit">
      
    <!-- {{user_data}} -->
      <div class="w-100 h-52px b-F3F6F6 d-fx fxd-c jc-c pl-16px bor-3px"
        v-for="(data, key, index) in signUpForm" :key="index"
        :class="[
          (index > 0 ? 'mt-15px' : ''), 
          (submitStatus === 'failed' && $v.signUpForm[key].$model[key] === '' ? 'bo-1px bo-rd' :''),
          (submitStatus === 'failed' && $v.signUpForm[key].$error ? 'bo-1px bo-rd' :''),
        ]">
        
        <div class="d-fx ai-c">
          <ic-icon :name="data.iconName" :width="data.iconWidth" :height="data.iconHeight" class=""></ic-icon>
          <input :type="key === 'password'? 'password': 'text'" 
            :placeholder="data.placeholder" 
            v-model="data[key]" class="h-100 w-100 ml-13px"
            @input="data[key].length > 0 ? $v.signUpForm[key].$touch() : ''"
            @focus="selectedField = key; " @blur="selectedField = ''">
        </div>
        <div class=""> <!-- error popups -->
          <p v-if="submitStatus === 'emailNotAvailable' && key === 'email'" class="f-9px lh-12px c-FF3030 ml-33px">Email EXISTED already</p>
          <p v-if="$v.signUpForm[key][key].$error && $v.signUpForm[key][key].$model.length > 0 && key === 'email'" class="f-9px lh-12px c-FF3030 ml-33px">Invalid Email</p>
          <p v-if="$v.signUpForm[key][key].$error && $v.signUpForm[key][key].$model.length > 0 && key === 'password'" class="f-9px lh-12px c-FF3030 ml-33px">Must contain 4 characters, numbers</p>
          <p v-if="$v.signUpForm[key][key].$error && $v.signUpForm[key][key].$model.length > 0 && key === 'fullName'" class="f-9px lh-12px c-FF3030 ml-33px">Must be at least 2 words</p>
          <p v-if="$v.signUpForm[key][key].$error && $v.signUpForm[key][key].$model.length > 0 && key === 'phone'" class="f-9px lh-12px c-FF3030 ml-33px">Invalid Phone number</p>
        </div>
      </div>

      <button ripple="ripple" class="w-201px h-56px b-1B1B1B bs-0_6_10_BABABA-H tn-100ms bor-100px mt-56px cursor-pointer" type="submit">
        <span class="f-18px fw-300 lh-22px t-c c-we">SIGN UP</span>
      </button>
    </form>
  </div>
</template>

<script>
import { required, email, minLength } from 'vuelidate/lib/validators'
import { UserM, SignUpM } from '@/models/Userist.js'
import { AccountM as AccountLeanist } from '@/models/Leanist.js'
import { AccountM as AccountIdist} from '@/models/Idist.js'
import {mapStateVModel} from 'map-state-vmodel';

export default {
  name: 'signUpFieldsC',
  extends: {},
  props: {},
  data(){
    return{
      userDataReady: false,
      user_data: [],
      selectedField: '',
      submitStatus: null,
      signUpForm: {
        email: {
          email: '',
          placeholder: 'Email',
          iconName: 'email',
          iconWidth: '20',
          iconHeight: '18'
        },
        password: {
          password: '',
          placeholder: 'Password',
          iconName: 'password',
          iconWidth: '20',
          iconHeight: '23'
        },
        fullName: {
          fullName: '',
          placeholder: 'Full Name',
          iconName: 'user',
          iconWidth: '20',
          iconHeight: '20'
        },
        phone: {
          phone: '',
          placeholder: 'Phone',
          iconName: 'mobile',
          iconWidth: '15',
          iconHeight: '20'
        }
      }
    };
  },
  validations: {
    signUpForm: {
      email: {
        email: {
          email,
          authentication() { // always returns true
            return true
          },
          required
        }
      },
      password: {
        password: {
          authentication (value) {
            return (/^(?=.*?[0-9])(?=.*?[a-z]).{8,}$/.test(value)); // Must contain 4 characters, numbers
            // return (/^(?=.*?[0-9])(?=.*?[A-Z])(?=.*?[a-z]).{8,}$/.test(value)); // Must contain 8 characters, CAPS, and Numbers
          },
          minLength: minLength(8),
          required
        }
      },
      fullName: {
        fullName: {
          authentication (value) {
            return (/^[a-zA-Z]([-']?[a-zA-Z]+)*( [a-zA-Z]([-']?[a-zA-Z]+)*)+$/.test(value))
          },
          required
        }
      },
      phone: {
        phone: {
          authentication (value) {
            return (/^(\+\d{1,2}[-]?)?\d{11}$/.test(value))
          },
          required
        }
      }
    }
  },
  components: {},
  watch: {},
  computed: {
    ...mapStateVModel('sign', ['sweetAlert_showing']),
    ...mapStateVModel('ic_loader', ['loader']),
    EmailExist () {
      return () => {
        let res = this.user_data.map(val => val.email).filter(res => res === this.$v.signUpForm.email.email.$model)
        if (window._.isEmpty(res)) { // from lodash -> window._.isEmpty 
          return false
        } else {
          return true
        }
      }
    },
  },
  methods: {
    async submit() {
      try {
        //  && this.EmailExist === true
        if (this.$v.$invalid) {
          this.submitStatus = await 'failed'
        } else if (this.EmailExist() === true) {
          this.submitStatus = await 'emailNotAvailable'
        } else {
          this.submitStatus = await 'success'
          this.loader = await true
          // Create User_id - USERIST
          let userCreate = await SignUpM.create({
            email: this.signUpForm.email.email,
            password: this.signUpForm.password.password,
            name: this.signUpForm.fullName.fullName,
            phone: this.signUpForm.phone.phone
          })        

          // Create Account_Id - LEANIST
          await AccountLeanist.create({
            user: userCreate.data.user.id
          })
          
          // Create Account_Id - IDIST        
          await AccountIdist.create({
            user: userCreate.data.user.id
          })
          this.loader = await false
          this.sweetAlert_showing = await true
          await this.$swal('Success', 'Account successfully created', 'success')
        }
      } catch (error) {
        if(error.response.status === 400) {
          await this.$swal('Error', 'Account already created', 'error')
        }
        
      }
      
    },

    // Used for checking the availability of an email
    async getUser() {
      // this.$store.state.ic_loader.loader = true
      const { data } = await UserM.get()
      this.user_data = data.results
      this.dataReady = true
      // this.$store.state.ic_loader.loader = false
    },
  },
  beforeCreate(){},
  mounted(){},
  created () {
    this.getUser()
  },
}
</script>
