<template>
  <div class="mb-8">
    <div class="mb-n2 ml-10">
      <span class="text-caption">{{ $ay.t("Address") }}</span>
    </div>
    <template>
      <div class="mb-6 mb-sm-0">
        <v-btn
          icon
          class="ml-n1 mr-2"
          :data-cy="`${dataCy}:open`"
          @click="openDialog = true"
        >
          <v-icon>$ayiEdit</v-icon>
        </v-btn>
        <span @click="openDialog = true">{{ displayServiceAddress }}</span>
      </div>
    </template>
    <v-row dense justify="center">
      <v-dialog v-model="openDialog">
        <v-card>
          <v-card-title>
            <span class="text-h5">{{ $ay.t("Address") }}</span>
          </v-card-title>
          <v-card-text>
            <v-row>
              <v-col cols="12">
                <v-menu v-if="!readonly" offset-y>
                  <template v-slot:activator="{ on, attrs }">
                    <span class="text-h6">
                      {{ $ay.t("AddressTypePhysical") }}</span
                    ><v-btn icon v-bind="attrs" v-on="on">
                      <v-icon small>$ayiEllipsisV</v-icon>
                    </v-btn>
                  </template>
                  <v-list>
                    <v-list-item @click="AddressSelectAlternatePhysical()">
                      <v-list-item-icon> </v-list-item-icon>
                      <v-list-item-title>{{
                        $ay.t("SelectAlternateAddress")
                      }}</v-list-item-title>
                    </v-list-item>
                    <v-list-item @click="AddressCopyPhysicalToClipBoard()">
                      <v-list-item-icon>
                        <v-icon>$ayiCopy</v-icon>
                      </v-list-item-icon>
                      <v-list-item-title>{{
                        $ay.t("CopyToClipboard")
                      }}</v-list-item-title>
                    </v-list-item>
                    <v-list-item @click="AddressCopyToPostal">
                      <v-list-item-icon>
                        <v-icon>$ayiClone</v-icon>
                      </v-list-item-icon>
                      <v-list-item-title>{{
                        $ay.t("AddressCopyToPostal")
                      }}</v-list-item-title>
                    </v-list-item>
                    <v-list-item @click="GeoCapture">
                      <v-list-item-icon>
                        <v-icon>$ayiMapMarker</v-icon>
                      </v-list-item-icon>
                      <v-list-item-title>{{
                        $ay.t("GeoCapture")
                      }}</v-list-item-title>
                    </v-list-item>
                  </v-list>
                </v-menu>
                <span v-else class="text-h6">
                  {{ $ay.t("AddressTypePhysical") }}</span
                >
              </v-col>
              <v-col
                v-if="form().showMe(this, 'Address')"
                cols="12"
                sm="6"
                lg="4"
                xl="3"
              >
                <v-text-field
                  ref="address"
                  v-model="value.address"
                  dense
                  :readonly="readonly"
                  :label="$ay.t('AddressDeliveryAddress')"
                  data-cy="address"
                  :error-messages="form().serverErrors(this, 'address')"
                  @input="fieldValueChanged('address')"
                ></v-text-field>
              </v-col>

              <v-col
                v-if="form().showMe(this, 'City')"
                cols="12"
                sm="6"
                lg="4"
                xl="3"
              >
                <v-text-field
                  ref="city"
                  v-model="value.city"
                  dense
                  :readonly="readonly"
                  :label="$ay.t('AddressCity')"
                  data-cy="city"
                  :error-messages="form().serverErrors(this, 'city')"
                  @input="fieldValueChanged('city')"
                ></v-text-field>
              </v-col>

              <v-col
                v-if="form().showMe(this, 'Region')"
                cols="12"
                sm="6"
                lg="4"
                xl="3"
              >
                <v-text-field
                  ref="region"
                  v-model="value.region"
                  dense
                  :readonly="readonly"
                  :label="$ay.t('AddressStateProv')"
                  data-cy="region"
                  :error-messages="form().serverErrors(this, 'region')"
                  @input="fieldValueChanged('region')"
                ></v-text-field>
              </v-col>

              <v-col
                v-if="form().showMe(this, 'Country')"
                cols="12"
                sm="6"
                lg="4"
                xl="3"
              >
                <v-text-field
                  ref="country"
                  v-model="value.country"
                  dense
                  :readonly="readonly"
                  :label="$ay.t('AddressCountry')"
                  data-cy="country"
                  :error-messages="form().serverErrors(this, 'country')"
                  @input="fieldValueChanged('country')"
                ></v-text-field>
              </v-col>

              <v-col
                v-if="form().showMe(this, 'AddressPostal')"
                cols="12"
                sm="6"
                lg="4"
                xl="3"
              >
                <v-text-field
                  ref="addressPostal"
                  v-model="value.addressPostal"
                  dense
                  :readonly="readonly"
                  :label="$ay.t('AddressPostal')"
                  data-cy="addressPostal"
                  :error-messages="form().serverErrors(this, 'addressPostal')"
                  @input="fieldValueChanged('addressPostal')"
                ></v-text-field>
              </v-col>

              <v-col
                v-if="form().showMe(this, 'Latitude')"
                cols="12"
                sm="6"
                lg="4"
                xl="3"
              >
                <gz-decimal
                  ref="latitude"
                  v-model="value.latitude"
                  :readonly="readonly"
                  :label="$ay.t('AddressLatitude')"
                  data-cy="latitude"
                  :rules="[form().decimalValid(this, 'latitude')]"
                  :error-messages="form().serverErrors(this, 'latitude')"
                  :precision="6"
                  @input="fieldValueChanged('latitude')"
                ></gz-decimal>
              </v-col>

              <v-col
                v-if="form().showMe(this, 'Longitude')"
                cols="12"
                sm="6"
                lg="4"
                xl="3"
              >
                <gz-decimal
                  ref="longitude"
                  v-model="value.longitude"
                  :readonly="readonly"
                  :label="$ay.t('AddressLongitude')"
                  data-cy="longitude"
                  :rules="[form().decimalValid(this, 'longitude')]"
                  :error-messages="form().serverErrors(this, 'longitude')"
                  :precision="6"
                  @input="fieldValueChanged('longitude')"
                ></gz-decimal>
              </v-col>

              <v-col cols="12">
                <v-menu v-if="!readonly" offset-y>
                  <template v-slot:activator="{ on, attrs }">
                    <span class="text-h6">
                      {{ $ay.t("AddressTypePostal") }}</span
                    ><v-btn icon v-bind="attrs" v-on="on">
                      <v-icon small>$ayiEllipsisV</v-icon>
                    </v-btn>
                  </template>
                  <v-list>
                    <v-list-item @click="AddressSelectAlternatePostal()">
                      <v-list-item-icon> </v-list-item-icon>
                      <v-list-item-title>{{
                        $ay.t("SelectAlternateAddress")
                      }}</v-list-item-title>
                    </v-list-item>
                    <v-list-item @click="AddressCopyPostalToClipBoard()">
                      <v-list-item-icon>
                        <v-icon>$ayiCopy</v-icon>
                      </v-list-item-icon>
                      <v-list-item-title>{{
                        $ay.t("CopyToClipboard")
                      }}</v-list-item-title>
                    </v-list-item>
                    <v-list-item @click="AddressCopyToPhysical">
                      <v-list-item-icon>
                        <v-icon>$ayiClone</v-icon>
                      </v-list-item-icon>
                      <v-list-item-title>{{
                        $ay.t("AddressCopyToPhysical")
                      }}</v-list-item-title>
                    </v-list-item>
                  </v-list>
                </v-menu>
                <span v-else class="text-h6">
                  {{ $ay.t("AddressTypePostal") }}</span
                >
              </v-col>

              <v-col
                v-if="form().showMe(this, 'PostAddress')"
                cols="12"
                sm="6"
                lg="4"
                xl="3"
              >
                <v-text-field
                  ref="postAddress"
                  v-model="value.postAddress"
                  dense
                  :readonly="readonly"
                  :label="$ay.t('AddressPostalDeliveryAddress')"
                  data-cy="postAddress"
                  :error-messages="form().serverErrors(this, 'postAddress')"
                  @input="fieldValueChanged('postAddress')"
                ></v-text-field>
              </v-col>

              <v-col
                v-if="form().showMe(this, 'PostCity')"
                cols="12"
                sm="6"
                lg="4"
                xl="3"
              >
                <v-text-field
                  ref="postCity"
                  v-model="value.postCity"
                  dense
                  :readonly="readonly"
                  :label="$ay.t('AddressPostalCity')"
                  data-cy="postCity"
                  :error-messages="form().serverErrors(this, 'postCity')"
                  @input="fieldValueChanged('postCity')"
                ></v-text-field>
              </v-col>

              <v-col
                v-if="form().showMe(this, 'PostRegion')"
                cols="12"
                sm="6"
                lg="4"
                xl="3"
              >
                <v-text-field
                  ref="postRegion"
                  v-model="value.postRegion"
                  dense
                  :readonly="readonly"
                  :label="$ay.t('AddressPostalStateProv')"
                  data-cy="postRegion"
                  :error-messages="form().serverErrors(this, 'postRegion')"
                  @input="fieldValueChanged('postRegion')"
                ></v-text-field>
              </v-col>

              <v-col
                v-if="form().showMe(this, 'PostCountry')"
                cols="12"
                sm="6"
                lg="4"
                xl="3"
              >
                <v-text-field
                  ref="postCountry"
                  v-model="value.postCountry"
                  dense
                  :readonly="readonly"
                  :label="$ay.t('AddressPostalCountry')"
                  data-cy="postCountry"
                  :error-messages="form().serverErrors(this, 'postCountry')"
                  @input="fieldValueChanged('postCountry')"
                ></v-text-field>
              </v-col>

              <v-col
                v-if="form().showMe(this, 'PostCode')"
                cols="12"
                sm="6"
                lg="4"
                xl="3"
              >
                <v-text-field
                  ref="postCode"
                  v-model="value.postCode"
                  dense
                  :readonly="readonly"
                  :label="$ay.t('AddressPostalPostal')"
                  data-cy="postCode"
                  :error-messages="form().serverErrors(this, 'postCode')"
                  @input="fieldValueChanged('postCode')"
                ></v-text-field>
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>

            <v-btn
              color="blue darken-1"
              text
              :data-cy="`${dataCy}:btnok`"
              @click="close()"
              >{{ $ay.t("OK") }}</v-btn
            >
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
    <v-dialog v-model="openSelectDialog" max-width="600px">
      <v-card>
        <v-card-title>
          <span class="text-h5">{{ $ay.t("SelectAlternateAddress") }}</span>
        </v-card-title>
        <v-card-text>
          <v-list>
            <template v-for="(item, index) in alternateAddresses">
              <v-list-item :key="index" @click="selectAlternate(item)">
                <v-list-item-avatar>
                  <v-icon v-text="item.icon"> </v-icon>
                </v-list-item-avatar>
                <v-list-item-content>
                  <v-list-item-title>{{ item.name }}</v-list-item-title>
                  <!-- eslint-disable vue/no-v-html -->
                  <v-list-item-subtitle
                    v-html="item.viz"
                  ></v-list-item-subtitle>
                </v-list-item-content>
              </v-list-item>
            </template>
          </v-list>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>

          <v-btn color="blue darken-1" text @click="closeSelect()">{{
            $ay.t("OK")
          }}</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <div class="v-messages theme--light error--text mt-6" role="alert">
      <div class="v-messages__wrapper">
        <div class="v-messages__message">{{ allErrors }}</div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    value: {
      default: null,
      type: Object
    },
    pvm: {
      default: null,
      type: Object
    },
    dataCy: { type: String, default: null },
    formKey: { type: String, default: "" }, //used to grab template from store
    readonly: Boolean,
    disabled: Boolean,
    errorMessages: { type: Array, default: null }
  },
  data() {
    return {
      openDialog: false,
      openSelectDialog: false,
      selectType: 1,
      alternateAddresses: []
    };
  },
  computed: {
    formState: function() {
      return this.pvm.formState;
    },
    formCustomTemplateKey: function() {
      return this.pvm.formCustomTemplateKey;
    },
    displayServiceAddress() {
      return formatAddress(this.value).physical;
    },
    allErrors: function() {
      let ret = "";

      if (this.errorMessages != null && this.errorMessages.length > 0) {
        ret += this.errorMessages.toString();
      }
      return ret;
    }
  },

  methods: {
    close() {
      this.openDialog = false;
    },
    closeSelect() {
      this.openSelectDialog = false;
    },
    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (!this.pvm.formState.loading && !this.pvm.formState.readonly) {
        this.value.isDirty = true;
        window.$gz.form.fieldValueChanged(this.pvm, ref);
      }
    },
    selectAlternate(item) {
      if (this.selectType == 2) {
        //postal
        this.value.postAddress = item.src.postAddress;
        this.value.postCity = item.src.postCity;
        this.value.postRegion = item.src.postRegion;
        this.value.postCountry = item.src.postCountry;
        this.value.postCode = item.src.postCode;

        this.pvm.formState.dirty = true;
        this.value.isDirty = true;
      } else {
        //physical
        this.value.address = item.src.address;
        this.value.city = item.src.city;
        this.value.region = item.src.region;
        this.value.country = item.src.country;
        this.value.addressPostal = item.src.addressPostal;
        if (item.src.latitude) {
          this.value.latitude = item.src.latitude;
        }
        if (item.src.longitude) {
          this.value.longitude = item.src.longitude;
        }
        this.pvm.formState.dirty = true;
        this.value.isDirty = true;
      }
    },
    async AddressSelectAlternatePostal() {
      this.selectType = 2;
      await populateAlternateAddresses(this);
      this.openSelectDialog = true;
    },
    async AddressSelectAlternatePhysical() {
      this.selectType = 1;
      await populateAlternateAddresses(this);
      this.openSelectDialog = true;
    },
    AddressCopyToPostal() {
      this.value.postAddress = this.value.address;
      this.value.postCity = this.value.city;
      this.value.postRegion = this.value.region;
      this.value.postCountry = this.value.country;
      this.value.postCode = this.value.addressPostal;
      this.pvm.formState.dirty = true;
      this.value.isDirty = true;
    },
    AddressCopyToPhysical() {
      this.value.address = this.value.postAddress;
      this.value.city = this.value.postCity;
      this.value.region = this.value.postRegion;
      this.value.country = this.value.postCountry;
      this.value.addressPostal = this.value.postCode;
      this.pvm.formState.dirty = true;
      this.value.isDirty = true;
    },
    AddressCopyPhysicalToClipBoard() {
      let ret = "";
      if (this.value.name) {
        ret += this.value.name + "\n";
      }
      if (this.value.address) {
        ret += this.value.address + "\n";
      }

      if (this.value.city) {
        ret += this.value.city + " ";
      }

      if (this.value.region) {
        ret += this.value.region + " ";
      }

      if (this.value.country) {
        ret += this.value.country + "\n";
      }

      if (this.value.addressPostal) {
        //Postal codes should have two spaces before them according to regs.
        ret += "  " + this.value.addressPostal + "\n";
      }

      window.$gz.util.copyToClipboard(ret);
      /* todo maybe down the road if asked for?

    if(mAddressType==AddressTypes.Physical)
    {
     if(mLatitude!=0 || mLongitude!=0)
     {
      sb.Append(" \r\n");
      sb.Append(LongitudeToString(mLongitude));
      sb.Append("   ");
      sb.Append(LatitudeToString(mLatitude));
      sb.Append(" \r\n");
     }
    } */
    },
    AddressCopyPostalToClipBoard() {
      let ret = "";
      if (this.value.name) {
        ret += this.value.name + "\n";
      }
      if (this.value.postAddress) {
        ret += this.value.postAddress + "\n";
      }

      if (this.value.postCity) {
        ret += this.value.postCity + " ";
      }

      if (this.value.postRegion) {
        ret += this.value.postRegion + " ";
      }

      if (this.value.postCode) {
        //Postal codes should have two spaces before them according to regs.
        ret += "  " + this.value.postCode + "\n";
      }

      if (this.value.postCountry) {
        ret += this.value.postCountry + "\n";
      }
      window.$gz.util.copyToClipboard(ret);
    },
    async GeoCapture() {
      try {
        const loc = await window.$gz.util.getGeoLocation();
        this.value.latitude = loc.latitude;
        this.fieldValueChanged("latitude");
        this.value.longitude = loc.longitude;
        this.fieldValueChanged("longitude");
      } catch (ex) {
        //could fail on some platforms
      }
    }
  }
};

/////////////////////////////////
//
//
async function populateAlternateAddresses(vm) {
  //walk through workorder
  //find all the addressible objects, get their addresses and push into list
  //at top should be customer, headoffice, then units
  vm.alternateAddresses = [];
  const ispostal = vm.selectType == 2;
  const wo = vm.value;
  if (wo.customerId != null) {
    const res = await window.$gz.api.get(`customer/address/${wo.customerId}`);
    if (res.data) {
      //customer first
      if (ispostal) {
        vm.alternateAddresses.push({
          name: res.data.customerpost.name,
          viz: formatAddress(res.data.customerpost).postal,
          icon: window.$gz.util.iconForType(window.$gz.type.Customer),
          src: res.data.customerpost
        });
        //headoffice if present
        if (res.data.headofficepost) {
          vm.alternateAddresses.push({
            name: res.data.headofficepost.name,
            viz: formatAddress(res.data.headofficepost).postal,
            icon: window.$gz.util.iconForType(window.$gz.type.HeadOffice),
            src: res.data.headofficepost
          });
        }
      } else {
        vm.alternateAddresses.push({
          name: res.data.customerphys.name,
          viz: formatAddress(res.data.customerphys).physical,
          icon: window.$gz.util.iconForType(window.$gz.type.Customer),
          src: res.data.customerphys
        });
      }
    }
  }
  //Unit addresses
  //Units only have physical addresses
  if (!ispostal) {
    const unitIdList = [];
    vm.value.items.forEach(i => {
      i.units.forEach(async u => {
        if (u.unitId != null && !unitIdList.includes(u.unitId)) {
          unitIdList.push(u.unitId);
          //get address
          const res = await window.$gz.api.get(`unit/address/${u.unitId}`);
          if (res.data) {
            vm.alternateAddresses.push({
              name: res.data.unit.name,
              viz: formatAddress(res.data.unit).physical,
              icon: window.$gz.util.iconForType(window.$gz.type.Unit),
              src: res.data.unit
            });
          }
        }
      });
    });
  }
}

////////////////////////////////
//
//
function formatAddress(o) {
  //Format address(es) as compact as possible
  const ret = { physical: "", postal: "" };

  //Physical
  if (!window.$gz.util.stringIsNullOrEmpty(o.address)) {
    ret.physical += o.address + " ";
  }
  if (!window.$gz.util.stringIsNullOrEmpty(o.city)) {
    ret.physical += o.city + " ";
  }
  if (!window.$gz.util.stringIsNullOrEmpty(o.region)) {
    ret.physical += o.region + " ";
  }
  if (!window.$gz.util.stringIsNullOrEmpty(o.country)) {
    ret.physical += o.country + " ";
  }
  if (!window.$gz.util.stringIsNullOrEmpty(o.addressPostal)) {
    ret.postal += o.addressPostal;
  }
  if (!window.$gz.util.stringIsNullOrEmpty(o.latitude)) {
    ret.physical += ", lat " + o.latitude;
  }
  if (!window.$gz.util.stringIsNullOrEmpty(o.longitude)) {
    ret.physical += ", long " + o.longitude;
  }

  //Postal
  if (!window.$gz.util.stringIsNullOrEmpty(o.postAddress)) {
    ret.postal += o.postAddress + " ";
  }
  if (!window.$gz.util.stringIsNullOrEmpty(o.postCity)) {
    ret.postal += o.postCity + " ";
  }
  if (!window.$gz.util.stringIsNullOrEmpty(o.postRegion)) {
    ret.postal += o.postRegion + " ";
  }
  if (!window.$gz.util.stringIsNullOrEmpty(o.postCountry)) {
    ret.postal += o.postCountry;
  }
  if (!window.$gz.util.stringIsNullOrEmpty(o.postCode)) {
    ret.postal += o.postCode;
  }

  return ret;
}
</script>
