<template>
  <main id="main">
    <section id="contact2">
      <div class="container">
        <div class="form">
          <div class="row">
            <div class="section-header">
              <h2>update agent info</h2>
            </div>
          </div>
          <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="Username"
                  data-rule="minlen:4"
                  data-msg="please enter your username"
                  v-model="agent.user.username"
                  v-bind:class="{
                    'is-valid': agent.user.username,
                    'is-invalid':
                      !requiredField(agent.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 class="form-group col-md-6">
              <float-label fixed label="Name">
                <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="agent.name"
                  v-bind:class="{
                    'is-valid': agent.name,
                    'is-invalid': !requiredField(agent.name) && nameLoad,
                  }"
                  v-on:keyup="nameLoad = true"
                  v-on:blur="nameLoad = true"
                />
                <div class="invalid-feedback">Name is Required!</div>
              </float-label>
            </div>
          </div>
          <div class="row mt-4">
            <div class="form-group col-md-6">
              <float-label fixed label="Surname">
                <input
                  type="text"
                  class="form-control uniInput"
                  name="surname"
                  id="surname"
                  placeholder="Surname"
                  data-msg="Please enter your surname"
                  v-model="agent.surname"
                  v-bind:class="{
                    'is-valid': agent.surname,
                    'is-invalid': !requiredField(agent.surname) && surnameLoad,
                  }"
                  v-on:keyup="surnameLoad = true"
                  v-on:blur="surnameLoad = true"
                />
                <div class="invalid-feedback">Surname is Required!</div>
              </float-label>
            </div>
            <div class="form-group col-md-6">
              <float-label fixed label="Email">
                <input
                  type="text"
                  class="form-control uniInput"
                  name="email"
                  id="email"
                  placeholder="Email Address"
                  data-msg="Please enter your email address"
                  v-model="agent.email"
                  v-bind:class="{
                    'is-valid': agent.email && validEmail(agent.email),
                    'is-invalid': !validEmail(agent.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 class="row mt-4">
            <div class="form-group col-md-6">
              <float-label fixed label="Cell Number">
                <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="agent.cellNumber"
                  v-bind:class="{
                    'is-valid':
                      agent.cellNumber && validPhoneNumber(agent.cellNumber),
                    'is-invalid':
                      !requiredField(agent.cellNumber) ||
                      (agent.cellNumber &&
                        !validPhoneNumber(agent.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 fixed label="Telephone Number">
                <input
                  type="text"
                  class="form-control uniInput"
                  name="telephone"
                  id="telephone"
                  placeholder="Telephone Number"
                  data-msg="Please enter your Telephone number"
                  v-model="agent.telephone"
                  v-bind:class="{
                    'is-valid':
                      agent.telephone && validPhoneNumber(agent.telephone),
                    'is-invalid':
                      agent.telephone && !validPhoneNumber(agent.telephone),
                  }"
                />
                <div class="invalid-feedback">
                  Valid telephone number is required!!
                </div>
              </float-label>
            </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="agent.agencyId"
                    v-bind:class="{
                      'is-valid': agent.agencyId,
                      'is-invalid':
                        !requiredField(agent.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 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="agent.user.role"
                      v-bind:class="{
                        'is-valid': agent.user.role,
                        'is-invalid':
                          !requiredField(agent.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="agent.user.loginPasswordChange"
                  />
                  <label for="changePass">Change Password on Next Login</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 mb-5">
              <div class="col">
                <button class="btn-white-border" @click="sendToApi()">
                  Update
                </button>
              </div>
              <div class="col">
                <button class="btn-white-border" @click="$router.go(-1)">
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </main>
</template>

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

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

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

        if (
          this.agent.user.role === 'Agent' ||
          this.agent.user.role === 'Agency' ||
          this.agent.user.role === 'Management Agent'
        ) {
          this.getAgentById(this.agent.userId)
          this.agent.agencyId = this.agent.agencyId
        }
      } else {
        this.agent = this.indiv
        this.agent.email = this.indiv.emailAddress
        this.agent.user = Log.getUser()
      }
    })
    this.getAgencies()
    this.selectedItem = this.currentUser
  },
  computed: {
    ...mapState('individual', ['indiv']),
    ...mapState('register', ['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',
      'updateAgent',
    ]),
    onSelectedItemItemChange(item) {
      this.currentUser = item
    },
    sendToApi() {
      this.boolError = false
      this.agent.fullName = this.agent.name + ' ' + this.agent.surname
      this.agent.emailAddress = this.agent.email
      if (this.validatePage()) {
        if (!this.boolValidationError) {
          if (
            this.agent.user.role === 'Agent' ||
            this.agent.user.role === 'Agency' ||
            this.agent.user.role === 'Managing Agent'
          ) {
            this.saveAgent(this.agent)
              .then(() => {
                this.boolMessage = true
                if (Log.getUser().role === 'Super Admin') {
                  if (
                    this.agent.id ===
                    JSON.parse(localStorage.getItem('person')).id
                  ) {
                    var newPerson = {
                      id: JSON.parse(localStorage.getItem('person')).id,
                      email: this.agent.email,
                      fullname: this.agent.name + ' ' + this.agent.surname,
                      name: this.agent.name,
                      surname: this.agent.surname,
                    }
                    localStorage.setItem('person', JSON.stringify(newPerson))
                    this.$router.go()
                  }
                  //this.$router.push('/status/agentuserManagementPage')
                } else {
                  var newPerson = {
                    id: JSON.parse(localStorage.getItem('person')).id,
                    email: this.agent.email,
                    fullname: this.agent.name + ' ' + this.agent.surname,
                    name: this.agent.name,
                    surname: this.agent.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.updateAgent(this.agent).then(() => {
              this.boolMessage = true
              if (Log.getUser().role === 'Super Admin') {
                if (
                  this.agent.id ===
                  JSON.parse(localStorage.getItem('person')).id
                ) {
                  var newPerson = {
                    id: JSON.parse(localStorage.getItem('person')).id,
                    email: this.agent.email,
                    fullname: this.agent.name + ' ' + this.agent.surname,
                    name: this.agent.name,
                    surname: this.agent.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.agent.email,
                  fullname: this.agent.name + ' ' + this.agent.surname,
                  name: this.agent.name,
                  surname: this.agent.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.agent.name &&
        this.agent.surname &&
        this.agent.emailAddress &&
        this.agent.cellNumber &&
        this.agent.user.role &&
        this.validEmail(this.agent.emailAddress) &&
        this.validPhoneNumber(this.agent.cellNumber) &&
        this.validPhoneNumber(this.agent.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 lang="scss" scoped></style>
