<template>
  <div>
    <main id="main" style="margin-top: -20px">
      <div class="container pb-5">
        <div class="row">
          <div class="col">
            <label v-if="!resSalesType" class="uniSelectLabel" for="resSaleType">Sale Type</label>
            <float-label label="Sale Type">
              <select class="form-control uniSelect mb-3" name="resSaleType" v-model="resSalesType">
                <option value="Sale">To Sell</option>
                <option value="Rental">To Rent</option>
              </select>
            </float-label>
          </div>
        </div>
        <div class="row mt-2">
          <div class="col-md-6">
            <div v-if="!property.propertyName">
              <label for="propertyName" class="uniSelectLabel">PROPERTY NAME</label>
            </div>
            <float-label label="PROPERTY NAME">
              <input
                class="form-control uniInput"
                type="text"
                name="resPropertyName"
                v-model="property.propertyName"
              />
            </float-label>
          </div>
          <div class="col-md-6">
            <div v-if="!property.propertyRef">
              <label for="propertyName" class="uniSelectLabel">PROPERTY REFERENCE</label>
            </div>
            <float-label label="PROPERTY REFERENCE">
              <input
                class="form-control uniInput"
                type="text"
                name="resPropertyRef"
                v-model="property.propertyRef"
              />
            </float-label>
          </div>
        </div>
        <div class="row my-5">
          <div class="col-md-6">
            <select
              class="form-control uniSelect"
              name="resPropertyType"
              id="resPropertyType"
              v-model="property.propertyTypeId"
              @change="PropertyTypeSelected"
            >
              <option value="0">Please select type *</option>
              <option v-for="item in propertyTypesRes" :value="item.id" :key="item.id">
                {{ item.description }}
              </option>
            </select>
          </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="resPrice"
                    class="uniSelectLabel"
                    style="
                      text-transform: uppercase;
                      margin-left: 17px;
                      background-color: white;
                    "
                    >{{ resSalesType }} Price</label
                  >
                </div>
                <float-label label="Price">
                  <currency-input
                    name="resPrice"
                    :value="property.price"
                    @input="property.price = $event"
                    v-model="property.price"
                    id="resPrice"
                    class="form-control uniInput"
                  />
                </float-label>
              </div>
              <div v-if="resSalesType === 'Rental'" class="col-md-6">
                <select
                  class="form-control uniSelect"
                  name="resPropertyType"
                  id="resPropertyType"
                  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="resDate"
                  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="resStreetNumber" class="uniSelectLabel">STREET NUMBER</label>
                </div>
                <input
                  class="form-control uniInput"
                  type="text"
                  name="resStreetNumber"
                  id="resStreetNumber"
                  v-model="property.streetNumber"
                />
              </div>
            </div>
            <div class="row my-3">
              <div class="col-md-12">
                <div v-if="!property.streetName">
                  <label for="resStreetName" class="uniSelectLabel">STREET NAME</label>
                </div>
                <input
                  class="form-control uniInput"
                  type="text"
                  name="resStreetName"
                  id="resStreetName"
                  v-model="property.streetName"
                />
              </div>
            </div>
            <div class="row my-3">
              <div class="col-md-12">
                <div v-if="!property.suburb">
                  <label for="resSuburb" class="uniSelectLabel">SUBURB</label>
                </div>
                <input
                  class="form-control uniInput"
                  type="text"
                  name="resSuburb"
                  id="resSuburb"
                  v-model="property.suburb"
                />
              </div>
            </div>
            <div class="row my-3">
              <div class="col-md-12">
                <div v-if="!property.city">
                  <label for="resCity" class="uniSelectLabel">CITY</label>
                </div>
                <input
                  class="form-control uniInput"
                  type="text"
                  name="resCity"
                  id="resCity"
                  v-model="property.city"
                />
              </div>
            </div>
            <div class="row my-3">
              <div class="col-md-12">
                <div v-if="!property.province">
                  <label for="resProvince" class="uniSelectLabel">PROVINCE</label>
                </div>
                <input
                  class="form-control uniInput"
                  type="text"
                  name="resProvince"
                  id="resProvince"
                  v-model="property.province"
                />
              </div>
            </div>
            <div class="row my-3">
              <div class="col-md-12">
                <div v-if="!property.postalCode">
                  <label for="resPostalCode" class="uniSelectLabel">POSTAL CODE</label>
                </div>
                <input
                  class="form-control uniInput"
                  type="text"
                  name="resPostalCode"
                  id="resPostalCode"
                  v-model="property.postalCode"
                />
              </div>
            </div>
            <div class="row my-3">
              <div class="col-md-12">
                <div v-if="!property.country">
                  <label for="resCountry" class="uniSelectLabel">COUNTRY</label>
                </div>
                <input
                  class="form-control uniInput"
                  type="text"
                  name="resCountry"
                  id="resCountry"
                  v-model="property.country"
                />
              </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="resCustomToolbar" />
            <br />
            <p>
              * A listing fee of R{{ getListingFee.amount }} including VAT is payable to list your
              Property on the Uni-Vate website
            </p>
          </div>
        </div>

        <div class="section-header">
          <h2>Property Information</h2>
        </div>
        <UserField
          :fields="propFields"
          @UpdateUserDefinedFields="UpdateUserResidentialFields"
        ></UserField>
        <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 mt-2">
            <label v-if="!property.virtualTour" class="uniSelectLabel">Virtual Tour (URL)</label>
            <div class="input-group-prepend">
              <float-label label="Virtual Tour (URL)" style="width: 100%">
                <input
                  class="form-control uniInput"
                  type="link"
                  name="resVtlink"
                  id="resVtlink"
                  v-model="property.virtualTour"
                />
              </float-label>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-md-12 mt-2">
            <label v-if="!property.video" class="uniSelectLabel">Video (URL)</label>
            <div class="input-group-prepend">
              <float-label label="Video (URL)" style="width: 100%">
                <input
                  class="form-control uniInput"
                  type="link"
                  name="resVlink"
                  id="resVlink"
                  v-model="property.video"
                />
              </float-label>
            </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="!resWait" type="button" @click="SubmitData()" class="btn-solid-blue">
          Save
        </button>
        <div v-if="resShowPropertyTypeError">
          <p class="alert myError">
            Missing fields. Please fill in all required fields. Marked with *
          </p>
        </div>
        <div v-if="resWait" id="preloader"></div>
      </div>
    </main>
  </div>
</template>

<script>
/* eslint-disable */
import { mapState, mapActions, mapGetters } 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
  },
  props: {
    propFields: {}
  },
  data() {
    return {
      resPropertyType: "Residential",
      resSalesType: "Rental",
      resImages: [],
      resPropertyFieldValues: [],
      resDefaultImage: 0,
      resWait: false,
      resCustomToolbar: [
        [{ 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" }]
      ],
      resAddressSet: false,
      resShowPropertyTypeError: false,
      resShowDateError: false,
      resUser: Log.getUser()
    };
  },
  methods: {
    ...mapActions("property", [
      "getPropertyTypesRes",
      "getPropertyOverviewFields",
      "getPropertyFields",
      "saveProperty",
      "getProperty",
      "getPropertyImages",
      "clearPropertyImages",
      "getPropertyEditDisplay",
      "getPropertySavedOverviewFields",
      "getPropertySavedFields",
      "getSavedPropertyData"
    ]),
    ...mapActions("register", ["getAgentById"]),
    updateLocation(place) {
      this.resAddressSet = 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.resPropertyType;
    },
    SubmitData() {
      if (this.property.propertyTypeId === 0) {
        this.resShowPropertyTypeError = true;
      }

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

      if (this.resShowPropertyTypeError || this.resShowDateError) {
        return;
      }

      this.resWait = true;
      if (this.resSalesType === "Sale") {
        this.property.isSale = true;
        this.property.dateAvailable = new Date();
      }
      if (this.resImages.length > 0) {
        this.property.propertyImages = [];
      }
      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < this.resImages.length; i++) {
        let setAsDefault = false;
        if (i === this.resDefaultImage) {
          setAsDefault = true;
        }
        this.property.propertyImages.push({
          image: this.resImages[i],
          isDefault: setAsDefault
        });
      }
      this.property.propertyUserFields = this.resPropertyFieldValues;
      this.property.propertyUserFields.forEach(field => {
        if (field.type === "yesno") {
          if (field.value) {
            field.value = "true";
          }
        }
      });
      if (this.resUser) {
        this.property.userId = this.resUser.id;
      }

      if (Log.getUser().role === "Agency" || Log.getUser().role === "Agent") {
        this.retrieveAgency().then(() => {
          this.property.agentId = this.agent[0].id;
          this.property.agencyId = this.agent[0].agencyId;
        });
      }
      //console.log(this.property);
      //console.log(JSON.stringify(this.property));
      this.saveProperty(this.property)
        .then(fulfilled => {
          this.$router.push(`/property/residential/property/${fulfilled.data.id}`);
        })
        .catch(error => {
          console.log(error);
        });
    },
    async retrieveAgency() {
      await this.getAgentById(Log.getUser().id);
    },
    Close() {
      this.$router.push("/property/admin/list/my");
    },
    Login() {
      this.$router.push("/user/login");
    },
    PropertyTypeSelected(item) {
      if (item.target.options.selectedIndex > 0) {
        this.resShowPropertyTypeError = false;
      } else {
        this.resShowPropertyTypeError = true;
      }
    },
    loadedImages(values) {
      this.resImages = values;
    },
    UpdateUserResidentialFields(item) {
      let update = false;

      this.resPropertyFieldValues.forEach(element => {
        if (element.userDefinedFieldId === item.userDefinedFieldId) {
          if (item.type !== "yesno") {
            element.value = item.value;
            update = true;
          } else {
            if (item.value) {
              element.value = "true";
            } else {
              element.value = "false";
            }
          }
        }
      });
      if (!update) {
        this.resPropertyFieldValues.push(item);
      }
    },
    UpdateDefaultImage(item) {
      this.resDefaultImage = item;
    },
    clearAddress() {
      this.resAddressSet = 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;
    },
    userFieldsArrFunc(arr, len) {
      const fields = [];
      const i = 0;
      const n = arr.length;

      while (i < n) {
        fields.push(arr.slice(i, (i += len)));
      }
      return fields;
    }
  },
  mounted() {
    this.resWait = false;
    this.getProperty(0);
    this.clearPropertyImages();
    this.resImages = [];
    this.resDefaultImage = 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.resPropertyType = this.$route.params.propertyUsageType;
    }
    this.resSalesType = this.$route.params.saleType;

    this.getPropertyTypesRes();

    this.getPropertyOverviewFields();
    //this.getPropertyFields(this.propertyType);
  },
  computed: {
    ...mapState("property", [
      "propertyTypesRes",
      "propertyOverviewFields",
      "propertyFields",
      "property",
      "propertyImages"
    ]),
    ...mapState("authentication", ["user"]),
    ...mapGetters("fees", ["getListingFee"]),
    ...mapState("register", ["agent"]),
    SalesTypeChanged() {
      this.resSalesType = this.$route.params.saleType;
      if (this.property && this.property.propertyUsageType) {
        this.resPropertyType = this.property.propertyUsageType;
      }
      if (!this.$route.query.id) {
        this.getPropertyFields(this.resPropertyType);
      }
      return this.resPropertyType;
    }
  },
  watch: {
    SalesTypeChanged() {
      return null;
    }
  }
};
</script>

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