<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">Edit Property: {{ property.shortDescription }}</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">
                <field :type="'datetime'" :mayEdit="true" />
              </div>
            </div>-->
            <div class="form-goup row">
              <div class="col-md-4">
                <label>Usage Type</label>
                <div class="input-group-prepend">
                  <input
                    class="form-control"
                    type="text"
                    name="unit"
                    id="unit"
                    v-model="property.propertyUsageType"
                    disabled
                  />
                </div>
              </div>
            </div>
            <br />
            <div class="form-group row">
              <div class="col-md-4">
                <label>Sale Type</label>
                <propField
                  :display="property.isSale ? 'Sale' : 'Rental'"
                  :editType="'selector'"
                  :arrayObject="salesTypeArr"
                  :propertyName="'isSale'"
                  :mayEdit="mayEdit"
                  @UpdateValue="UpdateValue"
                />
                <div v-if="showPropertyTypeError">
                  <p class="alert myError">Please select a Sales Type</p>
                </div>
              </div>
            </div>
            <div class="form-group row">
              <div class="col-md-4">
                <label>Property Type *</label>
                <field
                  :type="'select'"
                  :selectOptions="propertyTypes"
                  :selectValue="'id'"
                  :selectText="'description'"
                  v-model="property.propertyType"
                  :mayEdit="mayEdit"
                />
              </div>
              <div v-if="propertyType === 'Commercial'" class="col-md-4">
                <label>Property Name</label>
                <field :type="'text'" v-model="property.propertyName" :mayEdit="mayEdit" />
              </div>
              <div v-if="propertyType === 'Commercial'" class="col-md-4">
                <label>Unit</label>
                <field :type="'text'" v-model="property.unit" :mayEdit="mayEdit" />
              </div>
            </div>
            <div class="form-group row">
              <div class="col-md-6" style="margin-bottom: 1em">
                <label>Street Number</label>
                <field :type="'text'" v-model="property.addressLine1" :mayEdit="mayEdit" />
              </div>
              <div class="col-md-6" style="margin-bottom: 1em">
                <label>Street Name</label>
                <field :type="'text'" v-model="property.addressLine2" :mayEdit="mayEdit" />
              </div>
              <div class="col-md-6" style="margin-bottom: 1em">
                <label>Province *</label>
                <field
                  :type="'select'"
                  :selectOptions="provinces"
                  :selectValue="'id'"
                  :selectText="'description'"
                  v-model="property.province"
                  :mayEdit="mayEdit"
                  @change="provChanged"
                />
                <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>
                <field
                  :type="'select'"
                  :selectOptions="cities"
                  :selectValue="'id'"
                  :selectText="'description'"
                  v-model="property.city"
                  :mayEdit="mayEdit"
                  @change="cityChanged"
                />
                <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>
                <field
                  :type="'select'"
                  :selectOptions="suburbs"
                  :selectValue="'id'"
                  :selectText="'description'"
                  v-model="property.suburb"
                  :mayEdit="mayEdit"
                  @change="suburbChanged"
                />
                <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>
                <field :type="'text'" v-model="property.addressLine3" :mayEdit="mayEdit" />
              </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>
                <field :type="'number'" v-model="property.price" :mayEdit="mayEdit" />
              </div>
              <div class="col-md-6" v-if="salesType === 'Rental'">
                <label>Per</label>
                <field
                  :type="'selectlist'"
                  :selectOptions="pricePerArr"
                  v-model="property.pricePer"
                  :mayEdit="mayEdit"
                />
              </div>
            </div>
            <div class="form-group row" v-if="salesType === 'Rental'">
              <div class="col-md-6">
                <label>Available From</label>
                <field :type="'date'" :mayEdit="mayEdit" v-model="property.dateAvailable" />
              </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" />
            <div
              class="col-md-6"
              v-if="(propertyType === 'Residential') & (propertyOverviewFields.length > 0)"
            >
              <div v-for="(item, i) in propertyOverviewFields[0].fields" :key="item.id">
                <label>{{ item.name }}</label>
                <propField
                  :display="item.value"
                  :editType="item.type"
                  :propertyId="item.itemID"
                  :userDefinedId="item.id"
                  :isUDF="Boolean('true')"
                  :isPropOverview="Boolean('true')"
                  :mayEdit="mayEdit"
                  :arrayIndex="i"
                  @UpdateValue="UpdateValue"
                />
              </div>
            </div>

            <div class="form-group row" />
            <div v-for="(group, i) in propertyFields" :key="group.id">
              <div class="row">
                <div class="col-sm-12">
                  <div class="title-box-d">
                    <h5 class="title-d">{{ group.name }}</h5>
                  </div>
                </div>
              </div>
              <div v-for="(field, ii) in group.fields" :key="field.id">
                <label>{{ field.name }}</label>
                <propField
                  :display="field.value"
                  :editType="field.type"
                  :propertyId="field.itemID"
                  :userDefinedId="field.id"
                  :isUDF="Boolean('true')"
                  :arrayIndex="i"
                  :arrayItemIndex="ii"
                  :mayEdit="mayEdit"
                  @UpdateValue="UpdateValue"
                />
              </div>
              <br />
            </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>
                <field :type="'text'" v-model="property.virtualTour" :mayEdit="mayEdit" />
              </div>
            </div>
            <div class="form-group row">
              <div class="col-md-12">
                <label>Video (URL)</label>
                <field :type="'text'" v-model="property.video" :mayEdit="mayEdit" />
              </div>
            </div>
            <div class="form-group row">
              <div class="col-md-6">
                <label>Images</label>
                <div class="input-group-prepend"></div>
              </div>
            </div>
            <div class="form-group row">
              <div class="col-md-2" v-for="(img, i) in propertyImages" :key="i">
                <input
                  v-if="mayEdit"
                  type="checkbox"
                  id="checkbox"
                  v-model="img.isDefault"
                  :disabled="img.isDeleted"
                />
                <label v-if="mayEdit" for="checkbox" style="margin: 10px;">Main Image</label>
                <br />
                <img
                  :src="img.image"
                  style="height:200px; width:150px; object-fit: cover;"
                  :class="[img.isDeleted ? 'opacity' : '']"
                />
                <span
                  v-if="!img.isDeleted && mayEdit"
                  class="input-group-text spanCursor"
                  align="center"
                  @click="DeleteImage(img)"
                  style="width:150px"
                >
                  <eva-icon name="trash-2-outline" fill="#60CBEB"></eva-icon>Delete
                </span>
              </div>
            </div>

            <ImageLoad
              :loadedImages="loadedImages"
              @DefaultImage="UpdateDefaultImage"
              :mayEdit="mayEdit"
            />
            <button
              v-if="!wait"
              type="button"
              @click="SubmitData()"
              class="btn btn-b-n"
              style="width: 85px; height:40px;"
              :disabled="!mayEdit"
            >
              Save
            </button>
            <button
              type="button"
              @click="Close()"
              class="btn btn-b-n"
              style="width: 85px; height:40px;"
              :disabled="
                showPropertyTypeError || showProvinceError || showCityError || showSuburbError
              "
            >
              Close
            </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 ImageLoad from "./propertyImage.vue";
import propField from "./propertyFieldEditor.vue";
import field from "../shared/fieldEditor.vue";

export default {
  name: "PropertyEdit",
  components: {
    ImageLoad,
    VueEditor,
    propField,
    field
  },
  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" }]
      ],
      salesTypeArr: [
        { id: 1, description: "Sale" },
        { id: 2, description: "Rental" }
      ],
      pricePerArr: ["Month", "Day"],
      yesno: ["Yes", "No"],
      showPropertyTypeError: false,
      showProvinceError: false,
      showCityError: false,
      showSuburbError: false
    };
  },
  methods: {
    ...mapActions("property", ["getPropertyTypes"]),
    ...mapActions("propertyEdit", ["getSavedPropertyData", "updateProperty", "mayEditProperty"]),
    salesTypeChanged(item) {
      console.log(item);
    },
    UpdateValue(item) {
      if (item.isUDF) {
        if (item.isPropOverview) {
          this.propertyOverviewFields[0].fields[item.arrayIndex].value = item.value;
        } else if (item.isPropOverview === false) {
          this.propertyFields[item.arrayIndex].fields[item.arrayItemIndex].value = item.value;
        }
      } else if (!item.isUDF) {
        if (item.fieldName) {
          if (item.fieldName === "isSale") {
            let isSaleValue = false;
            if (item.value === "Sale") {
              isSaleValue = true;
            } else isSaleValue = false;
            this.property.isSale = isSaleValue;
          }
        }
      }
    },
    TypeChanged() {
      this.propertyType = this.property.propertyUsageType;
    },
    SubmitData() {
      if (this.property.propertyTypeId === 0) {
        this.showPropertyTypeError = true;
      }
      if (this.property.province === null) {
        this.showProvinceError = true;
      }
      if (this.property.city === null) {
        this.showCityError = true;
      }
      if (this.property.suburb === null) {
        this.showSuburbError = true;
      }

      if (
        this.showPropertyTypeError ||
        this.showProvinceError ||
        this.showCityError ||
        this.showSuburbError
      ) {
        return;
      }
      this.wait = true;
      this.newPropertyImages.propertyId = this.property.id;
      this.newPropertyImages.Images = [];
      // 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.newPropertyImages.images.push({
          image: this.images[i],
          isDefault: setAsDefault
        });
      }
      this.property.propertyImages = this.propertyImages;
      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < this.property.propertyImages.length; i++) {
        this.property.propertyImages[i].image = "";
      }
      this.property.propertyOverviewFields = this.propertyOverviewFields;
      this.property.propertyFields = this.propertyFields;
      this.updateProperty({
        property: this.property,
        images: this.newPropertyImages
      }).then(() => {
        this.$router.push("/properties");
      });
    },
    Close() {
      this.$router.push("/properties");
    },
    loadedImages(values) {
      this.images = values;
    },
    UpdateDefaultImage(item) {
      this.defaultImage = item;
    },
    DeleteImage(image) {
      this.propertyImages.find(item => item.id === image.id).isDeleted = true;
    }
  },
  mounted() {
    // Need to check this can remove unused code
    this.wait = false;
    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.getListsForPropertyEdit(this.$route.query.id);

    this.getSavedPropertyData(
      Object.assign({}, { id: this.$route.query.id, type: this.propertyType })
    );

    this.mayEditProperty(this.$route.query.id);
  },
  computed: {
    ...mapState("property", ["propertyTypes"]),
    ...mapState("propertyEdit", [
      "propertyOverviewFields",
      "propertyFields",
      "property",
      "propertyImages",
      "mayEdit",
      "newPropertyImages"
    ]),
    ...mapState("authentication", ["user"]),
    SalesTypeChanged() {
      if (this.property && this.property.propertyUsageType) {
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        this.propertyType = this.property.propertyUsageType;
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        this.salesType = this.property.isSale ? "Sale" : "Rental";
      }

      this.getPropertyTypes(this.propertyType);

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

<style>
.spanCursor {
  cursor: pointer;
}
.opacity {
  opacity: 0.5;
  filter: alpha(opacity=50);
}
</style>
