<template>
  <div v-if="value != null" class="mt-8">
    <v-row>
      <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"
                >$ayiHammer</v-icon
              >
              {{ $ay.t("WorkOrderItemLaborList") }}
              <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="hasSelection && !formState.readOnly"
              @click="appendTasks"
            >
              <v-list-item-icon>
                <v-icon>$ayiTasks</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{ $ay.t("AppendTasks") }}</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="laborsTable"
            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="labortopform"></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, 'WorkOrderItemLaborServiceStartDate')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-date-time-picker
            :ref="
              `Items[${activeWoItemIndex}].labors[${activeItemIndex}].serviceStartDate`
            "
            v-model="
              value.items[activeWoItemIndex].labors[activeItemIndex]
                .serviceStartDate
            "
            :label="$ay.t('WorkOrderItemLaborServiceStartDate')"
            :readonly="formState.readOnly"
            :disabled="isDeleted"
            data-cy="serviceStartDate"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].labors[${activeItemIndex}].serviceStartDate`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].labors[${activeItemIndex}].serviceStartDate`
              )
            "
          ></gz-date-time-picker>
        </v-col>

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

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

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

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemLaborUserID')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-pick-list
            :ref="
              `Items[${activeWoItemIndex}].labors[${activeItemIndex}].userId`
            "
            v-model="
              value.items[activeWoItemIndex].labors[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('WorkOrderItemLaborUserID')"
            data-cy="labors.userid"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].labors[${activeItemIndex}].laboruserId`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].labors[${activeItemIndex}].userId`
              )
            "
            @update:name="userChange"
          ></gz-pick-list>
        </v-col>

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

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

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

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemLaborServiceDetails')"
          cols="12"
        >
          <v-textarea
            :ref="
              `Items[${activeWoItemIndex}].labors[${activeItemIndex}].serviceDetails`
            "
            v-model="
              value.items[activeWoItemIndex].labors[activeItemIndex]
                .serviceDetails
            "
            :readonly="formState.readOnly"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemLaborServiceDetails')"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].labors[${activeItemIndex}].serviceDetails`
              )
            "
            data-cy="laborserviceDetails"
            auto-grow
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].labors[${activeItemIndex}].serviceDetails`
              )
            "
          ></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].labors[this.activeItemIndex] ==
        null
      ) {
        this.setDefaultView();
        return true;
      }
      return (
        this.value.items[this.activeWoItemIndex].labors[this.activeItemIndex]
          .deleted === true
      );
    },
    parentDeleted: function() {
      return this.value.items[this.activeWoItemIndex].deleted === true;
    },

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      if (
        this.form().showMe(this, "LaborLineTotalViz") &&
        !this.value.userIsRestrictedType
      ) {
        headers.push({
          text: this.$ay.t("LineTotal"),
          align: "right",
          value: "lineTotalViz"
        });
      }
      return headers;
    },
    itemList: function() {
      return this.value.items[this.activeWoItemIndex].labors.map((x, i) => {
        return {
          index: i,
          id: x.id,
          serviceStartDate: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
            x.serviceStartDate,
            this.pvm.timeZoneName,
            this.pvm.languageName,
            this.pvm.hour12
          ),
          serviceStopDate: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
            x.serviceStopDate,
            this.pvm.timeZoneName,
            this.pvm.languageName,
            this.pvm.hour12
          ),

          serviceRateQuantity: window.$gz.locale.decimalLocalized(
            x.serviceRateQuantity,
            this.pvm.languageName
          ),
          serviceRateViz: x.serviceRateViz,
          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
          ),
          serviceDetails: window.$gz.util.truncateString(
            x.serviceDetails,
            this.pvm.maxTableNotesLength
          )
        };
      });
    },
    formState: function() {
      return this.pvm.formState;
    },
    formCustomTemplateKey: function() {
      return this.pvm.formCustomTemplateKey;
    },
    hasData: function() {
      return this.value.items[this.activeWoItemIndex].labors.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.labortopform;
          if (el) {
            el.scrollIntoView({ behavior: "smooth" });
          }
        });
      }
    }
  },
  created() {
    this.setDefaultView();
  },
  methods: {
    appendTasks() {
      const tasks = this.value.items[this.activeWoItemIndex].tasks;
      if (tasks.length == 0) {
        return;
      }
      const l = this.value.items[this.activeWoItemIndex].labors[
        this.activeItemIndex
      ];
      let at = "";
      tasks.forEach(z => {
        at += `${z.task} - ${z.statusViz}\n`;
      });
      l.serviceDetails += `\n${at}`;
    },
    userChange(newName) {
      this.value.items[this.activeWoItemIndex].labors[
        this.activeItemIndex
      ].userViz = newName;
    },
    rateChange(newName) {
      this.value.items[this.activeWoItemIndex].labors[
        this.activeItemIndex
      ].serviceRateViz = newName;
    },
    taxCodeChange(newName) {
      this.value.items[this.activeWoItemIndex].labors[
        this.activeItemIndex
      ].taxCodeViz = newName;
    },
    newItem() {
      const newIndex = this.value.items[this.activeWoItemIndex].labors.length;

      this.value.items[this.activeWoItemIndex].labors.push({
        id: 0,
        concurrency: 0,
        userId: this.$store.getters.isScheduleableUser
          ? this.$store.state.userId
          : null,
        serviceStartDate: null,
        serviceStopDate: null,
        serviceRateId: null,
        serviceDetails: null,
        serviceRateQuantity: 0,
        noChargeQuantity: 0,
        taxCodeSaleId:
          window.$gz.store.state.globalSettings.defaultTaxRateSaleId,
        price: 0,
        priceOverride: null,
        isDirty: true,
        workOrderItemId: this.value.items[this.activeWoItemIndex].id,
        uid: Date.now(),
        userViz: this.$store.getters.isScheduleableUser
          ? this.$store.state.userName
          : null,
        serviceRateViz: 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].labors[
        this.activeItemIndex
      ].deleted = false;
      this.setDefaultView();
    },
    deleteItem() {
      this.value.items[this.activeWoItemIndex].labors[
        this.activeItemIndex
      ].deleted = true;
      this.setDefaultView();
      this.$emit("change");
    },
    deleteAllItem() {
      this.value.items[this.activeWoItemIndex].labors.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].labors.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].labors[
          this.activeItemIndex
        ].isDirty = true;
        window.$gz.form.fieldValueChanged(this.pvm, ref);
        //------- SPECIAL HANDLING OF CHANGES -----------
        const isNew =
          this.value.items[this.activeWoItemIndex].labors[this.activeItemIndex]
            .id == 0;

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

      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].labors[
            this.activeItemIndex
          ].serviceStopDate = dStop;
        }
      }
      {
        //Existing record or both dates filled, just update quantity
        if (dStop != null) {
          this.value.items[this.activeWoItemIndex].labors[
            this.activeItemIndex
          ].serviceRateQuantity = window.$gz.locale.diffHoursFromUTC8601String(
            dStart,
            dStop
          );
        }
      }
    },
    handleStopDateChange: function(isNew, dStart, dStop) {
      const globalMinutes =
        window.$gz.store.state.globalSettings.workLaborScheduleDefaultMinutes;

      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].labors[
            this.activeItemIndex
          ].serviceStartDate = dStart;
        }
      }
      {
        //Existing record or both dates filled, just update quantity
        if (dStart != null) {
          this.value.items[this.activeWoItemIndex].labors[
            this.activeItemIndex
          ].serviceRateQuantity = window.$gz.locale.diffHoursFromUTC8601String(
            dStart,
            dStop
          );
        }
      }
    },
    itemRowClasses: function(item) {
      let ret = "";
      const isDeleted =
        this.value.items[this.activeWoItemIndex].labors[item.index].deleted ===
        true;

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

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