<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"
                >$ayiFan</v-icon
              >
              {{ $ay.t("WorkOrderItemUnitList") }}
              <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="canAdd" @click="showBulkUnitsDialog()">
              <v-list-item-icon>
                <v-icon>$ayiFan</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{
                $ay.t("AddMultipleUnits")
              }}</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
            :headers="headerList"
            :items="itemList"
            item-key="index"
            v-model="selectedRow"
            class="elevation-1"
            disable-pagination
            disable-filtering
            disable-sort
            hide-default-footer
            data-cy="unitsTable"
            dense
            :item-class="itemRowClasses"
            @click:row="handleRowClick"
            :show-select="$vuetify.breakpoint.xs"
            single-select
          >
          </v-data-table>
        </v-col>
      </template>
      <template v-if="hasData && hasSelection">
        <div ref="unittopform"></div>
        <v-btn
          v-if="canDelete && isDeleted"
          large
          @click="unDeleteItem"
          color="primary"
          >{{ $ay.t("Undelete")
          }}<v-icon right large>$ayiTrashRestoreAlt</v-icon></v-btn
        >
        <v-col
          v-if="form().showMe(this, 'WorkOrderItemUnit')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-pick-list
            :aya-type="$ay.ayt().Unit"
            :variant="'customerid:' + value.customerId"
            :show-edit-icon="!value.userIsRestrictedType"
            v-model="
              value.items[activeWoItemIndex].units[activeItemIndex].unitId
            "
            :readonly="
              formState.readOnly || isDeleted || value.userIsRestrictedType
            "
            :disabled="isDeleted"
            :label="$ay.t('Unit')"
            :ref="
              `Items[${activeWoItemIndex}].units[${activeItemIndex}].unitId`
            "
            data-cy="units.unitId"
            :rules="[
              form().required(
                this,
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].unitId`
              )
            ]"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].unitId`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].unitId`
              )
            "
            @update:name="unitChange"
          ></gz-pick-list>
        </v-col>

        <v-col
          v-if="
            form().showMe(this, 'UnitWarrantyInfo') &&
              !value.userIsRestrictedType
          "
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <v-card>
            <v-card-title>{{ $ay.t("UnitWarrantyInfo") }}</v-card-title>
            <v-card-text
              v-html="
                value.items[activeWoItemIndex].units[activeItemIndex]
                  .warrantyViz
              "
            >
            </v-card-text>
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn color="primary" text @click="getWarrantyInfo">{{
                $ay.t("Search")
              }}</v-btn>
            </v-card-actions>
          </v-card>
        </v-col>

        <v-col
          v-if="
            form().showMe(this, 'WorkOrderItemUnitNotes') &&
              !value.userIsRestrictedType
          "
          cols="12"
        >
          <v-textarea
            v-model="
              value.items[activeWoItemIndex].units[activeItemIndex].notes
            "
            :readonly="formState.readOnly"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemUnitNotes')"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].notes`
              )
            "
            :ref="`Items[${activeWoItemIndex}].units[${activeItemIndex}].notes`"
            data-cy="unitUnitNotes"
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].notes`
              )
            "
            auto-grow
          ></v-textarea>
        </v-col>

        <v-col
          v-if="
            form().showMe(this, 'WorkOrderItemUnitTags') &&
              !value.userIsRestrictedType
          "
          cols="12"
        >
          <gz-tag-picker
            v-model="value.items[activeWoItemIndex].units[activeItemIndex].tags"
            :readonly="formState.readOnly"
            data-cy="unitTags"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].tags`
              )
            "
            :ref="`Items[${activeWoItemIndex}].units[${activeItemIndex}].tags`"
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].tags`
              )
            "
          ></gz-tag-picker>
        </v-col>

        <v-col v-if="!value.userIsRestrictedType" cols="12">
          <gz-custom-fields
            v-model="
              value.items[activeWoItemIndex].units[activeItemIndex].customFields
            "
            :form-key="formCustomTemplateKey"
            :readonly="formState.readOnly"
            :parent-v-m="this"
            key-start-with="WorkOrderItemUnitCustom"
            :ref="
              `Items[${activeWoItemIndex}].units[${activeItemIndex}].customFields`
            "
            data-cy="unitCustomFields"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].customFields`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].customFields`
              )
            "
          ></gz-custom-fields>
        </v-col>

        <v-col
          v-if="
            form().showMe(this, 'WorkOrderItemUnitWiki') &&
              !value.userIsRestrictedType
          "
          cols="12"
        >
          <gz-wiki
            :aya-type="$ay.ayt().WorkOrderItem"
            :aya-id="value.id"
            :ref="`Items[${activeWoItemIndex}].units[${activeItemIndex}].wiki`"
            v-model="value.items[activeWoItemIndex].units[activeItemIndex].wiki"
            :readonly="formState.readOnly"
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].wiki`
              )
            "
          ></gz-wiki
        ></v-col>

        <v-col
          v-if="
            form().showMe(this, 'WorkOrderItemUnitAttachments') &&
              value.id &&
              !value.userIsRestrictedType
          "
          cols="12"
        >
          <gz-attachments
            :readonly="formState.readOnly"
            :aya-type="$ay.ayt().WorkOrderItemUnit"
            :aya-id="value.items[activeWoItemIndex].units[activeItemIndex].id"
          ></gz-attachments
        ></v-col>
      </template>
    </v-row>
    <!-- ################################################################################-->
    <!-- ##########################  BULK ADD UNITS FORM  ###############################-->
    <!-- ################################################################################-->
    <template>
      <v-row justify="center">
        <v-dialog persistent max-width="600px" v-model="bulkUnitsDialog">
          <v-card>
            <v-card-title>{{ $ay.t("AddMultipleUnits") }}</v-card-title>
            <v-card-text>
              <gz-tag-picker v-model="selectedBulkUnitTags"></gz-tag-picker>
              <gz-pick-list
                :aya-type="$ay.ayt().Customer"
                :show-edit-icon="false"
                v-model="selectedBulkUnitCustomer"
                :label="$ay.t('Customer')"
                :can-clear="true"
              ></gz-pick-list>

              <v-data-table
                dense
                v-model="selectedBulkUnits"
                :headers="bulkUnitTableHeaders"
                :items="availableBulkUnits"
                class="my-10"
                :disable-filtering="true"
                hide-default-footer
                :no-data-text="$ay.t('NoData')"
                show-select
                item-key="unitId"
              >
              </v-data-table>
            </v-card-text>
            <v-card-actions>
              <v-btn text @click="bulkUnitsDialog = false" color="primary">{{
                $ay.t("Cancel")
              }}</v-btn>
              <v-spacer></v-spacer>
              <v-btn
                :disabled="selectedBulkUnitTags.length == 0"
                color="primary"
                text
                @click="bulkUnitsSearch()"
                >{{ $ay.t("Search") }}</v-btn
              >
              <v-btn
                :disabled="selectedBulkUnits.length == 0"
                color="primary"
                text
                @click="addSelectedBulkUnits()"
                >{{ $ay.t("Add") }}</v-btn
              >
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-row>
    </template>
  </div>
</template>
<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  XXXeslint-disable    */
////////////////////////////////////////////////////////////////////////////////////////////////////////////

export default {
  created() {
    this.setDefaultView();
  },
  data() {
    return {
      activeItemIndex: null,
      selectedRow: [],
      bulkUnitsDialog: false,
      selectedBulkUnitCustomer: this.value.customerId,
      availableBulkUnits: [],
      selectedBulkUnits: [],
      selectedBulkUnitTags: [],
      bulkUnitTableHeaders: []
    };
  },
  props: {
    value: {
      default: null,
      type: Object
    },
    pvm: {
      default: null,
      type: Object
    },
    activeWoItemIndex: {
      default: null,
      type: Number
    },
    gotoIndex: {
      default: null,
      type: Number
    },
    addNew: {
      default: null,
      type: Number
    }
  },
  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.unittopform;
          if (el) {
            el.scrollIntoView({ behavior: "smooth" });
          }
        });
      }
    }
  },
  methods: {
    async updateContractIfApplicable() {
      const id = this.value.items[this.activeWoItemIndex].units[
        this.activeItemIndex
      ].unitId;
      if (!id || id == 0) {
        return;
      }
      let res = await window.$gz.api.get(`unit/active-contract/${id}`);
      if (res.error) {
        window.$gz.eventBus.$emit(
          "notify-warning",
          window.$gz.errorHandler.errorToString(res, this)
        );
      } else {
        if (res.data.id == 0) {
          //no contract, just bail
          return;
        }
        //has contract, if it differs from main work order contract then offer to set it
        if (res.data.id == this.value.contractId) {
          //same contract, just bail
          //yes the date could not be different but we're not going to pick that nit, they can just unset and set if it matters
          return;
        }
        //Prompt user to use new contract
        const prompt = this.$ay
          .t("ApplyUnitContract")
          .replace("{0}", res.data.name);

        let dialogResult = await window.$gz.dialog.confirmGenericPreTranslated(
          prompt,
          "question"
        );
        if (dialogResult == false) {
          return;
        } else {
          this.value.contractId = res.data.id;
          this.value.isDirty = true;
          this.pvm.formState.dirty = true;
          this.$emit("change");
        }
      }
    },
    async getWarrantyInfo() {
      this.warrantyInfo = null;

      const id = this.value.items[this.activeWoItemIndex].units[
        this.activeItemIndex
      ].unitId;
      if (!id || id == 0) {
        return;
      }
      let res = await window.$gz.api.get(`unit/service-warranty-info/${id}`);
      if (res.error) {
        window.$gz.eventBus.$emit(
          "notify-warning",
          window.$gz.errorHandler.errorToString(res, this)
        );
      } else {
        /* {
  "recentWorkOrders":[{"serial":10,"id":10,"serviceDate":"2021-01-19T22:00:00Z"},{"serial":8,"id":8,"serviceDate":"2021-04-08T22:00:00Z"},{"serial":7,"id":7,"serviceDate":"2021-04-18T20:00:00Z"}],
  "purchaseDate":"2019-03-12T09:37:52.930923Z",
  "purchasedFromVendor":null,
  "purchaseFromVendorId":null,
  "purchaseReceiptNumber":"139736",
  "lifeTimeWarranty":false,
  "warrantyExpiryDate":"2019-04-12T09:37:52.930923Z",
  "warrantyTerms":"Shipping parts and service"} 
  
  "UnitPurchasedDate": "Purchased Date",
  "UnitPurchaseFromID": "Purchased From",
  "UnitReceipt": "Receipt Number",
  */
        const r = res.data;

        let WarrantyInfo = `${this.$ay.t("Warranty")}: `;
        let WarrantyExpiryInfo = "-";
        if (r.lifeTimeWarranty) {
          WarrantyExpiryInfo = this.$ay.t("UnitModelLifeTimeWarranty");
        } else {
          if (r.warrantyExpiryDate) {
            WarrantyExpiryInfo = `${this.$ay.t(
              "WarrantyExpires"
            )}:  ${window.$gz.locale.utcDateToShortDateAndTimeLocalized(
              r.warrantyExpiryDate,
              this.pvm.timeZoneName,
              this.pvm.languageName,
              this.pvm.hour12
            )}`;
          }
        }
        WarrantyInfo += WarrantyExpiryInfo;

        let PurchasedFrom = "-";
        if (r.purchaseFromVendorId) {
          PurchasedFrom = `<a href="/vendors/${r.purchaseFromVendorId}"> ${r.purchasedFromVendor}</a>`;
        }
        let PurchasedDate = "-";
        if (r.purchaseDate) {
          PurchasedDate = window.$gz.locale.utcDateToShortDateAndTimeLocalized(
            r.purchaseDate,
            this.pvm.timeZoneName,
            this.pvm.languageName,
            this.pvm.hour12
          );
        }
        let PurchaseInfo = `${this.$ay.t(
          "UnitPurchaseFromID"
        )}: ${PurchasedFrom}<br/>${this.$ay.t(
          "UnitPurchasedDate"
        )}: ${PurchasedDate}<br/>${this.$ay.t(
          "UnitReceipt"
        )}: ${r.purchaseReceiptNumber ?? "-"}`;

        let RecentWorkOrderList = "";
        if (r.recentWorkOrders.length > 0) {
          RecentWorkOrderList += "<br/>";
          r.recentWorkOrders.forEach(x => {
            RecentWorkOrderList += `<a href="/svc-workorders/${x.id}"> ${
              x.serial
            }<span class='ml-5'>${window.$gz.locale.utcDateToShortDateAndTimeLocalized(
              x.serviceDate,
              this.pvm.timeZoneName,
              this.pvm.languageName,
              this.pvm.hour12
            )}</span></a><br/>`;
          });
        } else {
          RecentWorkOrderList = "-";
        }

        let RecentWorkOrderInfo = `${this.$ay.t(
          "RecentWorkOrders"
        )}:${RecentWorkOrderList}`;

        let d = `<div>${WarrantyInfo}<br/>${PurchaseInfo}<br/>${RecentWorkOrderInfo}</div>`;

        this.value.items[this.activeWoItemIndex].units[
          this.activeItemIndex
        ].warrantyViz = d;
      }
    },
    showBulkUnitsDialog() {
      if (this.bulkUnitTableHeaders.length == 0) {
        //init bulk table headers
        this.bulkUnitTableHeaders = [
          { text: this.$ay.t("Customer"), value: "customerName" },
          { text: this.$ay.t("Unit"), value: "unitSerial" }
        ];
      }
      this.bulkUnitsDialog = true;
    },
    async bulkUnitsSearch() {
      this.selectedBulkUnits.splice(0);
      this.availableBulkUnits.splice(0);

      let res = await window.$gz.api.post(`unit/bulk-add-selection-list`, {
        tags: this.selectedBulkUnitTags,
        restrictToCustomerId: this.selectedBulkUnitCustomer
      });
      if (res.error) {
        window.$gz.eventBus.$emit(
          "notify-warning",
          window.$gz.errorHandler.errorToString(res, this)
        );
      } else {
        this.availableBulkUnits = res.data;
      }
    },
    addSelectedBulkUnits() {
      if (this.selectedBulkUnits.length > 0) {
        let newIndex = this.value.items[this.activeWoItemIndex].units.length;
        this.selectedBulkUnits.forEach(z => {
          newIndex++;
          this.value.items[this.activeWoItemIndex].units.push({
            id: 0,
            concurrency: 0,
            wiki: null,
            customFields: "{}",
            tags: [],
            notes: null,
            unitId: z.unitId, //zero to break rule on new
            isDirty: true,
            workOrderItemId: this.value.items[this.activeWoItemIndex].id,
            uid: Date.now(),
            unitViz: z.unitSerial,
            warrantyViz: null
          });
        });
        this.$emit("change");
        this.selectedRow = [{ index: newIndex }];
        this.activeItemIndex = newIndex;
      }
      this.bulkUnitsDialog = false;
    },
    async unitChange(newName) {
      this.value.items[this.activeWoItemIndex].units[
        this.activeItemIndex
      ].unitViz = newName;
      this.value.items[this.activeWoItemIndex].units[
        this.activeItemIndex
      ].warrantyViz = null;
      await this.updateContractIfApplicable();
    },
    newItem() {
      let newIndex = this.value.items[this.activeWoItemIndex].units.length;
      // {
      // 	"0": {
      // 		"id": 53,
      // 		"concurrency": 9586762,
      // 		"notes": "Aut modi molestias molestiae ipsa id.",
      // 		"wiki": null,
      // 		"customFields": null,
      // 		"tags": [],
      // 		"unitId": 4,
      // 		"unitViz": "83429560",
      // 		"workOrderItemId": 22
      // 	}
      // }

      this.value.items[this.activeWoItemIndex].units.push({
        id: 0,
        concurrency: 0,
        wiki: null,
        customFields: "{}",
        tags: [],
        notes: null,
        unitId: 0, //zero to break rule on new
        isDirty: true,
        workOrderItemId: this.value.items[this.activeWoItemIndex].id,
        uid: Date.now(),
        unitViz: null,
        warrantyViz: null
      });

      this.$emit("change");
      this.selectedRow = [{ index: newIndex }];
      this.activeItemIndex = newIndex;
      //trigger rule breaking / validation
      this.$nextTick(() => {
        this.value.items[this.activeWoItemIndex].units[
          this.activeItemIndex
        ].unitId = null;
        this.fieldValueChanged(
          `Items[${this.activeWoItemIndex}].units[${this.activeItemIndex}].unitId`
        );
      });

      return newIndex; //for create new on goto
    },
    unDeleteItem() {
      this.value.items[this.activeWoItemIndex].units[
        this.activeItemIndex
      ].deleted = false;
      this.setDefaultView();
    },
    deleteItem() {
      this.value.items[this.activeWoItemIndex].units[
        this.activeItemIndex
      ].deleted = true;
      this.setDefaultView();
      this.$emit("change");
    },
    deleteAllItem() {
      this.value.items[this.activeWoItemIndex].units.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].units.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].units[
          this.activeItemIndex
        ].isDirty = true;
        window.$gz.form.fieldValueChanged(this.pvm, ref);

        // //set viz if applicable
        // if(ref==""){
        //    let selectedPartWarehouse = vm.$refs.partWarehouseId.getFullSelectionValue();
        // }
      }
    },
    itemRowClasses: function(item) {
      let ret = "";
      const isDeleted =
        this.value.items[this.activeWoItemIndex].units[item.index].deleted ===
        true;

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

      if (isDeleted) {
        ret += this.form().tableRowDeletedClass();
      }
      if (hasError) {
        ret += this.form().tableRowErrorClass();
      }
      return ret;
    }
  },
  computed: {
    isDeleted: function() {
      if (
        this.value.items[this.activeWoItemIndex].units[this.activeItemIndex] ==
        null
      ) {
        this.setDefaultView();
        return true;
      }
      return (
        this.value.items[this.activeWoItemIndex].units[this.activeItemIndex]
          .deleted === true
      );
    },
    parentDeleted: function() {
      return this.value.items[this.activeWoItemIndex].deleted === true;
    },

    headerList: function() {
      /*
  If the column is a text, left-align it
  If the column is a number or number + unit, (or date) right-align it (like excel)
  */
      let headers = [];

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

      if (this.form().showMe(this, "UnitModelModelNumber")) {
        headers.push({
          text: this.$ay.t("UnitModelModelNumber"),
          align: "left",
          value: "unitModelModelNumberViz"
        });
      }
      if (this.form().showMe(this, "UnitModelVendorID")) {
        headers.push({
          text: this.$ay.t("UnitModelVendorID"),
          align: "left",
          value: "unitModelVendorViz"
        });
      }

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

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

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

      return headers;
    },
    itemList: function() {
      return this.value.items[this.activeWoItemIndex].units.map((x, i) => {
        return {
          index: i,
          id: x.id,
          unitViz: x.unitViz,
          unitModelModelNumberViz: x.unitModelModelNumberViz,
          unitModelVendorViz: x.unitModelVendorViz,
          unitModelNameViz: x.unitModelNameViz,
          unitDescriptionViz: x.unitDescriptionViz,
          notes: window.$gz.util.truncateString(
            x.notes,
            this.pvm.maxTableNotesLength
          )
        };
      });
    },
    formState: function() {
      return this.pvm.formState;
    },
    formCustomTemplateKey: function() {
      return this.pvm.formCustomTemplateKey;
    },
    hasData: function() {
      return this.value.items[this.activeWoItemIndex].units.length > 0;
    },
    hasSelection: function() {
      return this.activeItemIndex != null;
    },
    canAdd: function() {
      return this.pvm.rights.change && !this.value.userIsRestrictedType;
    },
    canDelete: function() {
      return (
        this.activeItemIndex != null &&
        this.canDeleteAll &&
        !this.value.userIsRestrictedType
      );
    },
    canDeleteAll: function() {
      return this.pvm.rights.change && !this.value.userIsRestrictedType;
    }
  }
};
</script>
