<template>
  <div>
    <carouselSection :salesType="salesType" />

    <main id="main" style="margin-top:-20px">
      <div class="container pt-5 pb-5">
        <div class="row">
          <div class="col-md-6">
            <div v-if="!property.propertyName">
              <label for="propertyName" class="uniSelectLabel">PROPERTY NAME</label>
            </div>
            <input
              class="form-control uniInput"
              type="text"
              name="propertyName"
              v-model="property.propertyName"
            />
          </div>
          <div class="col-md-6">
            <div v-if="!property.propertyRef">
              <label for="propertyName" class="uniSelectLabel">PROPERTY REFERENCE</label>
            </div>
            <input
              class="form-control uniInput"
              type="text"
              name="propertyRef"
              v-model="property.propertyRef"
            />
          </div>
        </div>
        <div class="row my-5">
          <div class="col-md-6">
            <select
              class="form-control uniSelect"
              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="propertyType === 'Commercial'" class="col-md-2">
            <div v-if="!property.unit">
              <label for="unit" class="uniSelectLabel">UNIT</label>
            </div>
            <input
              class="form-control uniInput"
              type="text"
              name="unit"
              id="unit"
              v-model="property.unit"
            />
          </div>
        </div>
        <div class="row my-5">
          <div class="col-md-6">
            <mapSection v-on:map-location="updateLocation" />
            <input
              type="checkbox"
              v-model="property.showAddress"
              style="margin-right: 10px; margin-top: 10px;"
            />
            <label>Show address on listing</label>
          </div>
          <div class="col-md-6">
            <div class="row">
              <div class="col-md-6">
                <div v-if="property.price < 1">
                  <label
                    for="price"
                    class="uniSelectLabel"
                    style="text-transform:uppercase; margin-left:17px; background-color:white"
                    >{{ salesType }} Price</label
                  >
                </div>
                <input
                  class="form-control uniInput"
                  type="number"
                  name="price"
                  id="price"
                  v-model="property.price"
                />
              </div>
              <div v-if="salesType === 'Rental'" class="col-md-6">
                <select
                  class="form-control uniSelect"
                  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 class="row my-3">
              <div class="col-md-12">
                <input
                  type="date"
                  class="form-control uniInput"
                  name="date"
                  v-model="property.dateAvailable"
                />
              </div>
            </div>
            <div class="row my-3">
              <br />
            </div>
            <div class="row my-3">
              <div class="col-md-12">
                <div v-if="!property.streetNumber">
                  <label for="streetNumber" class="uniSelectLabel">STREET NUMBER</label>
                </div>
                <input
                  class="form-control uniInput"
                  type="text"
                  name="streetNumber"
                  id="unit"
                  v-model="property.streetNumber"
                  disabled
                />
              </div>
            </div>
            <div class="row my-3">
              <div class="col-md-12">
                <div v-if="!property.streetName">
                  <label for="streetName" class="uniSelectLabel">STREET NAME</label>
                </div>
                <input
                  class="form-control uniInput"
                  type="text"
                  name="streetName"
                  id="unit"
                  v-model="property.streetName"
                  disabled
                />
              </div>
            </div>
            <div class="row my-3">
              <div class="col-md-12">
                <div v-if="!property.suburb">
                  <label for="suburb" class="uniSelectLabel">SUBURB</label>
                </div>
                <input
                  class="form-control uniInput"
                  type="text"
                  name="suburb"
                  id="unit"
                  v-model="property.suburb"
                  disabled
                />
              </div>
            </div>
            <div class="row my-3">
              <div class="col-md-12">
                <div v-if="!property.city">
                  <label for="city" class="uniSelectLabel">CITY</label>
                </div>
                <input
                  class="form-control uniInput"
                  type="text"
                  name="city"
                  id="unit"
                  v-model="property.city"
                  disabled
                />
              </div>
            </div>
            <div class="row my-3">
              <div class="col-md-12">
                <div v-if="!property.province">
                  <label for="province" class="uniSelectLabel">PROVINCE</label>
                </div>
                <input
                  class="form-control uniInput"
                  type="text"
                  name="province"
                  id="unit"
                  v-model="property.province"
                  disabled
                />
              </div>
            </div>
            <div class="row my-3">
              <div class="col-md-12">
                <div v-if="!property.postalCode">
                  <label for="postalCode" class="uniSelectLabel">POSTAL CODE</label>
                </div>
                <input
                  class="form-control uniInput"
                  type="text"
                  name="postalCode"
                  id="unit"
                  v-model="property.postalCode"
                  disabled
                />
              </div>
            </div>
            <div class="row my-3">
              <div class="col-md-12">
                <div v-if="!property.country">
                  <label for="country" class="uniSelectLabel">COUNTRY</label>
                </div>
                <input
                  class="form-control uniInput"
                  type="text"
                  name="country"
                  id="unit"
                  v-model="property.country"
                  disabled
                />
              </div>
            </div>
            <div class="row my-3">
              <div class="col-md-12">
                <button type="button" @click="clearAddress()" class="btn-solid-blue">
                  Clear Address
                </button>
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-md-12">
            <label for="Property Description" style="font-family:'muli'">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="row" />

        <div class="section-header">
          <h2>Extra Information</h2>
        </div>

        <UserField
          v-if="propertyOverviewFields.length > 0"
          :fields="propertyOverviewFields[0].fields"
          @UpdateUserDefinedFields="UpdateUserDefinedFields"
          :id="1"
        ></UserField>
        <div class="row">
          <div class="col-md-12">
            <div v-for="item in propertyFields" :key="item.id">
              <div class="row">
                <div class="col-sm-12">
                  <div class="section-header">
                    <h2>{{ item.name }}</h2>
                  </div>
                </div>
              </div>
              <UserField
                :fields="item.fields"
                :id="item.name"
                @UpdateUserDefinedFields="UpdateUserDefinedFields"
                :fieldValues="item.fields"
              />
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-sm-12">
            <div class="section-header">
              <h2>Media</h2>
            </div>
          </div>
        </div>
        <div class="form-group row">
          <div class="col-md-12">
            <label class="uniSelectLabel">Virtual Tour (URL)</label>
            <div class="input-group-prepend">
              <input
                class="form-control uniInput"
                type="link"
                name="vtlink"
                id="vtlink"
                v-model="property.virtualTour"
              />
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-md-12">
            <label class="uniSelectLabel">Video (URL)</label>
            <div class="input-group-prepend">
              <input
                class="form-control uniInput"
                type="link"
                name="vlink"
                id="vlink"
                v-model="property.video"
              />
            </div>
          </div>
        </div>
        <div class="row mt-3">
          <div class="col-md-6">
            <div class="content-header">
              <h2>Images</h2>
            </div>

            <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-solid-blue">
          Save
        </button>
        <div v-if="showPropertyTypeError">
          <p class="alert myError">
            Missing fields. Please fill in all required fields. Marked with *
          </p>
        </div>
        <div v-if="wait" id="preloader"></div>
      </div>
    </main>
  </div>
</template>

<script>
/* eslint-disable */
import { mapState, mapActions } from "vuex";
import { VueEditor } from "vue2-editor";
import UserField from "../../propertyUserField.vue";
import ImageLoad from "../../propertyImage.vue";
import Log from "../../../../assets/Log";
import carouselSection from "./carouselSection";
import mapSection from "../../mapSection";

export default {
  name: "PropertyCreate",
  components: {
    UserField,
    ImageLoad,
    VueEditor,
    carouselSection,
    mapSection
  },
  data() {
    return {
      propertyType: "Residential",
      salesType: "Rental",
      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: "",
      addressSet: false,
      showPropertyTypeError: false,
      showDateError: false,
      user: Log.getUser(),
      mayEdit: Log.isLoggedIn()
    };
  },
  methods: {
    ...mapActions("property", [
      "getPropertyTypes",
      "getPropertyOverviewFields",
      "getPropertyFields",
      "saveProperty",
      "getProperty",
      "getPropertyImages",
      "clearPropertyImages",
      "getPropertyEditDisplay",
      "getPropertySavedOverviewFields",
      "getPropertySavedFields",
      "getSavedPropertyData"
    ]),
    updateLocation(place) {
      this.addressSet = true;
      this.property.streetNumber = place.streetNumber;
      this.property.streetName = place.streetName;
      this.property.suburb = place.suburb;
      this.property.city = place.city;
      this.property.province = place.province;
      this.property.country = place.country;
      this.property.postalCode = place.postalCode;
      this.property.addressUrl = place.url;
      this.property.propertCoords = place.coords;
    },
    TypeChanged() {
      this.property.propertyUsageType = this.propertyType;
    },
    SubmitData() {
      if (this.property.propertyTypeId === 0) {
        this.showPropertyTypeError = true;
      }

      if (this.salesType === "Rental" && this.property.dateAvailable === "undef") {
        this.showDateError = true;
      }

      if (this.showPropertyTypeError || this.showDateError) {
        return;
      }

      this.wait = true;
      if (this.salesType === "Sale") {
        this.property.isSale = true;
        this.property.dateAvailable = new Date();
      }
      if (this.images.length > 0) {
        this.property.propertyImages = [];
      }
      // 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;
      }
      console.log(this.propertyFieldValues);
      console.log("It was here");
      this.saveProperty(this.property)
        .then(fulfilled => {
          this.$router.push(`/property/residential/property/${fulfilled.data.id}`);
        })
        .catch(error => {
          console.log(error.message);
        });
    },
    Close() {
      this.$router.push("/property/admin/list/my");
    },
    Login() {
      this.$router.push("/user/login");
    },
    PropertyTypeSelected(item) {
      if (item.target.options.selectedIndex > 0) {
        this.showPropertyTypeError = false;
      } else {
        this.showPropertyTypeError = 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;
    },
    clearAddress() {
      this.addressSet = false;
      this.property.streetNumber = undefined;
      this.property.streetName = undefined;
      this.property.suburb = undefined;
      this.property.city = undefined;
      this.property.province = undefined;
      this.property.country = undefined;
      this.property.postalCode = undefined;
      this.property.addressUrl = undefined;
      this.property.propertCoords = undefined;
    }
  },
  mounted() {
    this.wait = false;
    this.getProperty(0);
    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.getPropertyOverviewFields();
    this.getPropertyFields(this.propertyType);
  },
  computed: {
    ...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>

<style lang="scss" scoped></style>
