<template>
  <!-- eslint-disable max-len -->
  <div>
    <div class="container">
      <div class="col-sm-12">
        <br />
        <div class="tobuy-img-box">
          <img
            v-if="propertyType === 'Commercial'"
            src="img/Commercial-Property.jpg"
            alt="Timeshare To Buy"
            class="img-fluid"
            style="width:800px;height:400px; border-radius:10px"
          />
          <img
            v-else
            src="img/Listing3.2.jpg"
            alt="Timeshare To Buy"
            class="img-fluid"
            style="width:800px;height:400px; border-radius:10px"
          />
        </div>
        <div class="sinse-box" style="opacity:0.7; border: white solid 3px; border-radius: 15px">
          <h3 class="sinse-title">List {{ propertyType }} {{ salesType }} Property</h3>
        </div>
      </div>
      <br />
      <div class="row">
        <div class="container col-md-10">
          <div class="title-box-d">
            <h5 class="title-d" style="text-align:left">Property Overview</h5>
          </div>
        </div>
      </div>
      <div class="row mb-3">
        <div class="container col-md-10" style="text-align:left">
          <form id="mainForm">
            <div class="form-goup row">
              <div class="col-md-4">
                <label>Usage Type</label>
                <div class="input-group-prepend">
                  <span class="input-group-text" style="color: #60CBEB">
                    <b>U</b>
                  </span>
                  <select
                    class="form-control"
                    name="propertyUsageType"
                    id="propertyUsageType"
                    v-model="propertyType"
                    @change="TypeChanged"
                  >
                    <option value="Residential">Residential</option>
                    <option value="Commercial">Commercial</option>
                  </select>
                </div>
              </div>
            </div>
            <br />
            <div class="form-group row">
              <div class="col-md-4">
                <label>Property Type *</label>
                <div class="input-group-prepend">
                  <span class="input-group-text" style="color: #60CBEB">
                    <b>T</b>
                  </span>
                  <select
                    class="form-control"
                    name="propertyType"
                    id="propertyType"
                    v-model="property.propertyTypeId"
                    @change="PropertyTypeSelected"
                  >
                    <option value="0">Please select type</option>
                    <option v-for="item in propertyTypes" :value="item.id" :key="item.id">{{
                      item.description
                    }}</option>
                  </select>
                </div>
                <div v-if="showPropertyTypeError">
                  <p class="alert myError">Please select a type</p>
                </div>
              </div>
              <div v-if="propertyType === 'Commercial'" class="col-md-4">
                <label>Property Name</label>
                <div class="input-group-prepend">
                  <span class="input-group-text" style="color: #60CBEB">
                    <b>N</b>
                  </span>
                  <input
                    class="form-control"
                    type="text"
                    name="propertyName"
                    id="propertyName"
                    v-model="property.propertyName"
                  />
                </div>
              </div>
              <div v-if="propertyType === 'Commercial'" class="col-md-4">
                <label>Unit</label>
                <div class="input-group-prepend">
                  <span class="input-group-text" style="color: #60CBEB">
                    <b>U#</b>
                  </span>
                  <input
                    class="form-control"
                    type="text"
                    name="unit"
                    id="unit"
                    v-model="property.unit"
                  />
                </div>
              </div>
            </div>
            <div class="form-group row">
              <div class="col-md-6" style="margin-bottom: 1em">
                <label>Street Number</label>
                <div class="input-group-prepend">
                  <span class="input-group-text">
                    <eva-icon name="home-outline" fill="#60CBEB"></eva-icon>
                  </span>
                  <input
                    class="form-control"
                    type="text"
                    name="streetnumber"
                    v-model="property.addressLine1"
                  />
                </div>
              </div>
              <div class="col-md-6" style="margin-bottom: 1em">
                <label>Street Name</label>
                <div class="input-group-prepend">
                  <span class="input-group-text">
                    <eva-icon name="home-outline" fill="#60CBEB"></eva-icon>
                  </span>
                  <input
                    class="form-control"
                    type="text"
                    name="streetname"
                    id="streetname"
                    v-model="property.addressLine2"
                  />
                </div>
              </div>
              <div class="col-md-6" style="margin-bottom: 1em">
                <label>Province *</label>
                <div class="input-group-prepend">
                  <span class="input-group-text">
                    <eva-icon name="home-outline" fill="#60CBEB"></eva-icon>
                  </span>
                  <select
                    class="form-control"
                    name="propertyType"
                    id="propertyType"
                    @change="ProvinceSelected"
                    v-model="property.provinceId"
                  >
                    <option value="0">Please select province</option>
                    <option v-for="province in provinces" :value="province.id" :key="province.id">{{
                      province.description
                    }}</option>
                  </select>
                </div>
                <div v-if="showProvinceError">
                  <p class="alert myError">Please select a Province</p>
                </div>
              </div>

              <div class="col-md-6" style="margin-bottom: 1em">
                <label>City *</label>
                <div class="input-group-prepend">
                  <span class="input-group-text">
                    <eva-icon name="home-outline" fill="#60CBEB"></eva-icon>
                  </span>
                  <select
                    class="form-control"
                    name="propertyType"
                    id="propertyType"
                    @change="CitySelected"
                    v-model="property.cityId"
                  >
                    <option value="0">Please select city</option>
                    <option v-for="city in cities" :value="city.id" :key="city.id">{{
                      city.description
                    }}</option>
                  </select>
                </div>
                <div v-if="showCityError">
                  <p class="alert myError">Please select a City</p>
                </div>
              </div>
              <div class="col-md-6" style="margin-bottom: 1em">
                <label>Suburb *</label>
                <div class="input-group-prepend">
                  <span class="input-group-text">
                    <eva-icon name="home-outline" fill="#60CBEB"></eva-icon>
                  </span>
                  <select
                    class="form-control"
                    name="propertyType"
                    id="suburbselector"
                    v-model="property.suburbId"
                    @change="getPostalCode"
                  >
                    <option value="0">Please select suburb</option>
                    <option v-for="suburb in suburbs" :value="suburb.id" :key="suburb.id">{{
                      suburb.description
                    }}</option>
                  </select>
                </div>
                <div v-if="showSuburbError">
                  <p class="alert myError">Please select a Suburb</p>
                </div>
              </div>
              <div class="col-md-6" style="margin-bottom: 1em">
                <label>Postal Code</label>
                <div class="input-group-prepend">
                  <span class="input-group-text">
                    <eva-icon name="home-outline" fill="#60CBEB"></eva-icon>
                  </span>
                  <input
                    class="form-control"
                    type="text"
                    name="postalcode"
                    v-model="property.addressLine3"
                  />
                </div>
              </div>
            </div>

            <div class="form-group row">
              <div class="col-md-6">
                <label v-if="salesType === 'Rental'">Rental Price</label>
                <label v-if="salesType !== 'Rental'">Sales Price</label>
                <div class="input-group-prepend">
                  <span class="input-group-text" style="color: #60CBEB">
                    <b>R</b>
                  </span>
                  <input
                    class="form-control"
                    type="number"
                    name="price"
                    id="price"
                    placeholder="R"
                    v-model="property.price"
                  />
                </div>
              </div>
              <div class="col-md-6" v-if="salesType === 'Rental'">
                <label>Per</label>
                <div class="input-group-prepend">
                  <span class="input-group-text" style="color: #60CBEB">
                    <b>D/M</b>
                  </span>
                  <select
                    class="form-control"
                    name="propertyType"
                    id="propertyType"
                    v-model="property.pricePer"
                  >
                    <option value>Please select</option>
                    <option value="Month">Month</option>
                    <option value="Day">Day</option>
                  </select>
                </div>
              </div>
            </div>
            <div class="form-group row">
              <div class="col-md-12">
                <label for="Property Description">Description</label>
                <vue-editor v-model="property.description" :editor-toolbar="customToolbar" />
                <br />
                <p>
                  * A listing fee of R380 including VAT is payable to list your Property on the
                  Uni-Vate website
                </p>
              </div>
            </div>
            <div class="form-group row" />
            <UserField
              v-if="(propertyType === 'Residential') & (propertyOverviewFields.length > 0)"
              :fields="propertyOverviewFields[0].fields"
              @UpdateUserDefinedFields="UpdateUserDefinedFields"
              :id="1"
            ></UserField>
            <div class="form-group row" />
            <div v-for="item in propertyFields" :key="item.id">
              <div class="row">
                <div class="col-sm-12">
                  <div class="title-box-d">
                    <h5 class="title-d">{{ item.name }}</h5>
                  </div>
                </div>
              </div>
              <UserField
                :fields="item.fields"
                :id="item.name"
                @UpdateUserDefinedFields="UpdateUserDefinedFields"
                :fieldValues="item.fields"
              />
            </div>
            <div class="form-group row" />
            <div class="row">
              <div class="col-sm-12">
                <div class="title-box-d">
                  <h5 class="title-d">Media</h5>
                </div>
              </div>
            </div>
            <div class="form-group row">
              <div class="col-md-12">
                <label>Virtual Tour (URL)</label>
                <div class="input-group-prepend">
                  <span class="input-group-text" style="color: #60CBEB">
                    <b>VT</b>
                  </span>
                  <input
                    class="form-control"
                    type="link"
                    name="vtlink"
                    id="vtlink"
                    v-model="property.virtualTour"
                  />
                </div>
              </div>
            </div>
            <div class="form-group row">
              <div class="col-md-12">
                <label>Video (URL)</label>
                <div class="input-group-prepend">
                  <span class="input-group-text" style="color: #60CBEB">
                    <b>V</b>
                  </span>
                  <input
                    class="form-control"
                    type="link"
                    name="vlink"
                    id="vlink"
                    v-model="property.video"
                  />
                </div>
              </div>
            </div>
            <div class="form-group row">
              <div class="col-md-6">
                <label>Images</label>
                <div class="input-group-prepend"></div>
              </div>
            </div>
            <ImageLoad
              :loadedImages="loadedImages"
              :savedImages="propertyImages"
              @DefaultImage="UpdateDefaultImage"
            />
            <button
              v-if="!wait"
              type="button"
              @click="SubmitData()"
              class="btn btn-b-n"
              style="width: 85px; height:40px;"
            >
              Save
            </button>
            <div
              v-if="showPropertyTypeError || showProvinceError || showCityError || showSuburbError"
            >
              <p class="alert myError">
                Missing fields. Please fill in all required fields. Marked with *
              </p>
            </div>
            <div v-if="wait" id="preloader"></div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { VueEditor } from 'vue2-editor';
import UserField from './propertyUserField.vue';
import ImageLoad from './propertyImage.vue';

export default {
  name: 'PropertyCreate',
  components: {
    UserField,
    ImageLoad,
    VueEditor,
  },
  data() {
    return {
      propertyType: 'Residential',
      salesType: 'Rental',
      selectedProvince: '',
      selectedCity: '',
      images: [],
      propertyFieldValues: [],
      defaultImage: 0,
      wait: false,
      customToolbar: [
        [{ header: [false, 1, 2, 3, 4, 5, 6] }],
        ['bold', 'italic', 'underline', 'strike'],
        [{ align: '' }, { align: 'center' }, { align: 'right' }, { align: 'justify' }],
        [{ list: 'ordered' }, { list: 'bullet' }, { list: 'check' }],
        [{ script: 'sub' }, { script: 'super' }],
        [{ indent: '-1' }, { indent: '+1' }],
      ],
      error: '',
      showPropertyTypeError: false,
      showProvinceError: false,
      showCityError: false,
      showSuburbError: false,
    };
  },
  methods: {
    ...mapActions('searchTab', ['getProvince', 'getCities', 'getSuburbs']),
    ...mapActions('property', [
      'getPropertyTypes',
      'getPropertyOverviewFields',
      'getPropertyFields',
      'saveProperty',
      'getProperty',
      'getPropertyImages',
      'clearProperty',
      'clearPropertyImages',
      'getPropertyEditDisplay',
      'getPropertySavedOverviewFields',
      'getPropertySavedFields',
      'getSavedPropertyData',
    ]),
    TypeChanged() {
      this.propertyType = this.property.propertyUsageType;
    },
    SubmitData() {
      if (this.property.propertyTypeId === 0) {
        this.showPropertyTypeError = true;
      }
      if (this.property.provinceId === 0) {
        this.showProvinceError = true;
      }
      if (this.property.cityId === 0) {
        this.showCityError = true;
      }
      if (this.property.suburbId === 0) {
        this.showSuburbError = true;
      }

      if (
        this.showPropertyTypeError
        || this.showProvinceError
        || this.showCityError
        || this.showSuburbError
      ) {
        return;
      }

      this.wait = true;
      if (this.salesType === 'Sale') {
        this.property.isSale = true;
      }
      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < this.images.length; i++) {
        let setAsDefault = false;
        if (i === this.defaultImage) {
          setAsDefault = true;
        }
        this.property.propertyImages.push({
          image: this.images[i],
          isDefault: setAsDefault,
        });
      }
      this.property.propertyUserFields = this.propertyFieldValues;

      if (this.user) {
        this.property.userId = this.user.id;
      }

      this.saveProperty(this.property)
        .then((fulfilled) => {
          this.$router.push(`/property/property/${fulfilled.data.id}`);
        })
        .catch((error) => {
          console.log(error.message);
        });
    },
    Close() {
      this.$router.push('/property/admin/list/my');
    },
    PropertyTypeSelected(item) {
      if (item.target.options.selectedIndex > 0) {
        this.showPropertyTypeError = false;
      } else {
        this.showPropertyTypeError = true;
      }
    },
    ProvinceSelected(item) {
      if (item.target.options.selectedIndex > 0) {
        this.selectedProvince = this.provinces[item.target.options.selectedIndex - 1].description;
        this.getCities(Object.assign({}, { province: this.selectedProvince }));
        this.showProvinceError = false;
      } else {
        this.showProvinceError = true;
      }
    },
    CitySelected(item) {
      if (item.target.options.selectedIndex > 0) {
        this.selectedCity = this.cities[item.target.options.selectedIndex - 1].description;
        this.getSuburbs(
          Object.assign({}, { province: this.selectedProvince, city: this.selectedCity }),
        );
        this.showCityError = false;
      } else {
        this.showCityError = true;
      }
    },
    getPostalCode(item) {
      this.property.addressLine3 = this.suburbs[item.target.options.selectedIndex - 1].postalCode;
      if (item.target.options.selectedIndex > 0) {
        this.showSuburbError = false;
      } else {
        this.showSuburbError = true;
      }
    },
    loadedImages(values) {
      this.images = values;
    },
    UpdateUserDefinedFields(item) {
      let update = false;
      this.propertyFieldValues.forEach((element) => {
        if (element.userDefinedFieldId === item.userDefinedFieldId) {
          element.value = item.value;
          update = true;
        }
      });
      if (!update) {
        this.propertyFieldValues.push(item);
      }
    },
    UpdateDefaultImage(item) {
      this.defaultImage = item;
    },
  },
  mounted() {
    this.wait = false;
    this.clearProperty();
    this.clearPropertyImages();
    this.images = [];
    this.defaultImage = 0;

    if (this.propertyOverviewFields.length > 0) {
      this.propertyOverviewFields = [];
    }
    if (this.propertyFields.length > 0) {
      this.propertyFields = [];
    }
    if (this.property.description !== '') {
      this.property.description = '';
    }

    if (this.$route.params.propertyUsageType) {
      this.propertyType = this.$route.params.propertyUsageType;
    }
    this.salesType = this.$route.params.saleType;

    this.getPropertyTypes(this.propertyType);

    this.getProvince();
    this.getPropertyOverviewFields();
    this.getPropertyFields(this.propertyType);
  },
  computed: {
    ...mapState('searchTab', ['provinces', 'cities', 'suburbs']),
    ...mapState('property', [
      'propertyTypes',
      'propertyOverviewFields',
      'propertyFields',
      'property',
      'propertyImages',
    ]),
    ...mapState('authentication', ['user']),
    SalesTypeChanged() {
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      // this.propertyType = this.$route.params.propType;
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      this.salesType = this.$route.params.saleType;
      if (this.property && this.property.propertyUsageType) {
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        this.propertyType = this.property.propertyUsageType;
      }

      if (!this.$route.query.id) {
        this.getPropertyFields(this.propertyType);
      }

      this.getPropertyTypes(this.propertyType);

      return this.propertyType;
    },
  },
  watch: {
    SalesTypeChanged() {
      return null;
    },
  },
};
</script>
