<template>
  <div>
    <main id="main" style="margin-top:-20px">
      <div class="container pb-5">
        <div class="row">
          <div class="col">
            <label v-if="!salesType" class="uniSelectLabel" for="saleType">Sale Type</label>
            <select class="form-control uniSelect mb-5" name="saleType" v-model="salesType">
              <option value="Sale">To Sell</option>
              <option value="Rental">To Rent</option>
            </select>
          </div>
        </div>
        <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">
              <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>
        </div>
        <div class="row" />

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

        <div class="row mb-3" v-for="item in propertyFields" :key="item.id">
          <div class="col-md-6" v-for="field in item.fields" :key="field.id">
            <div v-if="field.type === 'number'">
              {{ field.name }}
              <input type="number" class="form-control uniInput" v-model="field.value" />
            </div>
            <div v-else class="display:none"></div>
            <div v-if="field.type === 'yesno'">
              {{ field.name }}
              <input type="checkbox" v-model="field.value" />
            </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: "Commercial",
      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;
      }

      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;
    }
  },
  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.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>
