<template>
  <div>
    <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" @click="openDialog = true">
          <v-icon>$ayiEdit</v-icon>
        </v-btn>
        <span>{{ displayServiceAddress }}</span>
      </div>
    </template>
    <v-row 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 offset-y v-if="!formState.readOnly">
                  <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 class="text-h6" v-else>
                  {{ $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
                  v-model="value.address"
                  :readonly="formState.readOnly"
                  :label="$ay.t('AddressDeliveryAddress')"
                  ref="address"
                  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
                  v-model="value.city"
                  :readonly="formState.readOnly"
                  :label="$ay.t('AddressCity')"
                  ref="city"
                  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
                  v-model="value.region"
                  :readonly="formState.readOnly"
                  :label="$ay.t('AddressStateProv')"
                  ref="region"
                  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
                  v-model="value.country"
                  :readonly="formState.readOnly"
                  :label="$ay.t('AddressCountry')"
                  ref="country"
                  data-cy="country"
                  :error-messages="form().serverErrors(this, 'country')"
                  @input="fieldValueChanged('country')"
                ></v-text-field>
              </v-col>

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

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

              <v-col cols="12">
                <v-menu offset-y v-if="!formState.readOnly">
                  <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 class="text-h6" v-else>
                  {{ $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
                  v-model="value.postAddress"
                  :readonly="formState.readOnly"
                  :label="$ay.t('AddressPostalDeliveryAddress')"
                  ref="postAddress"
                  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
                  v-model="value.postCity"
                  :readonly="formState.readOnly"
                  :label="$ay.t('AddressPostalCity')"
                  ref="postCity"
                  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
                  v-model="value.postRegion"
                  :readonly="formState.readOnly"
                  :label="$ay.t('AddressPostalStateProv')"
                  ref="postRegion"
                  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
                  v-model="value.postCountry"
                  :readonly="formState.readOnly"
                  :label="$ay.t('AddressPostalCountry')"
                  ref="postCountry"
                  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
                  v-model="value.postCode"
                  :readonly="formState.readOnly"
                  :label="$ay.t('AddressPostalPostal')"
                  ref="postCode"
                  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 @click="close()">{{
              $ay.t("OK")
            }}</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
    <v-dialog max-width="600px" v-model="openSelectDialog">
      <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>
                  <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>
</template>
<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  XXXeslint-disable    */
////////////////////////////////////////////////////////////////////////////////////////////////////////////

export default {
  data() {
    return {
      openDialog: false,
      openSelectDialog: false,
      selectType: 1, //1==service / physical, 2==billing / postal
      alternateAddresses: [] //{objectName:"NAME-Type",addressViz:"summary",addressFields:{address:aaa,city:aaa,region:aaa,country:ccc, code:ccc, lat:lll, long:lll}}
    };
  },

  props: {
    value: {
      default: null,
      type: Object
    },
    pvm: {
      default: null,
      type: Object
    },

    formKey: { type: String, default: "" }, //used to grab template from store
    readonly: Boolean,
    disabled: Boolean
  },

  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) {
        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.pvm.formState.dirty = 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;
        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;
      }
    },
    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.pvm.formState.dirty = 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.pvm.formState.dirty = 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";
      }
      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 {
        //window.$gz.form.deleteAllErrorBoxErrors(vm);
        let loc = await window.$gz.util.getGeoLocation();
        this.value.latitude = loc.latitude;
        this.fieldValueChanged("latitude");
        this.value.longitude = loc.longitude;
        this.fieldValueChanged("longitude");
      } catch (ex) {
        //window.$gz.errorHandler.handleFormError(ex, vm);
      }
    }
  },
  computed: {
    formState: function() {
      return this.pvm.formState;
    },
    formCustomTemplateKey: function() {
      return this.pvm.formCustomTemplateKey;
    },
    displayServiceAddress() {
      return formatAddress(this.value).physical;
    }
  }
};

/////////////////////////////////
//
//
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) {
    let 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) {
    let unitIdList = [];
    vm.value.items.forEach(i => {
      i.units.forEach(async u => {
        if (u.id != null && !unitIdList.includes(u.id)) {
          unitIdList.push(u.id);
          //get address
          let res = await window.$gz.api.get(`unit/address/${u.id}`);
          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
  let 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.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>
