<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"
                >$ayiBoxes</v-icon
              >
              {{ $ay.t("WorkOrderItemPartList") }}
              <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="generateUnit"
            >
              <v-list-item-icon>
                <v-icon>$ayiFan</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{
                $ay.t("WorkOrderGenerateUnit")
              }}</v-list-item-title>
            </v-list-item>
            <v-list-item v-if="canAdd" @click="partAssemblyDialog = true">
              <v-list-item-icon>
                <v-icon>$ayiObjectGroup</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{ $ay.t("PartAssembly") }}</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="partsTable"
            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="parttopform"></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 cols="12" sm="6" lg="4" xl="3">
          <gz-pick-list
            :ref="
              `Items[${activeWoItemIndex}].parts[${activeItemIndex}].partId`
            "
            v-model="
              value.items[activeWoItemIndex].parts[activeItemIndex].partId
            "
            :aya-type="$ay.ayt().Part"
            :show-edit-icon="!value.userIsRestrictedType"
            :readonly="
              formState.readOnly || isDeleted || value.userIsRestrictedType
            "
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemPartPartID')"
            data-cy="parts.partId"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].parts[${activeItemIndex}].partId`
              )
            "
            :rules="[
              form().required(
                this,
                `Items[${activeWoItemIndex}].parts[${activeItemIndex}].partId`
              )
            ]"
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].parts[${activeItemIndex}].partId`
              )
            "
            @update:name="partChange"
          ></gz-pick-list>
        </v-col>

        <v-col
          v-if="pvm.useInventory && !value.userIsRestrictedType"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-pick-list
            :ref="
              `Items[${activeWoItemIndex}].parts[${activeItemIndex}].partWarehouseId`
            "
            v-model="
              value.items[activeWoItemIndex].parts[activeItemIndex]
                .partWarehouseId
            "
            :aya-type="$ay.ayt().PartWarehouse"
            show-edit-icon
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemPartPartWarehouseID')"
            data-cy="parts.partWarehouseId"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].parts[${activeItemIndex}].partWarehouseId`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].parts[${activeItemIndex}].partWarehouseId`
              )
            "
            @update:name="warehouseChange"
          ></gz-pick-list>
        </v-col>
        <v-col cols="12" sm="6" lg="4" xl="3">
          <gz-decimal
            :ref="
              `Items[${activeWoItemIndex}].parts[${activeItemIndex}].quantity`
            "
            v-model="
              value.items[activeWoItemIndex].parts[activeItemIndex].quantity
            "
            :readonly="
              formState.readOnly || isDeleted || value.userIsRestrictedType
            "
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemPartQuantity')"
            data-cy="partQuantity"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].parts[${activeItemIndex}].quantity`
              )
            "
            :rules="[
              form().decimalValid(
                this,
                `Items[${activeWoItemIndex}].parts[${activeItemIndex}].quantity`
              ),
              form().required(
                this,
                `Items[${activeWoItemIndex}].parts[${activeItemIndex}].quantity`
              )
            ]"
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].parts[${activeItemIndex}].quantity`
              )
            "
          ></gz-decimal>
          <template
            v-if="
              value.items[activeWoItemIndex].parts[activeItemIndex]
                .requestAmountViz != null
            "
          >
            <v-btn color="secondary" text @click="doRequest()">
              <v-icon left>
                $ayiParachuteBox
              </v-icon>
              {{ requestMore }}
            </v-btn>
          </template>
        </v-col>

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemPartDescription')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <v-text-field
            :ref="
              `Items[${activeWoItemIndex}].parts[${activeItemIndex}].description`
            "
            v-model="
              value.items[activeWoItemIndex].parts[activeItemIndex].description
            "
            dense
            :readonly="
              formState.readOnly || isDeleted || value.userIsRestrictedType
            "
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemPartDescription')"
            data-cy="partQuantity"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].parts[${activeItemIndex}].description`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].parts[${activeItemIndex}].description`
              )
            "
          ></v-text-field>
        </v-col>

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

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

        <v-col v-if="form().showMe(this, 'WorkOrderItemPartSerials')" cols="12">
          <v-textarea
            :ref="
              `Items[${activeWoItemIndex}].parts[${activeItemIndex}].serials`
            "
            v-model="
              value.items[activeWoItemIndex].parts[activeItemIndex].serials
            "
            dense
            :readonly="formState.readOnly || value.userIsRestrictedType"
            :disabled="isDeleted"
            :label="$ay.t('PurchaseOrderItemSerialNumbers')"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].parts[${activeItemIndex}].serials`
              )
            "
            data-cy="partSerials"
            auto-grow
            prepend-icon="$ayiListUl"
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].parts[${activeItemIndex}].serials`
              )
            "
            @click:prepend="selectSerials()"
          ></v-textarea>
        </v-col>
      </template>
    </v-row>
    <!-- ################################################################################-->
    <!-- ##########################  ASSEMBLY SELECTOR FORM  ###############################-->
    <!-- ################################################################################-->
    <template>
      <v-row dense justify="center">
        <v-dialog v-model="partAssemblyDialog" max-width="600px">
          <v-card>
            <v-card-title> </v-card-title>
            <v-card-text>
              <gz-pick-list
                ref="selectedPartAssembly"
                v-model="selectedPartAssembly"
                :aya-type="$ay.ayt().PartAssembly"
                show-edit-icon
                :label="$ay.t('PartAssemblyList')"
                data-cy="selectedPartAssembly"
              ></gz-pick-list>

              <gz-pick-list
                v-if="
                  pvm.useInventory &&
                    form().showMe(this, 'WorkOrderItemPartPartWarehouseID')
                "
                ref="selectedPartWarehouse"
                v-model="selectedPartWarehouse"
                :aya-type="$ay.ayt().PartWarehouse"
                show-edit-icon
                :label="$ay.t('WorkOrderItemPartPartWarehouseID')"
                data-cy="selectedPartWarehouse"
              ></gz-pick-list>
            </v-card-text>
            <v-card-actions>
              <v-btn text color="primary" @click="partAssemblyDialog = false">{{
                $ay.t("Cancel")
              }}</v-btn>
              <v-spacer></v-spacer>
              <v-btn
                :disabled="selectedPartAssembly == null"
                color="primary"
                text
                class="ml-4"
                @click="addPartAssembly()"
                >{{ $ay.t("Add") }}</v-btn
              >
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-row>
    </template>
    <!-- ################################################################################-->
    <!-- ##########################  SERIAL NUMBER SELECTOR FORM  ###############################-->
    <!-- ################################################################################-->
    <template>
      <v-row dense justify="center">
        <v-dialog v-model="serialDialog" persistent max-width="600px">
          <v-card>
            <v-card-title>
              <v-btn text color="primary" @click="serialDialog = false">{{
                $ay.t("Cancel")
              }}</v-btn>
              <v-spacer></v-spacer>
              <v-btn
                :disabled="selectedSerials.length == 0"
                color="primary"
                text
                @click="addSelectedSerials()"
                >{{ $ay.t("Add") }}</v-btn
              >
            </v-card-title>
            <v-card-text>
              <v-select
                v-model="selectedSerials"
                dense
                :items="availableSerials"
                :label="$ay.t('PartSerialNumbersAvailable')"
                multiple
              ></v-select>
            </v-card-text>
          </v-card>
        </v-dialog>
      </v-row>
    </template>
  </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: [],
      partAssemblyDialog: false,
      selectedPartAssembly: null,
      selectedPartWarehouse: 1,
      serialDialog: false,
      availableSerials: [],
      selectedSerials: []
    };
  },
  computed: {
    requestMore: function() {
      return this.$ay
        .t("WorkOrderItemPartRequestMore")
        .replace(
          "{n}",
          this.value.items[this.activeWoItemIndex].parts[this.activeItemIndex]
            .requestAmountViz
        );
    },
    isDeleted: function() {
      if (
        this.value.items[this.activeWoItemIndex].parts[this.activeItemIndex] ==
        null
      ) {
        this.setDefaultView();
        return true;
      }
      return (
        this.value.items[this.activeWoItemIndex].parts[this.activeItemIndex]
          .deleted === true
      );
    },
    parentDeleted: function() {
      return this.value.items[this.activeWoItemIndex].deleted === true;
    },

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

      headers.push({
        text: this.$ay.t("WorkOrderItemPartPartID"),
        align: "left",
        value: "partNameViz"
      });

      if (this.pvm.useInventory && !this.value.userIsRestrictedType) {
        headers.push({
          text: this.$ay.t("WorkOrderItemPartPartWarehouseID"),
          align: "left",
          value: "partWarehouseViz"
        });
      }

      headers.push({
        text: this.$ay.t("WorkOrderItemPartQuantity"),
        align: "right",
        value: "quantity"
      });

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

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

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

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

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

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

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

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

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

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

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

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

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

      if (
        this.form().showMe(this, "PartLineTotalViz") &&
        !this.value.userIsRestrictedType
      ) {
        headers.push({
          text: this.$ay.t("LineTotal"),
          align: "right",
          value: "lineTotalViz"
        });
      }
      return headers;
    },
    itemList: function() {
      return this.value.items[this.activeWoItemIndex].parts.map((x, i) => {
        return {
          index: i,
          id: x.id,
          partNameViz: x.partNameViz,
          partWarehouseViz: x.partWarehouseViz,
          quantity: window.$gz.locale.decimalLocalized(
            x.quantity,
            this.pvm.languageName
          ),
          partDescriptionViz: x.partDescriptionViz,
          upcViz: x.upcViz,
          description: x.description,
          serials: window.$gz.util.truncateString(
            x.serials,
            this.pvm.maxTableNotesLength
          ),
          unitOfMeasureViz: x.unitOfMeasureViz,
          cost: window.$gz.locale.currencyLocalized(
            x.cost,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          listPrice: window.$gz.locale.currencyLocalized(
            x.listPrice,
            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
          )
        };
      });
    },
    formState: function() {
      return this.pvm.formState;
    },
    formCustomTemplateKey: function() {
      return this.pvm.formCustomTemplateKey;
    },
    hasData: function() {
      return this.value.items[this.activeWoItemIndex].parts.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;
    }

    //----
  },
  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.parttopform;
          if (el) {
            el.scrollIntoView({ behavior: "smooth" });
          }
        });
      }
    }
  },
  created() {
    this.setDefaultView();
  },
  methods: {
    generateUnit() {
      const thisPart = this.value.items[this.activeWoItemIndex].parts[
        this.activeItemIndex
      ];
      this.$router.push({
        name: "unit-edit",
        params: {
          recordid: 0,
          genFromPart: {
            customerId: this.value.customerId,
            partId: thisPart.partId,
            purchaseDate: this.value.serviceDate,
            serial: thisPart.serials,
            address: this.value.address,
            city: this.value.city,
            region: this.value.region,
            country: this.value.country,
            latitude: this.value.latitude,
            longitude: this.value.longitude
          }
        }
      });
    },
    async selectSerials() {
      this.availableSerials.splice(0);
      this.selectedSerials.splice(0);

      const partId = this.value.items[this.activeWoItemIndex].parts[
        this.activeItemIndex
      ].partId;
      if (!partId || partId == 0) {
        return;
      }
      const res = await window.$gz.api.get(`part/serials/${partId}`);
      if (res.error) {
        window.$gz.eventBus.$emit(
          "notify-warning",
          window.$gz.errorHandler.errorToString(res, this)
        );
      } else {
        this.availableSerials = res.data;
        this.serialDialog = true;
      }
    },
    addSelectedSerials() {
      let serials = this.value.items[this.activeWoItemIndex].parts[
        this.activeItemIndex
      ].serials;

      if (!window.$gz.util.stringIsNullOrEmpty(serials)) {
        serials = serials.trim();
        serials += ", ";
      } else {
        serials = "";
      }

      serials += this.selectedSerials.join(", ");

      this.value.items[this.activeWoItemIndex].parts[
        this.activeItemIndex
      ].serials = serials;
      this.serialDialog = false;
      this.availableSerials.splice(0);
      this.selectedSerials.splice(0);
      this.value.items[this.activeWoItemIndex].parts[
        this.activeItemIndex
      ].isDirty = true;
      this.$emit("change");
    },
    async addPartAssembly() {
      const res = await window.$gz.api.get(
        `part-assembly/${this.selectedPartAssembly}`
      );
      if (res.data && res.data.items) {
        let newIndex = this.value.items[this.activeWoItemIndex].parts.length;
        res.data.items.forEach(z => {
          newIndex++;
          this.value.items[this.activeWoItemIndex].parts.push({
            id: 0,
            concurrency: 0,
            userId: null,
            description: null,
            serials: null,
            partId: z.partId,
            partWarehouseId: this.selectedPartWarehouse,
            quantity: z.quantity,
            taxPartSaleId:
              window.$gz.store.state.globalSettings.defaultTaxPartSaleId,
            price: 0,
            priceOverride: null,
            cost: 0,
            listPrice: 0,
            isDirty: true,
            quoteItemId: this.value.items[this.activeWoItemIndex].id,
            uid: Date.now(),
            partWarehouseViz: null,
            partNameViz: z.partNameViz,
            taxCodeViz: null
          });
        });
        this.$emit("change");
        this.selectedRow = [{ index: newIndex }];
        this.activeItemIndex = newIndex;
      }

      this.partAssemblyDialog = false;
    },
    doRequest() {
      const requestQuantity = this.value.items[this.activeWoItemIndex].parts[
        this.activeItemIndex
      ].requestAmountViz; //set in svc-workorder.vue on save of part with insufficient qty
      if (requestQuantity != null && requestQuantity > 0) {
        //Get names for UI for request record so user knows it's the right one
        let selectedPartWarehouse = this.$refs[
          `Items[${this.activeWoItemIndex}].parts[${this.activeItemIndex}].partWarehouseId`
        ].getFullSelectionValue();
        if (
          selectedPartWarehouse != null &&
          selectedPartWarehouse.name != null
        ) {
          selectedPartWarehouse = selectedPartWarehouse.name;
        }

        let selectedPart = this.$refs[
          `Items[${this.activeWoItemIndex}].parts[${this.activeItemIndex}].partId`
        ].getFullSelectionValue();
        if (selectedPart != null && selectedPart.name != null) {
          selectedPart = selectedPart.name;
        }

        //change the part quantity to the balance in stock
        this.value.items[this.activeWoItemIndex].parts[
          this.activeItemIndex
        ].quantity =
          this.value.items[this.activeWoItemIndex].parts[this.activeItemIndex]
            .quantity - requestQuantity;

        //add a request record
        this.value.items[this.activeWoItemIndex].partRequests.push({
          id: 0,
          concurrency: 0,
          partId: this.value.items[this.activeWoItemIndex].parts[
            this.activeItemIndex
          ].partId,
          partNameViz: selectedPart,
          partWarehouseId: this.value.items[this.activeWoItemIndex].parts[
            this.activeItemIndex
          ].partWarehouseId,
          partWarehouseViz: selectedPartWarehouse,
          quantity: requestQuantity,
          isDirty: true,
          quoteItemId: this.value.items[this.activeWoItemIndex].id,
          uid: Date.now(),
          requestAmountViz: null
        });

        this.$emit("change");

        //clear the error but leave dirty and let user save it
        this.value.items[this.activeWoItemIndex].parts[
          this.activeItemIndex
        ].requestAmountViz = null;

        this.fieldValueChanged(`Items[${this.activeWoItemIndex}].parts[
              ${this.activeItemIndex}
            ].quantity`);
      }
    },

    warehouseChange(newName) {
      this.value.items[this.activeWoItemIndex].parts[
        this.activeItemIndex
      ].partWarehouseViz = newName;
    },
    partChange(newName) {
      this.value.items[this.activeWoItemIndex].parts[
        this.activeItemIndex
      ].partNameViz = newName;
    },
    taxCodeChange(newName) {
      this.value.items[this.activeWoItemIndex].parts[
        this.activeItemIndex
      ].taxCodeViz = newName;
    },
    newItem() {
      const newIndex = this.value.items[this.activeWoItemIndex].parts.length;

      this.value.items[this.activeWoItemIndex].parts.push({
        id: 0,
        concurrency: 0,
        userId: null,
        description: null,
        serials: null,
        partId: 0, //deliberately zero to break rule on new
        partWarehouseId: 1, //important always default to "default" warehouse id 1 as even with inventory turned off it's required
        quantity: 1,
        taxPartSaleId:
          window.$gz.store.state.globalSettings.defaultTaxPartSaleId,
        price: 0,
        priceOverride: null,
        cost: 0,
        listPrice: 0,
        isDirty: true,
        quoteItemId: this.value.items[this.activeWoItemIndex].id,
        uid: Date.now(),
        partWarehouseViz: null,
        partNameViz: null,
        taxCodeViz: null
      });
      this.$emit("change");
      this.selectedRow = [{ index: newIndex }];
      this.activeItemIndex = newIndex;
      //trigger rule breaking / validation
      this.$nextTick(() => {
        this.value.items[this.activeWoItemIndex].parts[
          this.activeItemIndex
        ].partId = null;
        this.fieldValueChanged(
          `Items[${this.activeWoItemIndex}].parts[${this.activeItemIndex}].partId`
        );
      });
      return newIndex; //for create new on goto
    },
    unDeleteItem() {
      this.value.items[this.activeWoItemIndex].parts[
        this.activeItemIndex
      ].deleted = false;
      this.setDefaultView();
    },
    deleteItem() {
      this.value.items[this.activeWoItemIndex].parts[
        this.activeItemIndex
      ].deleted = true;
      this.setDefaultView();
      this.$emit("change");
    },
    deleteAllItem() {
      this.value.items[this.activeWoItemIndex].parts.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].parts.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].parts[
          this.activeItemIndex
        ].isDirty = true;
        window.$gz.form.fieldValueChanged(this.pvm, ref);
      }

      //reset part request if part, qty or warehouse is changed
      if (
        this.value.items[this.activeWoItemIndex].parts[this.activeItemIndex]
          .requestAmountViz != null
      ) {
        if (
          ref.endsWith("partWarehouseId") ||
          ref.endsWith("partId") ||
          ref.endsWith("quantity")
        )
          this.value.items[this.activeWoItemIndex].parts[
            this.activeItemIndex
          ].requestAmountViz = null;
      }
    },
    itemRowClasses: function(item) {
      let ret = "";
      const isDeleted =
        this.value.items[this.activeWoItemIndex].parts[item.index].deleted ===
        true;

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

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