<template>
  <div v-if="value != null" class="mt-8">
    <v-row dense>
      <v-col cols="12">
        <v-menu offset-y max-width="600px">
          <template v-slot:activator="{ on, attrs }">
            <div class="text-h6">
              <v-icon large :color="hasData ? 'primary' : null" class="mr-2"
                >$ayiTruckMonster</v-icon
              >
              {{ $ay.t("WorkOrderItemTravelList") }}
              <v-btn v-if="!parentDeleted" large icon v-bind="attrs" v-on="on">
                <v-icon small color="primary">$ayiEllipsisV</v-icon>
              </v-btn>
            </div>
          </template>
          <v-list>
            <v-list-item v-if="canAdd" @click="newItem">
              <v-list-item-icon>
                <v-icon>$ayiPlus</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{ $ay.t("New") }}</v-list-item-title>
            </v-list-item>
            <v-list-item v-if="canDelete && isDeleted" @click="unDeleteItem">
              <v-list-item-icon>
                <v-icon>$ayiTrashRestoreAlt</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{ $ay.t("Undelete") }}</v-list-item-title>
            </v-list-item>
            <v-list-item v-if="canDelete && !isDeleted" @click="deleteItem">
              <v-list-item-icon>
                <v-icon>$ayiTrashAlt</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{ $ay.t("SoftDelete") }}</v-list-item-title>
            </v-list-item>
            <v-list-item v-if="canDeleteAll" @click="deleteAllItem">
              <v-list-item-icon>
                <v-icon>$ayiDumpster</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{
                $ay.t("SoftDeleteAll")
              }}</v-list-item-title>
            </v-list-item>
          </v-list>
        </v-menu>
      </v-col>

      <template v-if="hasData">
        <!-- ############################################################### -->
        <v-col cols="12" class="mb-10">
          <v-data-table
            v-model="selectedRow"
            :headers="headerList"
            :items="itemList"
            item-key="index"
            class="elevation-1"
            disable-pagination
            disable-filtering
            disable-sort
            hide-default-footer
            data-cy="travelsTable"
            dense
            :item-class="itemRowClasses"
            :show-select="$vuetify.breakpoint.xs"
            single-select
            @click:row="handleRowClick"
          >
          </v-data-table>
        </v-col>
      </template>
      <template v-if="hasData && hasSelection">
        <div ref="traveltopform"></div>
        <v-btn
          v-if="canDelete && isDeleted"
          large
          color="primary"
          @click="unDeleteItem"
          >{{ $ay.t("Undelete")
          }}<v-icon right large>$ayiTrashRestoreAlt</v-icon></v-btn
        >

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemTravelStartDate')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-date-time-picker
            :ref="
              `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelStartDate`
            "
            v-model="
              value.items[activeWoItemIndex].travels[activeItemIndex]
                .travelStartDate
            "
            :label="$ay.t('WorkOrderItemTravelStartDate')"
            :readonly="formState.readOnly"
            :disabled="isDeleted"
            data-cy="travelStartDate"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelStartDate`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelStartDate`
              )
            "
          ></gz-date-time-picker>
        </v-col>

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemTravelStopDate')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-date-time-picker
            :ref="
              `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelStopDate`
            "
            v-model="
              value.items[activeWoItemIndex].travels[activeItemIndex]
                .travelStopDate
            "
            :label="$ay.t('WorkOrderItemTravelStopDate')"
            :readonly="formState.readOnly"
            :disabled="isDeleted"
            data-cy="travelStopDate"
            :rules="[
              form().datePrecedence(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelStartDate`,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelStopDate`
              )
            ]"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelStopDate`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelStopDate`
              )
            "
          ></gz-date-time-picker>
        </v-col>

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemTravelRateQuantity')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-decimal
            :ref="
              `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelRateQuantity`
            "
            v-model="
              value.items[activeWoItemIndex].travels[activeItemIndex]
                .travelRateQuantity
            "
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemTravelRateQuantity')"
            data-cy="travelTravelRateQuantity"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelRateQuantity`
              )
            "
            :rules="[
              form().decimalValid(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelRateQuantity`
              ),
              form().required(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelRateQuantity`
              )
            ]"
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelRateQuantity`
              )
            "
          ></gz-decimal>
        </v-col>
        <v-col
          v-if="form().showMe(this, 'WorkOrderItemTravelDistance')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-decimal
            :ref="
              `Items[${activeWoItemIndex}].travels[${activeItemIndex}].distance`
            "
            v-model="
              value.items[activeWoItemIndex].travels[activeItemIndex].distance
            "
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemTravelDistance')"
            data-cy="travelTravelRateDistance"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].distance`
              )
            "
            :rules="[
              form().decimalValid(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].distance`
              ),
              form().required(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].distance`
              )
            ]"
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].distance`
              )
            "
          ></gz-decimal>
        </v-col>
        <v-col
          v-if="form().showMe(this, 'WorkOrderItemTravelServiceRateID')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-pick-list
            :ref="
              `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelRateId`
            "
            v-model="
              value.items[activeWoItemIndex].travels[activeItemIndex]
                .travelRateId
            "
            :aya-type="$ay.ayt().TravelRate"
            :variant="'contractid:' + value.contractId"
            :show-edit-icon="!value.userIsRestrictedType"
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemTravelServiceRateID')"
            data-cy="travels.travelRateId"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelRateId`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelRateId`
              )
            "
            @update:name="rateChange"
          ></gz-pick-list>
        </v-col>

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemTravelUserID')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-pick-list
            :ref="
              `Items[${activeWoItemIndex}].travels[${activeItemIndex}].userId`
            "
            v-model="
              value.items[activeWoItemIndex].travels[activeItemIndex].userId
            "
            :aya-type="$ay.ayt().User"
            variant="tech"
            :show-edit-icon="!value.userIsRestrictedType"
            :readonly="
              formState.readOnly || isDeleted || value.userIsRestrictedType
            "
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemTravelUserID')"
            data-cy="travels.userid"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].userId`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].userId`
              )
            "
            @update:name="userChange"
          ></gz-pick-list>
        </v-col>

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemTravelNoChargeQuantity')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-decimal
            :ref="
              `Items[${activeWoItemIndex}].travels[${activeItemIndex}].noChargeQuantity`
            "
            v-model="
              value.items[activeWoItemIndex].travels[activeItemIndex]
                .noChargeQuantity
            "
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemTravelNoChargeQuantity')"
            data-cy="travelNoChargeQuantity"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].noChargeQuantity`
              )
            "
            :rules="[
              form().decimalValid(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].noChargeQuantity`
              ),
              form().required(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].noChargeQuantity`
              )
            ]"
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].noChargeQuantity`
              )
            "
          ></gz-decimal>
        </v-col>

        <v-col
          v-if="
            form().showMe(this, 'WorkOrderItemTravelTaxRateSaleID') &&
              !value.userIsRestrictedType
          "
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-pick-list
            :ref="
              `Items[${activeWoItemIndex}].travels[${activeItemIndex}].taxCodeSaleId`
            "
            v-model="
              value.items[activeWoItemIndex].travels[activeItemIndex]
                .taxCodeSaleId
            "
            :aya-type="$ay.ayt().TaxCode"
            show-edit-icon
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemTravelTaxRateSaleID')"
            data-cy="travelTaxCodeSaleId"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].taxCodeSaleId`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].taxCodeSaleId`
              )
            "
            @update:name="taxCodeChange"
          ></gz-pick-list>
        </v-col>

        <v-col
          v-if="
            form().showMe(this, 'TravelPriceOverride') &&
              !value.userIsRestrictedType
          "
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-currency
            :ref="
              `Items[${activeWoItemIndex}].travels[${activeItemIndex}].priceOverride`
            "
            v-model="
              value.items[activeWoItemIndex].travels[activeItemIndex]
                .priceOverride
            "
            can-clear
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('PriceOverride')"
            data-cy="travelpriceoverride"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].priceOverride`
              )
            "
            :rules="[
              form().decimalValid(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].priceOverride`
              )
            ]"
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].priceOverride`
              )
            "
          ></gz-currency>
        </v-col>

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemTravelDetails')"
          cols="12"
        >
          <v-textarea
            :ref="
              `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelDetails`
            "
            v-model="
              value.items[activeWoItemIndex].travels[activeItemIndex]
                .travelDetails
            "
            dense
            :readonly="formState.readOnly"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemTravelDetails')"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelDetails`
              )
            "
            data-cy="traveltravelDetails"
            auto-grow
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].travels[${activeItemIndex}].travelDetails`
              )
            "
          ></v-textarea>
        </v-col>
      </template>
    </v-row>
  </div>
</template>
<script>
export default {
  props: {
    value: {
      default: null,
      type: Object
    },
    pvm: {
      default: null,
      type: Object
    },
    activeWoItemIndex: {
      default: null,
      type: Number
    },
    gotoIndex: {
      default: null,
      type: Number
    }
  },
  data() {
    return {
      activeItemIndex: null,
      selectedRow: []
    };
  },
  computed: {
    isDeleted: function() {
      if (
        this.value.items[this.activeWoItemIndex].travels[
          this.activeItemIndex
        ] == null
      ) {
        this.setDefaultView();
        return true;
      }
      return (
        this.value.items[this.activeWoItemIndex].travels[this.activeItemIndex]
          .deleted === true
      );
    },
    parentDeleted: function() {
      return this.value.items[this.activeWoItemIndex].deleted === true;
    },

    headerList: function() {
      const headers = [];

      if (this.form().showMe(this, "WorkOrderItemTravelStartDate")) {
        headers.push({
          text: this.$ay.t("WorkOrderItemTravelStartDate"),
          align: "right",
          value: "travelStartDate"
        });
      }

      if (this.form().showMe(this, "WorkOrderItemTravelStopDate")) {
        headers.push({
          text: this.$ay.t("WorkOrderItemTravelStopDate"),
          align: "right",
          value: "travelStopDate"
        });
      }

      if (this.form().showMe(this, "WorkOrderItemTravelRateQuantity")) {
        headers.push({
          text: this.$ay.t("WorkOrderItemTravelRateQuantity"),
          align: "right",
          value: "travelRateQuantity"
        });
      }
      if (this.form().showMe(this, "WorkOrderItemTravelDistance")) {
        headers.push({
          text: this.$ay.t("WorkOrderItemTravelDistance"),
          align: "right",
          value: "distance"
        });
      }

      if (this.form().showMe(this, "WorkOrderItemTravelServiceRateID")) {
        headers.push({
          text: this.$ay.t("WorkOrderItemTravelServiceRateID"),
          align: "left",
          value: "travelRateViz"
        });
      }

      //removed due to taking up a lot of space, maybe in future make this it's own customize option for shops that enter few details
      // if (this.form().showMe(this, "WorkOrderItemTravelDetails")) {
      //   headers.push({
      //     text: this.$ay.t("WorkOrderItemTravelDetails"),
      //     align: "left",
      //     value: "travelDetails"
      //   });
      // }

      if (this.form().showMe(this, "WorkOrderItemTravelUserID")) {
        headers.push({
          text: this.$ay.t("WorkOrderItemTravelUserID"),
          align: "left",
          value: "userViz"
        });
      }

      if (this.form().showMe(this, "WorkOrderItemTravelNoChargeQuantity")) {
        headers.push({
          text: this.$ay.t("WorkOrderItemTravelNoChargeQuantity"),
          align: "right",
          value: "noChargeQuantity"
        });
      }

      if (this.form().showMe(this, "TravelUnitOfMeasureViz")) {
        headers.push({
          text: this.$ay.t("UnitOfMeasure"),
          align: "left",
          value: "unitOfMeasureViz"
        });
      }

      if (
        this.form().showMe(this, "TravelCostViz") &&
        this.value.userCanViewLaborOrTravelRateCosts &&
        !this.value.userIsRestrictedType
      ) {
        headers.push({
          text: this.$ay.t("Cost"),
          align: "right",
          value: "costViz"
        });
      }

      if (
        this.form().showMe(this, "TravelListPriceViz") &&
        !this.value.userIsRestrictedType
      ) {
        headers.push({
          text: this.$ay.t("ListPrice"),
          align: "right",
          value: "listPriceViz"
        });
      }

      if (
        this.form().showMe(this, "TravelPriceOverride") &&
        !this.value.userIsRestrictedType
      ) {
        headers.push({
          text: this.$ay.t("PriceOverride"),
          align: "right",
          value: "priceOverride"
        });
      }

      if (
        this.form().showMe(this, "TravelPriceViz") &&
        !this.value.userIsRestrictedType
      ) {
        headers.push({
          text: this.$ay.t("Price"),
          align: "right",
          value: "priceViz"
        });
      }

      if (
        this.form().showMe(this, "WorkOrderItemTravelTaxRateSaleID") &&
        !this.value.userIsRestrictedType
      ) {
        headers.push({
          text: this.$ay.t("Tax"),
          align: "left",
          value: "taxCodeViz"
        });
      }

      if (
        this.form().showMe(this, "TravelNetViz") &&
        !this.value.userIsRestrictedType
      ) {
        headers.push({
          text: this.$ay.t("NetPrice"),
          align: "right",
          value: "netViz"
        });
      }

      if (
        this.form().showMe(this, "TravelTaxAViz") &&
        !this.value.userIsRestrictedType
      ) {
        headers.push({
          text: this.$ay.t("TaxAAmt"),
          align: "right",
          value: "taxAViz"
        });
      }

      if (
        this.form().showMe(this, "TravelTaxBViz") &&
        !this.value.userIsRestrictedType
      ) {
        headers.push({
          text: this.$ay.t("TaxBAmt"),
          align: "right",
          value: "taxBViz"
        });
      }

      if (
        this.form().showMe(this, "TravelLineTotalViz") &&
        !this.value.userIsRestrictedType
      ) {
        headers.push({
          text: this.$ay.t("LineTotal"),
          align: "right",
          value: "lineTotalViz"
        });
      }
      return headers;
    },
    itemList: function() {
      return this.value.items[this.activeWoItemIndex].travels.map((x, i) => {
        return {
          index: i,
          id: x.id,
          travelStartDate: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
            x.travelStartDate,
            this.pvm.timeZoneName,
            this.pvm.languageName,
            this.pvm.hour12
          ),
          travelStopDate: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
            x.travelStopDate,
            this.pvm.timeZoneName,
            this.pvm.languageName,
            this.pvm.hour12
          ),
          travelRateQuantity: window.$gz.locale.decimalLocalized(
            x.travelRateQuantity,
            this.pvm.languageName
          ),
          distance: window.$gz.locale.decimalLocalized(
            x.distance,
            this.pvm.languageName
          ),
          travelRateViz: x.travelRateViz,
          userViz: x.userViz,
          noChargeQuantity: window.$gz.locale.decimalLocalized(
            x.noChargeQuantity,
            this.pvm.languageName
          ),
          unitOfMeasureViz: x.unitOfMeasureViz,
          costViz: window.$gz.locale.currencyLocalized(
            x.costViz,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          listPriceViz: window.$gz.locale.currencyLocalized(
            x.listPriceViz,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          priceViz: window.$gz.locale.currencyLocalized(
            x.priceViz,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          taxCodeViz: x.taxCodeViz,
          priceOverride: window.$gz.locale.currencyLocalized(
            x.priceOverride,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          netViz: window.$gz.locale.currencyLocalized(
            x.netViz,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          taxAViz: window.$gz.locale.currencyLocalized(
            x.taxAViz,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          taxBViz: window.$gz.locale.currencyLocalized(
            x.taxBViz,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          lineTotalViz: window.$gz.locale.currencyLocalized(
            x.lineTotalViz,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          travelDetails: window.$gz.util.truncateString(
            x.travelDetails,
            this.pvm.maxTableNotesLength
          )
        };
      });
    },
    formState: function() {
      return this.pvm.formState;
    },
    formCustomTemplateKey: function() {
      return this.pvm.formCustomTemplateKey;
    },
    hasData: function() {
      return this.value.items[this.activeWoItemIndex].travels.length > 0;
    },
    hasSelection: function() {
      return this.activeItemIndex != null;
    },
    canAdd: function() {
      return this.pvm.rights.change;
    },
    canDelete: function() {
      return this.activeItemIndex != null && this.pvm.rights.change;
    },
    canDeleteAll: function() {
      return this.pvm.rights.change && !this.value.userIsRestrictedType;
    }

    //----
  },
  watch: {
    activeWoItemIndex(val, oldVal) {
      if (val != oldVal) {
        this.setDefaultView();
      }
    },
    gotoIndex(val, oldVal) {
      if (val != oldVal) {
        let gotoIndex = val;
        if (val < 0) {
          //it's a create request
          gotoIndex = this.newItem();
        }
        this.selectedRow = [{ index: gotoIndex }];
        this.activeItemIndex = gotoIndex;
        this.$nextTick(() => {
          const el = this.$refs.traveltopform;
          if (el) {
            el.scrollIntoView({ behavior: "smooth" });
          }
        });
      }
    }
  },
  created() {
    this.setDefaultView();
  },
  methods: {
    userChange(newName) {
      this.value.items[this.activeWoItemIndex].travels[
        this.activeItemIndex
      ].userViz = newName;
    },
    rateChange(newName) {
      this.value.items[this.activeWoItemIndex].travels[
        this.activeItemIndex
      ].travelRateViz = newName;
    },
    taxCodeChange(newName) {
      this.value.items[this.activeWoItemIndex].travels[
        this.activeItemIndex
      ].taxCodeViz = newName;
    },
    newItem() {
      const newIndex = this.value.items[this.activeWoItemIndex].travels.length;

      this.value.items[this.activeWoItemIndex].travels.push({
        id: 0,
        concurrency: 0,
        userId: this.$store.getters.isScheduleableUser
          ? this.$store.state.userId
          : null,
        travelStartDate: null,
        travelStopDate: null,
        travelRateId:
          window.$gz.store.state.globalSettings.defaultTaxRateSaleId,
        travelDetails: null,
        travelRateQuantity: 0,
        noChargeQuantity: 0,
        distance: 0,
        taxCodeSaleId: null,
        price: 0,
        priceOverride: null,
        isDirty: true,
        pmItemId: this.value.items[this.activeWoItemIndex].id,
        uid: Date.now(),
        userViz: this.$store.getters.isScheduleableUser
          ? this.$store.state.userName
          : null,
        travelRateViz: null,
        taxCodeViz: null
      });
      this.$emit("change");
      this.selectedRow = [{ index: newIndex }];
      this.activeItemIndex = newIndex;
      return newIndex; //for create new on goto
    },
    unDeleteItem() {
      this.value.items[this.activeWoItemIndex].travels[
        this.activeItemIndex
      ].deleted = false;
      this.setDefaultView();
    },
    deleteItem() {
      this.value.items[this.activeWoItemIndex].travels[
        this.activeItemIndex
      ].deleted = true;
      this.setDefaultView();
      this.$emit("change");
    },
    deleteAllItem() {
      this.value.items[this.activeWoItemIndex].travels.forEach(
        z => (z.deleted = true)
      );
      this.setDefaultView();
      this.$emit("change");
    },
    setDefaultView: function() {
      //if only one record left then display it otherwise just let the datatable show what the user can click on
      if (this.value.items[this.activeWoItemIndex].travels.length == 1) {
        this.selectedRow = [{ index: 0 }];
        this.activeItemIndex = 0;
      } else {
        this.selectedRow = [];
        this.activeItemIndex = null; //select nothing in essence resetting a child selects and this one too clearing form
      }
    },
    handleRowClick: function(item) {
      this.activeItemIndex = item.index;
      this.selectedRow = [{ index: item.index }];
    },
    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (!this.formState.loading && !this.formState.readonly) {
        //flag this record dirty so it gets picked up by save
        this.value.items[this.activeWoItemIndex].travels[
          this.activeItemIndex
        ].isDirty = true;
        window.$gz.form.fieldValueChanged(this.pvm, ref);
        //------- SPECIAL HANDLING OF CHANGES -----------
        const isNew =
          this.value.items[this.activeWoItemIndex].travels[this.activeItemIndex]
            .id == 0;

        //Auto calculate dates / quantities / global defaults
        const dStart = this.value.items[this.activeWoItemIndex].travels[
          this.activeItemIndex
        ].travelStartDate;
        const dStop = this.value.items[this.activeWoItemIndex].travels[
          this.activeItemIndex
        ].travelStopDate;
        if (ref.includes("travelStartDate") && dStart != null) {
          this.handleStartDateChange(isNew, dStart, dStop);
        }
        if (ref.includes("travelStopDate") && dStop != null) {
          this.handleStopDateChange(isNew, dStart, dStop);
        }
        //------------------------------------------------------
      }
    },
    handleStartDateChange: function(isNew, dStart, dStop) {
      const globalMinutes =
        window.$gz.store.state.globalSettings.workOrderTravelDefaultMinutes;

      if (isNew) {
        if (globalMinutes != 0) {
          dStop = window.$gz.locale.addMinutesToUTC8601String(
            dStart,
            globalMinutes
          );

          //set stop date based on start date and global minutes
          this.value.items[this.activeWoItemIndex].travels[
            this.activeItemIndex
          ].travelStopDate = dStop;
        }
      }
      {
        //Existing record or both dates filled, just update quantity
        if (dStop != null) {
          this.value.items[this.activeWoItemIndex].travels[
            this.activeItemIndex
          ].travelRateQuantity = window.$gz.locale.diffHoursFromUTC8601String(
            dStart,
            dStop
          );
        }
      }
    },
    handleStopDateChange: function(isNew, dStart, dStop) {
      const globalMinutes =
        window.$gz.store.state.globalSettings.workOrderTravelDefaultMinutes;

      if (isNew && dStart == null) {
        if (globalMinutes != 0) {
          dStart = window.$gz.locale.addMinutesToUTC8601String(
            dStop,
            0 - globalMinutes
          );

          //set start date based on stop date and global minutes
          this.value.items[this.activeWoItemIndex].travels[
            this.activeItemIndex
          ].travelStartDate = dStart;
        }
      }
      {
        //Existing record or both dates filled, just update quantity
        if (dStart != null) {
          this.value.items[this.activeWoItemIndex].travels[
            this.activeItemIndex
          ].travelRateQuantity = window.$gz.locale.diffHoursFromUTC8601String(
            dStart,
            dStop
          );
        }
      }
    },
    itemRowClasses: function(item) {
      let ret = "";
      const isDeleted =
        this.value.items[this.activeWoItemIndex].travels[item.index].deleted ===
        true;

      const hasError = this.form().childRowHasError(
        this,
        `Items[${this.activeWoItemIndex}].Travels[${item.index}].`
      );

      if (isDeleted) {
        ret += this.form().tableRowDeletedClass();
      }
      if (hasError) {
        ret += this.form().tableRowErrorClass();
      }
      return ret;
    }
    //---
  }
};
</script>
