<template>
  <main id="main" style="margin-top: -20px; padding-bottom: 50px;">
    <!-- eslint-disable max-len -->
    <div class="container">
      <div class="form">
        <br />
        <div>
          <div class="section-header">
            <h2>Update Profile Info</h2>
          </div>
        </div>
        <div v-if="!isAgent()" class="row mb-4">
          <div class="col">
            <div class="section-header">
              <h2>Detailed Individual Information</h2>
            </div>
          </div>
        </div>
        <div v-else class="row mb-4">
          <div class="col">
            <div class="section-header">
              <h2>Detailed Agent Information</h2>
            </div>
          </div>
        </div>
        <!-- <DetailIndividual :currentUser="user" :showBank="true" :showAddress="true" /> -->
        <div class="row mb-4">
          <div class="col-md-6">
            <float-label fixed label="Username">
              <input
                type="text"
                name="username"
                class="form-control uniInput"
                id="username"
                placeholder="Name"
                data-rule="minlen:4"
                data-msg="Please enter your name"
                v-model="individual.user.username"
                v-bind:class="{
                  'is-valid': individual.user.username,
                  'is-invalid':
                    !requiredField(individual.user.username) && usernameLoad,
                }"
                v-on:keyup="usernameLoad = true"
                v-on:blur="usernameLoad = true"
              />
              <div class="invalid-feedback">Username is Required!</div>
            </float-label>
          </div>
        </div>
        <div class="row mb-2">
          <div class="form-group col-md-6">
            <float-label>
              <input
                type="text"
                name="name"
                class="form-control uniInput"
                id="name"
                placeholder="Name"
                data-rule="minlen:4"
                data-msg="Please enter your name"
                v-model="individual.name"
                v-bind:class="{
                  'is-valid': individual.name,
                  'is-invalid': !requiredField(individual.name) && nameLoad,
                }"
                v-on:keyup="nameLoad = true"
                v-on:blur="nameLoad = true"
              />
              <div class="invalid-feedback">Name is Required!</div>
            </float-label>
          </div>
          <div class="form-group col-md-6">
            <float-label>
              <input
                type="text"
                class="form-control uniInput"
                name="surname"
                id="surname"
                placeholder="Surname"
                data-msg="Please enter your surname"
                v-model="individual.surname"
                v-bind:class="{
                  'is-valid': individual.surname,
                  'is-invalid':
                    !requiredField(individual.surname) && surnameLoad,
                }"
                v-on:keyup="surnameLoad = true"
                v-on:blur="surnameLoad = true"
              />
              <div class="invalid-feedback">Surname is Required!</div>
            </float-label>
          </div>
        </div>
        <div class="row mb-2">
          <div v-if="!isAgent()" class="form-group col-md-6">
            <float-label>
              <input
                type="text"
                name="idnum"
                class="form-control uniInput"
                id="idnum"
                placeholder="ID Number"
                data-rule="minlen:4"
                data-msg="Please enter your ID number"
                v-model="individual.idNumber"
                v-bind:class="{
                  'is-valid': individual.idNumber,
                }"
              />
            </float-label>
          </div>
          <div class="form-group col-md-6">
            <float-label>
              <input
                type="text"
                class="form-control uniInput"
                name="email"
                id="email"
                placeholder="Email Address"
                data-msg="Please enter your email address"
                v-model="individual.email"
                v-bind:class="{
                  'is-valid': individual.email,
                  'is-invalid':
                    !validEmail(individual.email) && emailAddressLoad,
                }"
                v-on:keyup="emailAddressLoad = true"
                v-on:blur="emailAddressLoad = true"
              />
              <div class="invalid-feedback">
                Valid Email address is Required!
              </div>
            </float-label>
          </div>
        </div>

        <div v-if="!isAgent()" class="row mb-2">
          <div class="form-group col-md-6">
            <div class="input-group">
              <float-label label="Marital Status" style="width: 100%;">
                <select
                  class="form-control uniSelect"
                  id="howMarried"
                  v-model="individual.howMarried"
                  v-bind:class="{
                    'is-valid': individual.howMarried,
                  }"
                >
                  <option v-bind:value="0">N/A</option>
                  <option v-bind:value="1">In Community Of Property</option>
                  <option v-bind:value="2">Out of Community Of Property</option>
                  <option v-bind:value="3">Other</option>
                  <option v-bind:value="4">Traditional Wedding</option>
                  <option v-bind:value="5">Single</option>
                  <option v-bind:value="6">Divorced</option>
                  <option v-bind:value="7">Widow</option>
                  <option v-bind:value="8">Committed Relationship</option>
                  <option v-bind:value="9">Partner</option>
                </select>
              </float-label>
            </div>
          </div>
          <div class="form-group col-md-6">
            <float-label>
              <input
                type="text"
                class="form-control uniInput"
                name="company"
                id="company"
                placeholder="Company Reg Number"
                data-rule="minlen:4"
                data-msg="Please enter your company reg number"
                v-model="individual.companyRegNumber"
                v-bind:class="{
                  'is-valid': individual.companyRegNumber,
                }"
              />
            </float-label>
          </div>
        </div>
        <div class="row">
          <div class="form-group col-md-6">
            <float-label>
              <input
                type="text"
                name="cell"
                class="form-control uniInput"
                id="cell"
                placeholder="Cell Number"
                data-rule="minlen:4"
                data-msg="Please enter your cell number"
                v-model="individual.cellNumber"
                v-bind:class="{
                  'is-valid':
                    individual.cellNumber &&
                    validPhoneNumber(individual.cellNumber),
                  'is-invalid':
                    !requiredField(individual.cellNumber) ||
                    (individual.cellNumber &&
                      !validPhoneNumber(individual.cellNumber) &&
                      cellNumberLoad),
                }"
                v-on:keyup="cellNumberLoad = true"
                v-on:blur="cellNumberLoad = true"
              />
              <div class="invalid-feedback">
                Valid Cell Number is Required!
              </div>
            </float-label>
          </div>
          <div class="form-group col-md-6">
            <float-label>
              <input
                type="text"
                class="form-control uniInput"
                name="telephone"
                id="telephone"
                placeholder="Telephone Number"
                data-msg="Please enter your Telephone number"
                v-model="individual.telephone"
                v-bind:class="{
                  'is-valid':
                    individual.telephone &&
                    validPhoneNumber(individual.telephone),
                  'is-invalid':
                    individual.telephone &&
                    !validPhoneNumber(individual.telephone),
                }"
              />
              <div class="invalid-feedback">
                Valid telephone number is required!!
              </div>
            </float-label>
          </div>
        </div>

        <div v-if="individual.howMarried === 1" class="section-header">
          <h2>Spouse Details</h2>
        </div>
        <div v-if="individual.howMarried === 1" class="form">
          <div class="form-row mb-2">
            <div class="form-group col-md-6 mt-2">
              <float-label>
                <input
                  type="text"
                  class="form-control uniInput"
                  placeholder="Spouse Name"
                  data-msg="Please enter your spouse's name"
                  v-model="individual.spouseName"
                  v-bind:class="{ 'is-valid': individual.spouseName }"
                />
              </float-label>
            </div>
            <div class="form-group col-md-6 mt-2">
              <float-label>
                <input
                  type="text"
                  class="form-control uniInput"
                  placeholder="Spouse Surname"
                  data-msg="Please enter your spouse's surname"
                  v-model="individual.spouseSurname"
                  v-bind:class="{ 'is-valid': individual.spouseSurname }"
                />
              </float-label>
            </div>
            <div class="form-group col-md-6 mt-2">
              <float-label>
                <input
                  type="text"
                  class="form-control uniInput"
                  placeholder="Spouse Email"
                  data-rule="minlen:4"
                  data-msg="Please enter your spouse's email"
                  v-model="individual.spouseEmail"
                  v-bind:class="{
                    'is-valid': individual.spouseEmail,
                    'is-invalid':
                      !validEmail(individual.spouseEmail) && spouseEmailLoad,
                  }"
                  v-on:keyup="spouseEmailLoad = true"
                  v-on:blur="spouseEmailLoad = true"
                />
                <div class="invalid-feedback">
                  Valid Email address is Required!
                </div>
              </float-label>
            </div>
            <div class="form-group col-md-6 mt-2">
              <float-label>
                <input
                  type="text"
                  class="form-control uniInput"
                  placeholder="Spouse Telephone"
                  data-rule="minlen:4"
                  data-msg="Please enter your spouse's telephone number"
                  v-model="individual.spouseTelephone"
                />
              </float-label>
            </div>
            <div class="form-group col-md-6 mt-2">
              <float-label>
                <input
                  type="text"
                  class="form-control uniInput"
                  placeholder="Spouse Cell Number"
                  data-rule="minlen:4"
                  data-msg="Please enter your spouse's cellphone number"
                  v-model="individual.spouseCellnumber"
                />
              </float-label>

              <div class="validation"></div>
            </div>
          </div>
        </div>
        <div v-if="!isAgent()" class="row">
          <div class="col">
            <div class="section-header">
              <h2>Address</h2>
            </div>
          </div>
        </div>
        <div v-if="!isAgent()" class="row">
          <div class="form-group col-md-12">
            <addressAutoComplete @GoogleAddress="UpdateAddress" />
          </div>
        </div>
        <div v-if="!isAgent()" class="form-row">
          <div class="form-group col-md-6">
            <input
              type="text"
              name="street-nr"
              class="form-control"
              id="street-nr"
              placeholder="Street Number"
              data-rule="minlen:4"
              data-msg="Please enter your street number"
              v-model="individual.address.streetNumber"
              disabled
            />

            <div class="validation"></div>
          </div>
          <div class="form-group col-md-6">
            <input
              type="text"
              class="form-control"
              name="street"
              id="street"
              placeholder="Street Name"
              data-msg="Please enter your street name"
              disabled
              v-model="individual.address.street"
            />
            <div class="validation"></div>
          </div>
          <div class="form-group col-md-6">
            <input
              type="text"
              name="province"
              class="form-control"
              id="province"
              placeholder="Province"
              data-rule="minlen:4"
              data-msg="Please enter your province"
              disabled
              v-model="individual.address.province"
            />
            <div class="validation"></div>
          </div>
          <div class="form-group col-md-6">
            <input
              type="text"
              class="form-control"
              name="city"
              id="city"
              placeholder="City"
              data-rule="minlen:4"
              data-msg="Please enter your city"
              v-model="individual.address.city"
              disabled
            />
            <div class="validation"></div>
          </div>
          <div class="form-group col-md-6">
            <input
              type="text"
              name="suburb"
              class="form-control"
              id="suburb"
              placeholder="Suburb"
              data-rule="minlen:4"
              data-msg="Please enter your suburb"
              v-model="individual.address.suburb"
              disabled
            />
            <div class="validation"></div>
          </div>
          <div class="form-group col-md-6">
            <input
              type="text"
              class="form-control"
              name="postal"
              id="postal"
              placeholder="Postal Code"
              data-msg="Please enter your postal code"
              v-model="individual.address.postalCode"
              disabled
            />
            <div class="validation"></div>
          </div>
        </div>
        <div v-if="pullUserRole === 'Super Admin'">
          <div class="row">
            <div class="col">
              <div class="section-header">
                <h2>Access Control</h2>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-md-6">
              <float-label label="User Role" style="width: 100%;">
                <select
                  class="form-control uniSelect"
                  id="howMarried"
                  v-model="individual.user.role"
                  v-bind:class="{
                    'is-valid': individual.user.role,
                    'is-invalid':
                      !requiredField(individual.user.role) && userRoleLoad,
                  }"
                  v-on:keyup="userRoleLoad = true"
                  v-on:blur="userRoleLoad = true"
                >
                  <option
                    v-for="role in getRoles"
                    :key="role.id"
                    :value="role.roleName"
                  >
                    {{ role.roleName }}
                  </option>
                </select>
                <div class="invalid-feedback">
                  User Role is Required!
                </div>
              </float-label>
            </div>
            <div class="col-md-6">
              <input
                class="mr-2 mt-3"
                name="changePass"
                type="checkbox"
                v-model="individual.user.loginPasswordChange"
              />
              <label for="changePass">Change Password on Next Login</label>
            </div>
          </div>
          <div class="row mt-4">
            <div class="col-md-6">
              <float-label fixed label="Agency" style="width: 100%;">
                <select
                  class="form-control uniSelect"
                  v-model="individual.agencyId"
                  v-bind:class="{
                    'is-valid': individual.agencyId,
                    'is-invalid':
                      !requiredField(individual.agencyId) && inputAgencyLoad,
                  }"
                  v-on:keyup="inputAgencyLoad = true"
                  v-on:blur="inputAgencyLoad = true"
                >
                  <option value="">Private User</option>
                  <option
                    v-for="(item, i) in agencies"
                    :key="i"
                    :value="item.id"
                  >
                    {{ item.agencyName }}
                  </option>
                </select>
              </float-label>
            </div>
          </div>
        </div>
        <div class="row">
          <div v-if="boolMessage" class="row">
            <div class="col">
              <alert
                :text="'Your Information has been updated!'"
                :type="'SUCCESS'"
              />
            </div>
          </div>
          <div v-if="boolValidationError" class="row">
            <div class="col">
              <alert :text="errorMessage" :type="errorOccurred" />
            </div>
          </div>
        </div>
        <div class="row mt-5">
          <div class="col">
            <button class="btn-white-border" @click="sendToApi()">
              Update
            </button>
          </div>
          <div class="col">
            <router-link
              v-if="pullUserRole === 'Super Admin'"
              class="btn-white-border"
              to="/status/userManagementPage"
            >
              Cancel
            </router-link>
          </div>
        </div>
      </div>
    </div>
  </main>
</template>

<script>
/* eslint-disable */
import { mapState, mapActions, mapGetters } from 'vuex'
import DetailIndividual from './timeshareIndividual.vue'
import addressAutoComplete from '../shared/addressAutoComplete'
import Log from '../../assets/Log'
import Alert from '../shared/alert'
import logOutVue from './logOut.vue'

export default {
  name: 'UpdateInfo',
  data() {
    return {
      selectedItem: {},
      individual: {},
      errorOccurred: '',
      errorMessage: '',
      boolMessage: false,
      boolValidationError: false,
      usernameLoad: false,
      nameLoad: false,
      surnameLoad: false,
      emailAddressLoad: false,
      cellNumberLoad: false,
      landlineNumberLoad: false,
      spouseEmailLoad: false,
      userRoleLoad: false,
      inputAgencyLoad: false,
    }
  },
  props: {},
  components: {
    DetailIndividual,
    addressAutoComplete,
    Alert,
  },
  mounted() {
    this.selectedItem = this.currentUser
  },
  created() {
    this.retrieveUserRoles()
    this.getIndividual(Log.getUser().id).then(() => {
      if (this.$route.params.indivParam) {
        this.individual = this.$route.params.indivParam

        if (this.individual.address === null) {
          this.individual.address = {}
        }

        if (
          this.individual.user.role === 'Agent' ||
          this.individual.user.role === 'Agency' ||
          this.individual.user.role === 'Managment Agent'
        ) {
          this.getAgentById(this.individual.userId)
          this.individual.agencyId = this.agent[0].agencyId
        }
      } else {
        this.individual = this.indiv
        this.individual.email = this.indiv.emailAddress
        this.individual.user = Log.getUser()
      }
      this.getAgencies()
    })
  },
  computed: {
    ...mapState('individual', ['indiv']),
    ...mapState('authentication', ['isLoggedIn', 'user']),
    ...mapState('register', ['agent', 'agencies']),
    ...mapGetters({
      user: 'authentication/getUser',
      person: 'authentication/getPerson',
    }),
    ...mapGetters('role', ['getRoles']),
    isLoggedIn() {
      return this.user && this.person
    },
    pullUserRole() {
      return Log.getUser().role
    },
  },
  methods: {
    ...mapActions('individual', ['getIndividual', 'updateIndividual']),
    ...mapActions('role', ['retrieveUserRoles']),
    ...mapActions('register', ['getAgentById', 'getAgencies', 'saveAgent']),
    onSelectedItemItemChange(item) {
      this.currentUser = item
    },
    isAgent() {
      if (
        this.individual.user.role === 'Agency' ||
        this.individual.user.role === 'Agent' ||
        this.individual.user.role === 'Managing Agent'
      ) {
        return true
      } else {
        return false
      }
    },
    UpdateAddress(address) {
      this.individual.address.streetNumber = address.streetNumber
      this.individual.address.street = address.streetName
      this.individual.address.province = address.province
      this.individual.address.city = address.city
      this.individual.address.suburb = address.suburb
      this.individual.address.postalCode = address.postalCode
    },

    sendToApi() {
      this.boolValidationError = false
      this.boolMessage = false
      this.individual.emailAddress = this.individual.email
      if (this.validatePage()) {
        if (!this.boolValidationError) {
          if (
            this.individual.user.role === 'Agency' ||
            this.individual.user.role === 'Agent' ||
            this.individual.user.role === 'Managing Agent'
          ) {
            this.saveAgent(this.individual)
              .then(() => {
                this.boolMessage = true
                if (Log.getUser().role === 'Super Admin') {
                  if (
                    this.individual.id ===
                    JSON.parse(localStorage.getItem('person')).id
                  ) {
                    var newPerson = {
                      id: JSON.parse(localStorage.getItem('person')).id,
                      email: this.individual.email,
                      fullname:
                        this.individual.name + ' ' + this.individual.surname,
                      name: this.individual.name,
                      surname: this.individual.surname,
                    }
                    localStorage.setItem('person', JSON.stringify(newPerson))
                    this.$router.go()
                  }
                  this.$router.push('/status/userManagementPage')
                } else {
                  var newPerson = {
                    id: JSON.parse(localStorage.getItem('person')).id,
                    email: this.individual.email,
                    fullname:
                      this.individual.name + ' ' + this.individual.surname,
                    name: this.individual.name,
                    surname: this.individual.surname,
                  }
                  localStorage.setItem('person', JSON.stringify(newPerson))
                  this.$router.go()
                }
              })
              .catch((err) => {
                this.errorOccurred = 'ERROR'
                this.errorMessage = 'Server Error: CONNECTION_REFUSED'
                if (err.status) {
                  if (err.data.message) {
                    this.errorMessage = err.data.message
                  } else {
                    this.errorMessage = err
                  }
                }
              })
          } else {
            this.updateIndividual(this.individual).then(() => {
              this.boolMessage = true
              if (Log.getUser().role === 'Super Admin') {
                if (
                  this.individual.id ===
                  JSON.parse(localStorage.getItem('person')).id
                ) {
                  var newPerson = {
                    id: JSON.parse(localStorage.getItem('person')).id,
                    email: this.individual.email,
                    fullname:
                      this.individual.name + ' ' + this.individual.surname,
                    name: this.individual.name,
                    surname: this.individual.surname,
                  }
                  localStorage.setItem('person', JSON.stringify(newPerson))
                  //this.$router.go()
                }
                //this.$router.push('/status/userManagementPage')
              } else {
                var newPerson = {
                  id: JSON.parse(localStorage.getItem('person')).id,
                  email: this.individual.email,
                  fullname:
                    this.individual.name + ' ' + this.individual.surname,
                  name: this.individual.name,
                  surname: this.individual.surname,
                }
                localStorage.setItem('person', JSON.stringify(newPerson))
                //this.$router.go()
              }
            })
          }
        }
      }
    },
    requiredField: function (tfield) {
      if (tfield) {
        return true
      } else {
        return false
      }
    },
    validEmail: function (email) {
      var re = /(.+)@(.+){2,}\.(.+){2,}/
      if (email) {
        return re.test(email.toLowerCase())
      } else {
        return re.test(email)
      }
    },
    validPhoneNumber(number) {
      if (number) {
        const rx = /^\(?\d{3}\)?[-\s]?\d{3}[-\s]?\d{4}$/
        // const rx = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im
        return rx.test(String(number))
      } else {
        return true
      }
    },
    validatePage: function () {
      if (
        this.individual.name &&
        this.individual.surname &&
        this.individual.emailAddress &&
        this.individual.cellNumber &&
        this.individual.user.role &&
        this.validEmail(this.individual.emailAddress) &&
        this.validPhoneNumber(this.individual.cellNumber) &&
        this.validPhoneNumber(this.individual.telephone)
      ) {
        this.errorOccurred = ''
        this.errorMessage = ''
        this.boolValidationError = false

        return true
      } else {
        this.nameLoad = true
        this.surnameLoad = true
        this.emailAddressLoadLoad = true
        this.cellNumberLoad = true
        this.telephoneLoad = true
        this.userRoleLoad = true
        this.boolValidationError = true
        this.errorOccurred = 'ERROR'
        this.errorMessage = 'Please check form and correct all input fields!'
        return false
      }
    },
  },
}
</script>
<style>
.myWell {
  width: 100%;
  background-color: #60cbeb;
  border-radius: 6px;
  padding: 5px;
  margin: 3px;
}
</style>
