<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">
                <label>Usage Type</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.propertyUsageType"
                    disabled
                  />
                </div>
              </div>
            </div>
            <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>
            </div>
            <div class="form-group row">
              <div class="col-md-4">
                <label>Property Type</label>
                <propField
                  :display="property.propertyType ? property.propertyType.description : ''"
                  :editType="'selector'"
                  :arrayObject="propertyTypes"
                  :propertyName="'propertyType'"
                  :mayEdit="mayEdit"
                  @UpdateValue="UpdateValue"
                />
              </div>
              <div v-if="propertyType === 'Commercial'" class="col-md-4">
                <label>Property Name</label>
                <propField
                  :display="property.propertyName"
                  :editType="'text'"
                  :propertyName="'propertyName'"
                  :mayEdit="mayEdit"
                  @UpdateValue="UpdateValue"
                />
              </div>
              <div v-if="propertyType === 'Commercial'" class="col-md-4">
                <label>Unit</label>
                <propField
                  :label="'Property Type'"
                  :display="property.unit"
                  :editType="'text'"
                  :propertyName="'unit'"
                  :mayEdit="mayEdit"
                  @UpdateValue="UpdateValue"
                />
              </div>
            </div>
            <div class="form-group row">
              <div class="col-md-6" style="margin-bottom: 1em">
                <label>Street Number</label>
                <propField
                  :display="property.addressLine1"
                  :editType="'text'"
                  :propertyName="'addressLine1'"
                  :mayEdit="mayEdit"
                  @UpdateValue="UpdateValue"
                />
              </div>
              <div class="col-md-6" style="margin-bottom: 1em">
                <label>Street Name</label>
                <propField
                  :display="property.addressLine2"
                  :editType="'text'"
                  :propertyName="'addressLine2'"
                  :mayEdit="mayEdit"
                  @UpdateValue="UpdateValue"
                />
              </div>
              <div class="col-md-6" style="margin-bottom: 1em">
                <label>Province</label>
                <propField
                  :display="property.province ? property.province.description : ''"
                  :editType="'selector'"
                  :arrayObject="provinces"
                  :propertyName="'province'"
                  :mayEdit="mayEdit"
                  @UpdateValue="UpdateValue"
                />
              </div>

              <div class="col-md-6" style="margin-bottom: 1em">
                <label>City</label>
                <propField
                  :display="property.city ? property.city.description : ''"
                  :editType="'selector'"
                  :arrayObject="cities"
                  :propertyName="'city'"
                  :mayEdit="mayEdit"
                  @UpdateValue="UpdateValue"
                />
              </div>
              <div class="col-md-6" style="margin-bottom: 1em">
                <label>Suburb</label>
                <propField
                  :display="property.suburb ? property.suburb.description : ''"
                  :editType="'selector'"
                  :arrayObject="suburbs"
                  :propertyName="'suburb'"
                  :mayEdit="mayEdit"
                  @UpdateValue="UpdateValue"
                />
              </div>
              <div class="col-md-6" style="margin-bottom: 1em">
                <label>Postal Code</label>
                <propField
                  :display="property.addressLine3"
                  :editType="'text'"
                  :propertyName="'addressLine3'"
                  :mayEdit="mayEdit"
                  @UpdateValue="UpdateValue"
                />
              </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>
                <propField
                  :display="String(property.price)"
                  :editType="'number'"
                  :propertyName="'price'"
                  :mayEdit="mayEdit"
                  @UpdateValue="UpdateValue"
                />
              </div>
              <div class="col-md-6" v-if="salesType === 'Rental'">
                <label>Per</label>
                <propField
                  :display="property.pricePer"
                  :editType="'selector'"
                  :propertyName="'pricePer'"
                  :arrayObject="pricePerArr"
                  :mayEdit="mayEdit"
                  @UpdateValue="UpdateValue"
                />
              </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>
            </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>
                <propField
                  :display="property.virtualTour"
                  :editType="'text'"
                  :propertyName="'virtualTour'"
                  :mayEdit="mayEdit"
                  @UpdateValue="UpdateValue"
                />
              </div>
            </div>
            <div class="form-group row">
              <div class="col-md-12">
                <label>Video (URL)</label>
                <propField
                  :display="property.video"
                  :editType="'text'"
                  :propertyName="'video'"
                  :mayEdit="mayEdit"
                  @UpdateValue="UpdateValue"
                />
              </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"
                  align="center"
                  @click="DeleteImage(img)"
                >
                  <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;"
            >Close</button>
            <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 { setTimeout } from 'timers';
import ImageLoad from './propertyImage.vue';
import propField from './propertyFieldEditor.vue';

export default {
  name: 'PropertyEdit',
  components: {
    ImageLoad,
    VueEditor,
    propField,
  },
  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: [
        { id: 'Month', description: 'Month' },
        { id: 'Day', description: 'Day' },
      ],
    };
  },
  methods: {
    ...mapActions('searchTab', [
      'getProvince',
      'getCities',
      'getSuburbs',
      'getListsForPropertyEdit',
    ]),
    ...mapActions('property', ['getPropertyTypes']),
    ...mapActions('propertyEdit', [
      'getSavedPropertyData',
      'updateProperty',
      'mayEditProperty',
    ]),
    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;
          }
          if (item.fieldName === 'propertyType') {
            this.property.propertyType = this.propertyTypes.find(
              pt => pt.description === item.value,
            );
            this.property.propertyTypeId = this.property.propertyType.id;
          }
          if (item.fieldName === 'propertyName') {
            this.property.propertyName = item.value;
          }
          if (item.fieldName === 'unit') {
            this.property.unit = item.value;
          }
          if (item.fieldName === 'addressLine1') {
            this.property.addressLine1 = item.value;
          }
          if (item.fieldName === 'addressLine2') {
            this.property.addressLine2 = item.value;
          }
          if (item.fieldName === 'addressLine3') {
            this.property.addressLine3 = item.value;
          }
          if (item.fieldName === 'province') {
            if (item.value !== '') {
              this.property.province = this.provinces.find(
                p => p.description === item.value,
              );
              this.property.provinceId = this.property.province.id;
              this.getCities(Object.assign({}, { province: item.value }));
              this.property.city = null;
              this.property.suburb = null;
              this.property.addressLine3 = '';
            } else {
              this.property.province = null;
              this.property.city = null;
              this.property.suburb = null;
              this.property.addressLine3 = '';
              this.cities = [];
              this.suburbs = [];
            }
          }
          if (item.fieldName === 'city') {
            if (item.value !== '') {
              const newCity = this.cities.find(
                p => p.description === item.value,
              );
              this.property.city = newCity;
              this.property.cityId = newCity.id;
              this.getSuburbs(
                Object.assign(
                  {},
                  {
                    province: this.property.province.description,
                    city: item.value,
                  },
                ),
              );
              this.property.suburb = null;
              this.property.addressLine3 = '';
            } else {
              this.property.city = null;
              this.property.suburb = null;
              this.property.addressLine3 = '';
              this.suburbs = [];
            }
          }
          if (item.fieldName === 'suburb') {
            if (item.value !== '') {
              const newSuburb = this.suburbs.find(
                p => p.description === item.value,
              );
              this.property.suburb = newSuburb;
              this.property.suburbId = newSuburb.id;
              this.property.addressLine3 = this.property.suburb.postalCode;
            } else {
              this.property.suburb = null;
              this.property.addressLine3 = '';
            }
          }
          if (item.fieldName === 'price') {
            this.property.price = item.value;
          }
          if (item.fieldName === 'pricePer') {
            this.property.pricePer = item.value;
          }
          if (item.fieldName === 'virtualTour') {
            this.property.virtualTour = item.value;
          }
          if (item.fieldName === 'video') {
            this.property.video = item.value;
          }
        }
      }
    },
    TypeChanged() {
      this.propertyType = this.property.propertyUsageType;
    },
    SubmitData() {
      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,
      });

      // console.log(JSON.stringify(this.newPropertyImages));

      // Need to change to promis.
      setTimeout(
        () => this.$router.push({
            path: '/property/admin/list/my',
          }),
        5000,
      );
    },
    Close() {
      this.$router.push('/property/admin/list/my');
    },
    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('searchTab', ['provinces', 'cities', 'suburbs']),
    ...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>
span {
  cursor: pointer;
}
.opacity {
  opacity: 0.5;
  filter: alpha(opacity=50);
}
</style>
