<template>
  <main id="main" style="margin-top: 200px; padding-bottom: 50px;">
    <div class="container">
      <div class="form">
        <div class="row">
          <div class="col">
            <div class="section-header">
              <h2>Property User Defined Group</h2>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="checkAccess">
      <div v-if="showField === false">
        <div class="container">
          <div class="form">
            <div class="row mb-3">
              <div class="col-md-12">
                <form id="mainForm">
                  <div v-if="userDefinedGroup" class="form-group row">
                    <div class="form-group col-md-4">
                      <float-label fixed label="Description">
                        <input
                          class="form-control uniInput"
                          type="text"
                          name="description"
                          id="description"
                          v-model="userDefinedGroup.description"
                          placeholder="Description"
                          v-bind:class="{
                            'is-valid': userDefinedGroup.description,
                            'is-invalid':
                              !requiredField(userDefinedGroup.description) &&
                              descriptionLoad,
                          }"
                          v-on:keyup="descriptionLoad = true"
                          v-on:blur="descriptionLoad = true"
                        />
                        <div class="invalid-feedback">
                          Description is Required!
                        </div>
                      </float-label>
                    </div>

                    <div class="form-group col-md-4">
                      <float-label fixed label="Property Usage Type">
                        <select
                          class="form-control uniSelect"
                          name="UsageType"
                          id="UsageType"
                          v-model="userDefinedGroup.usageType"
                          placeholder="Property Usage Type"
                          v-bind:class="{
                            'is-valid': userDefinedGroup.usageType,
                          }"
                        >
                          <option value="0">Residential</option>
                          <option value="1">Commercial</option>
                          <option value="2">Both</option>
                        </select>
                      </float-label>
                    </div>
                    <div class="col-md-4">
                      <float-label fixed label="Order">
                        <input
                          class="form-control uniInput"
                          type="number"
                          name="rank"
                          id="rank"
                          v-model="userDefinedGroup.rank"
                          placeholder="Order"
                          v-bind:class="{
                            'is-valid': userDefinedGroup.rank,
                          }"
                        />
                      </float-label>
                    </div>
                  </div>
                  <div v-if="!userDefinedGroup" class="form-group row">
                    <div class="form-group col-md-4">
                      <label>Description</label>
                      <input
                        class="form-control"
                        type="text"
                        name="description"
                        id="description"
                        v-model="group.description"
                      />
                    </div>
                    <div class="col-md-4">
                      <label>Property Usage Type</label>
                      <select
                        class="form-control"
                        name="UsageType"
                        id="UsageType"
                        v-model="group.usageType"
                      >
                        <option value="0">Residential</option>
                        <option value="1">Commercial</option>
                        <option value="2">Both</option>
                      </select>
                    </div>
                    <div class="col-md-4">
                      <label>Order</label>
                      <input
                        class="form-control"
                        type="number"
                        name="rank"
                        id="rank"
                        v-model="group.rank"
                        v-bind:class="{
                          'is-valid': group.rank,
                        }"
                      />
                    </div>
                  </div>
                </form>
              </div>
            </div>
            <!--            <div class="row">
              <div class="col">
                <listView
                  :items="userFields"
                  :showNew="true"
                  :editable="true"
                  :deleteable="true"
                  :displayColumns="columns"
                  :sortKey="'rank'"
                  @onEdit="Edit"
                  @onDelete="Delete"
                  @onNew="newItem"
                />
              </div>
            </div>
            -->
            <div v-if="boolValidationError" class="row">
              <div class="col">
                <alert :text="errorMessage" :type="errorOccurred" />
              </div>
            </div>
            <div class="row">
              <div class="col">
                <button
                  type="button"
                  @click="SubmitData()"
                  class="btn-white-border mb-5"
                >
                  Save
                </button>
                <button type="button" @click="Close()" class="btn-white-border">
                  Close
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-else>
        <userFields @UpdateUserField="UpdateUserField" :field="item" />
      </div>
    </div>
    <div v-else>
      <alert
        :text="'You don\'t have permission to view this page'"
        :type="'ERROR'"
      />
    </div>
  </main>
</template>

<script>
/* eslint-disable */
import { mapState, mapActions } from 'vuex'

import Log from '../../../assets/Log'
import alert from '../../shared/alert'
import userFields from './userDefinedField.vue'
import listView from '../../shared/listView.vue'

export default {
  name: 'UserDefinedGroup',
  components: {
    userFields,
    listView,
    alert,
  },
  data() {
    return {
      item: {},
      showField: false,
      errorOccurred: '',
      errorMessage: '',
      boolMessage: false,
      boolValidationError: false,
      descriptionLoad: false,
      columns: ['fieldName', 'fieldType', 'rank'],
    }
  },
  mounted() {
    this.clearUserFields()
    this.clearUserGroup()

    if (this.$route.params.id > 0) {
      this.getUserDefinedGroup(this.$route.params.id)
      this.getUserFields(this.$route.params.id)
    }
  },
  computed: {
    ...mapState('propertyAdmin', [
      'userDefinedGroup',
      'userFields',
      'userField',
    ]),
    checkAccess() {
      if (Log.getUser().role === 'Super Admin') {
        return true
      } else {
        return false
      }
    },
  },
  methods: {
    ...mapActions('propertyAdmin', [
      'getUserDefinedGroup',
      'getUserFields',
      'saveUserDefinedGroup',
      'updateUserDefinedGroup',
      'clearUserGroup',
      'clearUserFields',
      'clearUserField',
      'saveUserField',
      'updateUserField',
      'deleteUserField',
    ]),
    SubmitData() {
      if (this.validatePage()) {
        console.log('SubmitData')
        this.userDefinedGroup.fields = []
        let reload = false
        if (this.$route.params.id > 0) {
          this.updateUserDefinedGroup(this.userDefinedGroup)
          this.userFields.forEach((fieldData) => {
            if (fieldData.id === 0) {
              fieldData.groupId = this.userDefinedGroup.id
              this.saveUserField(fieldData)
            } else {
              this.updateUserField(fieldData)
            }
          })
        } else {
          reload = true
          this.userFields.forEach((fieldData) => {
            this.userDefinedGroup.fields.push({
              fieldName: fieldData.fieldName,
              fieldType: fieldData.fieldType,
              rank: fieldData.rank,
            })
          })
          this.saveUserDefinedGroup(this.userDefinedGroup)
        }
        this.$router.push('/userDefinedGroups/list')
        // this.$router.push({
        //   path: '/userDefinedGroups/list',
        //   query: { reload },
        // });
      }
    },
    newItem() {
      this.clearUserField()
      this.item = this.userField
      this.item.groupId = this.userDefinedGroup.id
      this.showField = true
    },
    Edit(item) {
      this.item = item
      this.showField = true
    },
    Close() {
      this.$router.push('/userDefinedGroups/list')
    },
    UpdateUserField(item) {
      if (item.id === 0) {
        this.userFields.push(item)
      }
      this.showField = false
    },
    Delete(item) {
      console.log(item)

      if (item.id === 0) {
        this.userFields.pop(this.userFields.find((p) => p.id === item.id))
      } else {
        this.deleteUserField(item.id)
      }
    },
    requiredField: function (tfield) {
      if (tfield) {
        return true
      } else {
        return false
      }
    },
    validatePage: function () {
      console.log('validatePage')
      if (this.userDefinedGroup.description) {
        console.log('passed')
        this.errorOccurred = ''
        this.errorMessage = ''
        this.boolValidationError = false
        return true
      } else {
        console.log('failed')
        this.descriptionLoad = true
        this.boolValidationError = true
        this.errorOccurred = 'ERROR'
        this.errorMessage = 'Please check form and correct all input fields!'
        return false
      }
    },
  },
}
</script>
