<template>
  <div>
    <!-- {{ obj.items }} -->
    <gz-report-selector ref="reportSelector"></gz-report-selector>
    <div v-if="formState.ready">
      <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
      <gz-alert :alert-message="obj.vendorAlertNotesViz" pop-alert></gz-alert>
      <v-form ref="form">
        <v-row>
          <v-col
            cols="12"
            sm="6"
            lg="4"
            xl="3"
            v-if="obj.serial != 0 && canEditSerial"
          >
            <v-text-field
              v-model="obj.serial"
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderPONumber')"
              ref="serial"
              data-cy="serial"
              :rules="[
                form().integerValid(this, 'serial'),
                form().required(this, 'serial')
              ]"
              :error-messages="form().serverErrors(this, 'serial')"
              @input="fieldValueChanged('serial')"
            ></v-text-field>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-pick-list
              :aya-type="ayaTypes().Vendor"
              show-edit-icon
              :allow-no-selection="false"
              v-model="obj.vendorId"
              :readonly="formState.readOnly"
              :label="$ay.t('Vendor')"
              ref="vendorId"
              data-cy="vendorId"
              :error-messages="form().serverErrors(this, 'vendorId')"
              @input="fieldValueChanged('vendorId')"
              :rules="[form().required(this, 'vendorId')]"
            ></gz-pick-list>
          </v-col>
          <v-col
            v-if="form().showMe(this, 'Status')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <v-select
              v-model="obj.status"
              :items="selectLists.status"
              item-text="name"
              item-value="id"
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderStatus')"
              ref="status"
              data-cy="status"
              :rules="[form().integerValid(this, 'status')]"
              :error-messages="form().serverErrors(this, 'status')"
              @input="fieldValueChanged('status')"
            ></v-select>
          </v-col>

          <v-col
            v-if="form().showMe(this, 'OrderedDate')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <gz-date-time-picker
              :label="$ay.t('PurchaseOrderOrderedDate')"
              v-model="obj.orderedDate"
              :readonly="formState.readOnly"
              ref="orderedDate"
              data-cy="orderedDate"
              :error-messages="form().serverErrors(this, 'orderedDate')"
              @input="fieldValueChanged('orderedDate')"
            ></gz-date-time-picker>
          </v-col>

          <v-col
            v-if="form().showMe(this, 'ExpectedReceiveDate')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <gz-date-time-picker
              :label="$ay.t('PurchaseOrderExpectedReceiveDate')"
              v-model="obj.expectedReceiveDate"
              :readonly="formState.readOnly"
              ref="expectedReceiveDate"
              data-cy="expectedReceiveDate"
              :error-messages="form().serverErrors(this, 'expectedReceiveDate')"
              @input="fieldValueChanged('expectedReceiveDate')"
            ></gz-date-time-picker>
          </v-col>

          <v-col
            v-if="form().showMe(this, 'ReferenceNumber')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <v-text-field
              v-model="obj.referenceNumber"
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderReferenceNumber')"
              ref="referenceNumber"
              data-cy="referenceNumber"
              :error-messages="form().serverErrors(this, 'referenceNumber')"
              @input="fieldValueChanged('referenceNumber')"
            ></v-text-field>
          </v-col>
          <v-col
            v-if="form().showMe(this, 'ProjectId')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <gz-pick-list
              :aya-type="ayaTypes().Project"
              show-edit-icon
              v-model="obj.projectId"
              :readonly="formState.readOnly"
              :label="$ay.t('Project')"
              ref="projectId"
              data-cy="projectId"
              :error-messages="form().serverErrors(this, 'projectId')"
              @input="fieldValueChanged('projectId')"
            ></gz-pick-list>
          </v-col>
          <v-col
            v-if="form().showMe(this, 'vendorMemo')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <v-textarea
              v-model="obj.vendorMemo"
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderVendorMemo')"
              :error-messages="form().serverErrors(this, 'vendorMemo')"
              ref="vendorMemo"
              data-cy="vendorMemo"
              @input="fieldValueChanged('vendorMemo')"
              auto-grow
            ></v-textarea>
          </v-col>

          <v-col
            v-if="form().showMe(this, 'Text1')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <v-text-field
              v-model="obj.text1"
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderReceiptText1')"
              ref="text1"
              data-cy="text1"
              :error-messages="form().serverErrors(this, 'text1')"
              @input="fieldValueChanged('text1')"
            ></v-text-field>
          </v-col>

          <v-col
            v-if="form().showMe(this, 'Text2')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <v-text-field
              v-model="obj.text2"
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderReceiptText2')"
              ref="text2"
              data-cy="text2"
              :error-messages="form().serverErrors(this, 'text2')"
              @input="fieldValueChanged('text2')"
            ></v-text-field>
          </v-col>

          <v-col
            v-if="form().showMe(this, 'DropShipToCustomerId')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <gz-pick-list
              :aya-type="ayaTypes().Customer"
              show-edit-icon
              v-model="obj.dropShipToCustomerId"
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderDropShipToCustomerID')"
              ref="dropShipToCustomerId"
              data-cy="dropShipToCustomerId"
              :error-messages="
                form().serverErrors(this, 'dropShipToCustomerId')
              "
              @input="fieldValueChanged('dropShipToCustomerId')"
            ></gz-pick-list>
          </v-col>

          <v-col v-if="form().showMe(this, 'Notes')" cols="12">
            <v-textarea
              v-model="obj.notes"
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderNotes')"
              :error-messages="form().serverErrors(this, 'notes')"
              ref="notes"
              data-cy="notes"
              @input="fieldValueChanged('notes')"
              auto-grow
            ></v-textarea>
          </v-col>

          <!-- ################################ PURCHASE ORDER ITEMS LIST ############################### -->

          <v-col cols="12">
            <v-data-table
              :headers="headerList"
              :items="itemList"
              item-key="index"
              class="elevation-1"
              disable-pagination
              disable-filtering
              disable-sort
              hide-default-footer
              data-cy="itemsTable"
              dense
              :item-class="poItemsRowClasses"
              :no-data-text="$ay.t('NoData')"
            >
              <template v-slot:[`item.workOrderItemPartRequestViz`]="{ item }">
                <div class="subtitle-1" @click="openWOItemPartRequest(item)">
                  <a href="javascript:">
                    {{ item.workOrderItemPartRequestViz }}</a
                  >
                </div>
              </template>
              <template v-slot:top>
                <v-col cols="12">
                  <v-menu offset-y v-if="rights.change">
                    <template v-slot:activator="{ on, attrs }">
                      <span class="text-subtitle-2">
                        {{ $ay.t("PurchaseOrderItemList") }}</span
                      ><v-btn large icon v-bind="attrs" v-on="on">
                        <v-icon small color="primary">$ayiEllipsisV</v-icon>
                      </v-btn>
                    </template>
                    <v-list>
                      <v-list-item @click="newPOItem">
                        <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 @click="showRestockSelectDialog()">
                        <v-list-item-icon>
                          <v-icon>$ayiClipboardList</v-icon>
                        </v-list-item-icon>
                        <v-list-item-title>{{
                          $ay.t("PurchaseOrderUIRestockList")
                        }}</v-list-item-title>
                      </v-list-item>

                      <v-list-item @click="showRequestSelectDialog()">
                        <v-list-item-icon>
                          <v-icon>$ayiParachuteBox</v-icon>
                        </v-list-item-icon>
                        <v-list-item-title>{{
                          $ay.t("WorkOrderItemPartRequestList")
                        }}</v-list-item-title>
                      </v-list-item>

                      <v-divider></v-divider>
                      <v-list-item
                        @click="receiveAll"
                        :disabled="!obj.hasUnreceived"
                      >
                        <v-list-item-icon>
                          <v-icon>$ayiBoxOpen</v-icon>
                        </v-list-item-icon>
                        <v-list-item-title>{{
                          $ay.t("ReceiveAll")
                        }}</v-list-item-title>
                      </v-list-item>
                    </v-list>
                  </v-menu>
                  <span class="text-h6" v-else>
                    {{ $ay.t("PurchaseOrderItemList") }}</span
                  >
                </v-col>
              </template>

              <template v-slot:[`item.actions`]="{ item }">
                <v-btn icon @click="editItem(item)">
                  <v-icon :class="poItemsRowClasses(item)">
                    $ayiEdit
                  </v-icon>
                </v-btn>
              </template>
            </v-data-table>
          </v-col>

          <!-- --------------------------------- -->

          <v-col v-if="form().showMe(this, 'Tags')" cols="12">
            <gz-tag-picker
              v-model="obj.tags"
              :readonly="formState.readOnly"
              ref="tags"
              data-cy="tags"
              :error-messages="form().serverErrors(this, 'tags')"
              @input="fieldValueChanged('tags')"
            ></gz-tag-picker>
          </v-col>

          <v-col cols="12">
            <gz-custom-fields
              v-model="obj.customFields"
              :form-key="formCustomTemplateKey"
              :readonly="formState.readOnly"
              :parent-v-m="this"
              ref="customFields"
              data-cy="customFields"
              :error-messages="form().serverErrors(this, 'customFields')"
              @input="fieldValueChanged('customFields')"
            ></gz-custom-fields>
          </v-col>

          <v-col v-if="form().showMe(this, 'Wiki')" cols="12">
            <gz-wiki
              :aya-type="ayaType"
              :aya-id="obj.id"
              ref="wiki"
              v-model="obj.wiki"
              :readonly="formState.readOnly"
              @input="fieldValueChanged('wiki')"
            ></gz-wiki
          ></v-col>

          <v-col v-if="form().showMe(this, 'Attachments') && obj.id" cols="12">
            <gz-attachments
              :readonly="formState.readOnly"
              :aya-type="ayaType"
              :aya-id="obj.id"
            ></gz-attachments
          ></v-col>
        </v-row>
      </v-form>
    </div>
    <v-overlay :value="!formState.ready || formState.loading">
      <v-progress-circular indeterminate :size="64" />
    </v-overlay>
    <!-- #########################################################################################-->
    <!-- ########################## PURCHASE ORDER ITEM EDIT FORM  ###############################-->
    <!-- #########################################################################################-->
    <template v-if="obj.items.length">
      <v-row justify="center">
        <v-dialog v-model="editPoItemDialog">
          <v-card>
            <v-card-title>
              <template
                v-if="
                  obj.items[editPoItemIndex].workOrderItemPartRequestId != null
                "
              >
                <v-btn text @click="openWOItemPartRequest()">
                  <v-icon>$ayiParachuteBox</v-icon>

                  <span
                    class="text-h6 accent--text"
                    @click="openWOItemPartRequest()"
                    >{{ $ay.t("WorkOrderItemPartRequest") }}
                    {{
                      obj.items[editPoItemIndex].workOrderItemPartRequestViz
                    }}</span
                  ></v-btn
                >
              </template>
            </v-card-title>
            <v-card-text>
              <v-row>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-pick-list
                    :aya-type="ayaTypes().Part"
                    :allow-no-selection="false"
                    show-edit-icon
                    v-model="obj.items[editPoItemIndex].partId"
                    :readonly="formState.readOnly"
                    :label="$ay.t('Part')"
                    ref="Items.PartId"
                    data-cy="Items.PartId"
                    :rules="[form().required(this, 'Items.PartId')]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `Items[${editPoItemIndex}].PartId`
                      )
                    "
                    @input="
                      fieldValueChanged(`Items[${editPoItemIndex}].PartId`)
                    "
                  ></gz-pick-list>
                </v-col>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-pick-list
                    v-if="obj.hasSelectableWarehouses"
                    :aya-type="ayaTypes().PartWarehouse"
                    :allow-no-selection="false"
                    show-edit-icon
                    v-model="obj.items[editPoItemIndex].partWarehouseId"
                    :readonly="formState.readOnly"
                    :label="$ay.t('PartWarehouse')"
                    ref="Items.PartWarehouseId"
                    data-cy="Items.PartWarehouseId"
                    :rules="[form().required(this, 'Items.PartWarehouseId')]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `Items[${editPoItemIndex}].PartWarehouseId`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `Items[${editPoItemIndex}].PartWarehouseId`
                      )
                    "
                  ></gz-pick-list>
                </v-col>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-decimal
                    v-model="obj.items[editPoItemIndex].quantityOrdered"
                    :readonly="
                      formState.readOnly ||
                        obj.items[editPoItemIndex].workOrderItemPartRequestId !=
                          null
                    "
                    :label="$ay.t('PurchaseOrderItemQuantityOrdered')"
                    ref="Items.QuantityOrdered"
                    data-cy="Items.QuantityOrdered"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `Items[${editPoItemIndex}].QuantityOrdered`
                      )
                    "
                    :rules="[
                      form().decimalValid(this, 'Items.QuantityOrdered'),
                      form().required(this, 'Items.QuantityOrdered')
                    ]"
                    @input="
                      fieldValueChanged(
                        `Items[${editPoItemIndex}].QuantityOrdered`
                      )
                    "
                  ></gz-decimal>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-decimal
                    v-model="obj.items[editPoItemIndex].quantityReceived"
                    :readonly="formState.readOnly"
                    :label="$ay.t('PurchaseOrderItemQuantityReceived')"
                    ref="Items.QuantityReceived"
                    data-cy="Items.QuantityReceived"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `Items[${editPoItemIndex}].QuantityReceived`
                      )
                    "
                    :rules="[
                      form().decimalValid(this, 'Items.QuantityReceived'),
                      form().required(this, 'Items.QuantityReceived')
                    ]"
                    @input="
                      fieldValueChanged(
                        `Items[${editPoItemIndex}].QuantityReceived`
                      )
                    "
                  ></gz-decimal>
                </v-col>

                <v-col
                  v-if="form().showMe(this, 'Items.ReceivedDate')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <gz-date-time-picker
                    :label="$ay.t('PurchaseOrderReceiptReceivedDate')"
                    v-model="obj.items[editPoItemIndex].receivedDate"
                    :readonly="formState.readOnly"
                    ref="Items.ReceivedDate"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `Items[${editPoItemIndex}].ReceivedDate`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `Items[${editPoItemIndex}].ReceivedDate`
                      )
                    "
                  ></gz-date-time-picker>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-currency
                    v-model="obj.items[editPoItemIndex].purchaseOrderCost"
                    :readonly="formState.readOnly"
                    :label="$ay.t('PurchaseOrderItemPurchaseOrderCost')"
                    ref="Items.PurchaseOrderCost"
                    data-cy="Items.PurchaseOrderCost"
                    :rules="[
                      form().decimalValid(this, 'Items.PurchaseOrderCost'),
                      form().required(this, 'Items.PurchaseOrderCost')
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `Items[${editPoItemIndex}].PurchaseOrderCost`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `Items[${editPoItemIndex}].PurchaseOrderCost`
                      )
                    "
                  ></gz-currency>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-currency
                    v-model="obj.items[editPoItemIndex].receivedCost"
                    :readonly="formState.readOnly"
                    :label="$ay.t('PurchaseOrderReceiptItemReceiptCost')"
                    :append-outer-icon="
                      updatePartCostIcon(obj.items[editPoItemIndex])
                    "
                    @gz-append-outer="
                      updatePartCost(obj.items[editPoItemIndex])
                    "
                    ref="Items.ReceivedCost"
                    data-cy="Items.ReceivedCost"
                    :rules="[
                      form().decimalValid(this, 'Items.ReceivedCost'),
                      form().required(this, 'Items.ReceivedCost')
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `Items[${editPoItemIndex}].ReceivedCost`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `Items[${editPoItemIndex}].ReceivedCost`
                      )
                    "
                  ></gz-currency>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-pick-list
                    v-if="form().showMe(this, 'Items.PurchaseTaxCodeId')"
                    :aya-type="ayaTypes().TaxCode"
                    show-edit-icon
                    v-model="obj.items[editPoItemIndex].purchaseTaxCodeId"
                    :readonly="formState.readOnly"
                    :label="$ay.t('TaxCode')"
                    ref="Items.PurchaseTaxCodeId"
                    data-cy="Items.PurchaseTaxCodeId"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `Items[${editPoItemIndex}].PurchaseTaxCodeId`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `Items[${editPoItemIndex}].PurchaseTaxCodeId`
                      )
                    "
                  ></gz-pick-list>
                </v-col>

                <v-col
                  v-if="form().showMe(this, 'Items.VendorPartNumber')"
                  cols="12"
                  sm="6"
                  lg="4"
                  xl="3"
                >
                  <v-text-field
                    v-model="obj.items[editPoItemIndex].vendorPartNumber"
                    :readonly="formState.readOnly"
                    :clearable="!formState.readOnly"
                    @click:clear="fieldValueChanged('Items.VendorPartNumber')"
                    :label="$ay.t('PurchaseOrderItemVendorPartNumber')"
                    ref="Items.VendorPartNumber"
                    data-cy="Items.VendorPartNumber"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `Items[${editPoItemIndex}].VendorPartNumber`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `Items[${editPoItemIndex}].VendorPartNumber`
                      )
                    "
                  ></v-text-field>
                </v-col>

                <v-col v-if="form().showMe(this, 'Items.Serials')" cols="12">
                  <v-textarea
                    outlined
                    v-model="obj.items[editPoItemIndex].serials"
                    :readonly="formState.readOnly"
                    :label="$ay.t('PurchaseOrderItemSerialNumbers')"
                    :rows="$vuetify.breakpoint.xs ? 3 : 5"
                    ref="Items.Serials"
                    data-cy="Items.Serials"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `Items[${editPoItemIndex}].serials`
                      )
                    "
                    @input="
                      fieldValueChanged(`Items[${editPoItemIndex}].serials`)
                    "
                  ></v-textarea>
                </v-col>
              </v-row>
            </v-card-text>
            <v-card-actions>
              <template v-if="!$vuetify.breakpoint.xs">
                <v-btn
                  color="red darken-1"
                  text
                  @click="deletePoItem(obj.items[editPoItemIndex])"
                  >{{ $ay.t("Delete") }}</v-btn
                >
                <v-spacer></v-spacer>
                <v-btn
                  color="blue darken-1"
                  text
                  @click="editPoItemDialog = false"
                  >{{ $ay.t("Close") }}</v-btn
                >

                <v-btn
                  color="blue darken-1"
                  text
                  @click="newPOItem()"
                  class="ml-4"
                  >{{ $ay.t("New") }}</v-btn
                >
                <v-btn
                  v-if="
                    obj.items[editPoItemIndex].quantityReceived <
                      obj.items[editPoItemIndex].quantityOrdered
                  "
                  color="blue darken-1"
                  text
                  @click="receive(obj.items[editPoItemIndex])"
                  class="ml-4"
                  ><v-icon left> $ayiBoxOpen </v-icon
                  >{{ $ay.t("ReceiveAll") }}</v-btn
                >
                <v-btn
                  color="blue darken-1"
                  text
                  @click="submit()"
                  class="ml-4"
                  >{{ $ay.t("Save") }}</v-btn
                >
              </template>
              <template v-else>
                <!-- MOBILE FORMAT -->
                <v-row>
                  <v-btn
                    class="mt-4"
                    block
                    text
                    color="blue darken-1"
                    @click="submit()"
                    >{{ $ay.t("Save") }}</v-btn
                  >
                  <v-btn
                    class="mt-4"
                    block
                    text
                    color="blue darken-1"
                    @click="newPOItem()"
                    >{{ $ay.t("New") }}</v-btn
                  >
                  <v-btn
                    class="mt-4"
                    block
                    text
                    color="blue darken-1"
                    @click="editPoItemDialog = false"
                    >{{ $ay.t("Close") }}</v-btn
                  >
                  <v-btn
                    class="mt-4"
                    v-if="
                      obj.items[editPoItemIndex].quantityReceived <
                        obj.items[editPoItemIndex].quantityOrdered
                    "
                    color="blue darken-1"
                    block
                    text
                    @click="receive(obj.items[editPoItemIndex])"
                    ><v-icon left> $ayiBoxOpen </v-icon
                    >{{ $ay.t("ReceiveAll") }}</v-btn
                  >
                  <v-btn
                    class="mt-8 mb-6"
                    block
                    text
                    color="red darken-1"
                    @click="deletePoItem(obj.items[editPoItemIndex])"
                    >{{ $ay.t("Delete") }}</v-btn
                  >
                </v-row>
              </template>
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-row>
    </template>

    <!-- ########################## RESTOCK SELECTION DIALOG  ###############################-->
    <template>
      <v-row justify="center">
        <v-dialog v-model="restockSelectDialog">
          <v-card>
            <v-card-title
              >{{ $ay.t("PartRestockRequiredByVendorList") }}
            </v-card-title>
            <v-card-text>
              <v-col cols="12">
                <v-data-table
                  :headers="restockHeaderList"
                  :items="restockItemList"
                  item-key="index"
                  v-model="selectedRestocks"
                  class="elevation-1"
                  disable-pagination
                  disable-filtering
                  :show-select="true"
                  :single-select="false"
                  selectable-key="index"
                  hide-default-footer
                  data-cy="restockTable"
                  dense
                  :no-data-text="$ay.t('NoData')"
                >
                </v-data-table>
              </v-col>
            </v-card-text>
            <v-card-actions>
              <v-btn
                color="blue darken-1"
                text
                @click="restockSelectDialog = false"
                >{{ $ay.t("Close") }}</v-btn
              >
              <v-spacer></v-spacer>
              <v-btn
                color="blue darken-1"
                text
                :disabled="selectedRestocks.length == 0"
                @click="appendSelectedRestocks()"
                >{{ $ay.t("PurchaseOrderUICopyToPurchaseOrder") }}</v-btn
              >
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-row>
    </template>
    <!-- ########################## WORKORDER ITEM PART REQUEST SELECTION DIALOG  ###############################-->

    <template>
      <v-row justify="center">
        <v-dialog v-model="requestSelectDialog">
          <v-card>
            <v-card-title>
              {{ $ay.t("WorkOrderItemPartRequestList") }}
            </v-card-title>
            <v-card-text>
              <v-col cols="12">
                <v-data-table
                  :headers="requestHeaderList"
                  :items="requestItemList"
                  item-key="index"
                  v-model="selectedRequests"
                  class="elevation-1"
                  disable-pagination
                  disable-filtering
                  :show-select="true"
                  :single-select="false"
                  selectable-key="index"
                  hide-default-footer
                  data-cy="requestTable"
                  dense
                  :no-data-text="$ay.t('NoData')"
                >
                </v-data-table>
              </v-col>
            </v-card-text>
            <v-card-actions>
              <v-btn
                color="blue darken-1"
                text
                @click="requestSelectDialog = false"
                >{{ $ay.t("Close") }}</v-btn
              >
              <v-spacer></v-spacer>
              <v-btn
                color="blue darken-1"
                text
                :disabled="selectedRequests.length == 0"
                @click="appendSelectedRequests()"
                >{{ $ay.t("PurchaseOrderUICopyToPurchaseOrder") }}</v-btn
              >
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-row>
    </template>
  </div>
</template>

<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
const FORM_KEY = "inv-purchase-order-edit";
const API_BASE_URL = "purchase-order/";
const FORM_CUSTOM_TEMPLATE_KEY = "PurchaseOrder"; //<-- Should always be CoreBizObject AyaType name here where possible

export default {
  async created() {
    let vm = this;

    try {
      await initForm(vm);

      vm.rights = window.$gz.role.getRights(window.$gz.type.PurchaseOrder);
      vm.formState.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);

      //---------------------------------
      let setDirty = false;
      let setValid = true;
      //id 0 means create or duplicate to new
      if (vm.$route.params.recordid != 0) {
        //is there already an obj from a prior operation?
        if (this.$route.params.obj) {
          //yes, no need to fetch it
          this.obj = this.$route.params.obj;
        } else {
          await vm.getDataFromApi(vm.$route.params.recordid); //let getdata handle loading
        }
      } else {
        //Might be a duplicate and contain another record
        if (this.$route.params.obj) {
          this.obj = this.$route.params.obj;
          this.obj.concurrency = undefined;
          this.obj.id = 0;
          this.obj.serial = 0;

          vm.obj.status = 1; // OpenNotYetOrdered = 1,
          vm.obj.items.forEach(z => {
            z.id = 0;
            z.concurrency = undefined;
            z.quantityReceived = 0;
            z.receivedCost = 0;
            z.receivedDate = null;
            z.purchaseOrderId = 0;
            z.workOrderItemPartRequestId = null;
            z.partRequestedById = null;
          });

          setDirty = true;
        }
      }
      window.$gz.form.setFormState({
        vm: vm,
        loading: false,
        dirty: setDirty,
        valid: setValid
      });
      //----------------------------
      generateMenu(vm);
    } catch (error) {
      window.$gz.errorHandler.handleFormError(error, vm);
    } finally {
      vm.formState.ready = true;
    }
  },
  async beforeRouteLeave(to, from, next) {
    if (!this.formState.dirty || JUST_DELETED) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      editPoItemDialog: false,
      editPoItemIndex: 0,
      restockSelectDialog: false,
      restockItems: [],
      selectedRestocks: [],
      requestSelectDialog: false,
      requestItems: [],
      selectedRequests: [],
      selectLists: {
        status: []
      },
      headers: [],
      obj:
        //IMPORTANT NOTE: Fields that are NON NULLABLE in the schema for the table but *are* hideable **MUST** have a default value set here or else there will be no way to save the record
        //I.E. Serial, usertype fields, ACTIVE
        //Also, if it's a non-nullable Enum backed field then it should have a valid selection i.e. not zero if there is no zero
        {
          id: 0,
          concurrency: 0,
          serial: 0,
          notes: null,
          wiki: null,
          customFields: null,
          tags: [],
          vendorMemo: null,
          dropShipToCustomerId: null,
          referenceNumber: null,
          vendorId: null,
          orderedDate: window.$gz.locale.nowUTC8601String(),
          expectedReceiveDate: null,
          status: 1,
          projectId: null,
          text1: null,
          text2: null,
          items: []
        },

      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject(),
      canEditSerial: window.$gz.role.hasRole([
        window.$gz.role.AUTHORIZATION_ROLES.BizAdmin
      ]),
      ayaType: window.$gz.type.PurchaseOrder,
      currencyName: window.$gz.locale.getCurrencyName(),
      timeZoneName: window.$gz.locale.getResolvedTimeZoneName(),
      languageName: window.$gz.locale.getResolvedLanguage(),
      hour12: window.$gz.locale.getHour12()
    };
  },
  //WATCHERS
  watch: {
    formState: {
      handler: function(val) {
        //,oldval is available here too if necessary
        if (this.formState.loading) {
          return;
        }

        //enable / disable save button
        if (val.dirty && val.valid && !val.readOnly) {
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
        } else {
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
        }

        //enable / disable duplicate / new button
        if (!val.dirty && val.valid && !val.readOnly) {
          window.$gz.eventBus.$emit(
            "menu-enable-item",
            FORM_KEY + ":duplicate"
          );
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":new");
        } else {
          window.$gz.eventBus.$emit(
            "menu-disable-item",
            FORM_KEY + ":duplicate"
          );
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":new");
        }
      },
      deep: true
    }
  },
  computed: {
    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 = [];
      let vm = this;
      headers.push({
        text: vm.$ay.t("Part"),
        align: "left",
        value: "partViz"
      });

      if (vm.form().showMe(vm, "Items.PartName")) {
        headers.push({
          text: vm.$ay.t("PartName"),
          align: "left",
          value: "partNameViz"
        });
      }

      if (vm.obj.hasSelectableWarehouses) {
        headers.push({
          text: vm.$ay.t("PartWarehouse"),
          align: "left",
          value: "warehouseViz"
        });
      }

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

      headers.push({
        text: vm.$ay.t("PurchaseOrderItemQuantityOrdered"),
        align: "right",
        value: "quantityOrdered"
      });

      if (vm.obj.hasReceipt) {
        headers.push({
          text: vm.$ay.t("PurchaseOrderItemQuantityReceived"),
          align: "right",
          value: "quantityReceived"
        });
        if (vm.form().showMe(vm, "Items.ReceivedDate")) {
          headers.push({
            text: vm.$ay.t("PurchaseOrderReceiptReceivedDate"),
            align: "right",
            value: "receivedDate"
          });
        }
      }

      headers.push({
        text: vm.$ay.t("PurchaseOrderItemPurchaseOrderCost"),
        align: "right",
        value: "purchaseOrderCost"
      });

      if (vm.obj.hasReceipt) {
        headers.push({
          text: vm.$ay.t("PurchaseOrderReceiptItemReceiptCost"),
          align: "right",
          value: "receivedCost"
        });
      }

      if (vm.obj.hasTaxes && vm.form().showMe(vm, "Items.PurchaseTaxCodeId")) {
        headers.push({
          text: vm.$ay.t("TaxCode"),
          align: "left",
          value: "purchaseTaxCodeViz"
        });
      }

      headers.push({
        text: vm.$ay.t("PurchaseOrderItemNetTotal"),
        align: "right",
        value: "netTotalViz"
      });

      if (vm.obj.hasTaxes && vm.form().showMe(vm, "Items.PurchaseTaxCodeId")) {
        headers.push({
          text: vm.$ay.t("TaxCodeTaxA"),
          align: "right",
          value: "taxAViz"
        });

        headers.push({
          text: vm.$ay.t("TaxCodeTaxB"),
          align: "right",
          value: "taxBViz"
        });
      }

      headers.push({
        text: vm.$ay.t("PurchaseOrderItemLineTotal"),
        align: "right",
        value: "lineTotalViz"
      });

      if (
        vm.obj.hasVendorNumber &&
        vm.form().showMe(vm, "Items.VendorPartNumber")
      ) {
        headers.push({
          text: vm.$ay.t("PurchaseOrderItemVendorPartNumber"),
          align: "left",
          value: "vendorPartNumber"
        });
      }

      if (vm.obj.hasPartRequest) {
        if (vm.form().showMe(vm, "Items.PartRequestedById")) {
          headers.push({
            text: vm.$ay.t("PurchaseOrderItemPartRequestedByID"),
            align: "left",
            value: "partRequestedByViz"
          });
        }
        if (vm.form().showMe(vm, "Items.WorkOrderItemPartRequestId")) {
          headers.push({
            text: vm.$ay.t("PurchaseOrderItemWorkOrderNumber"),
            align: "left",
            value: "workOrderItemPartRequestViz"
          });
        }
      }

      if (!vm.formState.readOnly) {
        headers.push({ text: "", value: "actions" });
      }
      return headers;
    },
    itemList: function() {
      let vm = this;
      return vm.obj.items.map((x, i) => {
        return {
          index: i,
          id: x.id,
          quantityOrdered: window.$gz.locale.decimalLocalized(
            x.quantityOrdered,
            vm.languageName
          ),
          quantityReceived: window.$gz.locale.decimalLocalized(
            x.quantityReceived,
            vm.languageName
          ),
          purchaseOrderCost: window.$gz.locale.currencyLocalized(
            x.purchaseOrderCost,
            vm.languageName,
            vm.currencyName
          ),
          receivedCost: window.$gz.locale.currencyLocalized(
            x.receivedCost,
            vm.languageName,
            vm.currencyName
          ),
          receivedDate: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
            x.receivedDate,
            vm.timeZoneName,
            vm.languageName,
            vm.hour12
          ),
          vendorPartNumber: x.vendorPartNumber,
          partViz: x.partViz,
          partNameViz: x.partNameViz,
          warehouseViz: x.warehouseViz,
          partUnitOfMeasureViz: x.partUnitOfMeasureViz,
          partRequestedByViz: x.partRequestedByViz,
          workOrderItemPartRequestViz: x.workOrderItemPartRequestViz,
          workOrderItemPartRequestId: x.workOrderItemPartRequestId,
          purchaseTaxCodeViz: x.purchaseTaxCodeViz,
          netTotalViz: window.$gz.locale.currencyLocalized(
            x.netTotalViz,
            vm.languageName,
            vm.currencyName
          ),
          taxAViz: window.$gz.locale.currencyLocalized(
            x.taxAViz,
            vm.languageName,
            vm.currencyName
          ),
          taxBViz: window.$gz.locale.currencyLocalized(
            x.taxBViz,
            vm.languageName,
            vm.currencyName
          ),
          lineTotalViz: window.$gz.locale.currencyLocalized(
            x.lineTotalViz,
            vm.languageName,
            vm.currencyName
          )
        };
      });
    },
    restockHeaderList: function() {
      let headers = [];
      let vm = this;
      headers.push({
        text: vm.$ay.t("Part"),
        align: "left",
        value: "partNumber"
      });

      if (vm.obj.hasSelectableWarehouses) {
        headers.push({
          text: vm.$ay.t("PartWarehouse"),
          align: "left",
          value: "warehouseViz"
        });
      }

      headers.push({
        text: vm.$ay.t("PartByWarehouseInventoryMinStockLevel"),
        align: "right",
        value: "minimumQuantity"
      });

      headers.push({
        text: vm.$ay.t("PartInventoryBalance"),
        align: "right",
        value: "balance"
      });

      headers.push({
        text: vm.$ay.t("PartByWarehouseInventoryQuantityOnOrder"),
        align: "right",
        value: "onOrderQuantity"
      });

      headers.push({
        text: vm.$ay.t("PartByWarehouseInventoryReorderQuantity"),
        align: "right",
        value: "requiredQuantity"
      });

      return headers;
    },
    restockItemList: function() {
      /**
       *
       * {"data":[{"partId":2,"partWarehouseId":1,"partNumber":"249986","warehouseViz":"Default","manufacturerId":2,
       * "displayManufacturer":"Ryan - Legros","wholesalerId":6,"displayWholesaler":"Emmerich and Sons","alternativeWholesalerId":9,
       * "displayAlternativeWholesaler":"O'Connell - MacGyver","minimumQuantity":6.0000,"balance":4.0000,"onOrderQuantity":0.0,"requiredQuantity":2.0000}]}
       */
      let vm = this;
      return vm.restockItems.map((x, i) => {
        return {
          index: i,
          partId: x.partId,
          partWarehouseId: x.partWarehouseId,
          partNumber: x.partNumber,
          warehouseViz: x.warehouseViz,

          minimumQuantity: window.$gz.locale.decimalLocalized(
            x.minimumQuantity,
            vm.languageName
          ),
          balance: window.$gz.locale.decimalLocalized(
            x.balance,
            vm.languageName
          ),
          onOrderQuantity: window.$gz.locale.decimalLocalized(
            x.onOrderQuantity,
            vm.languageName
          ),
          requiredQuantity: window.$gz.locale.decimalLocalized(
            x.requiredQuantity,
            vm.languageName
          )
        };
      });
    },
    requestHeaderList: function() {
      let headers = [];
      let vm = this;
      headers.push({
        text: vm.$ay.t("Part"),
        align: "left",
        value: "partNumber"
      });

      if (vm.obj.hasSelectableWarehouses) {
        headers.push({
          text: vm.$ay.t("PartWarehouse"),
          align: "left",
          value: "partWarehouseName"
        });
      }

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

      headers.push({
        text: vm.$ay.t("WorkOrder"),
        align: "right",
        value: "serial"
      });

      headers.push({
        text: vm.$ay.t("PurchaseOrderItemPartRequestedByID"),
        align: "left",
        value: "requestedByUserName"
      });

      headers.push({
        text: vm.$ay.t("PartWholesalerID"),
        align: "left",
        value: "wholesalerName"
      });

      headers.push({
        text: vm.$ay.t("PartAlternativeWholesalerID"),
        align: "left",
        value: "altWholesalerName"
      });

      return headers;
    },
    requestItemList: function() {
      /**
      {
	"0": {
		"requestId": 2,
		"partId": 7,
		"partWarehouseId": 1,
		"quantity": 498,
		"serial": 74,
		"partNumber": "CAB1064",
		"partName": "KYBD EXT-DIN5M DIN5F 6FT",
		"partWarehouseName": "Default",
		"wholesalerId": 19,
		"wholesalerName": "Merisale",
		"altWholesalerId": 13,
		"altWholesalerName": "Ingrim"
	}
}
       */
      let vm = this;
      return vm.requestItems.map((x, i) => {
        return {
          index: i,
          requestId: x.requestId,
          requestedByUserId: x.requestedByUserId,
          requestedByUserViz: x.requestedByUserName,
          partId: x.partId,
          partWarehouseId: x.partWarehouseId,
          partNumber: x.partNumber,
          partWarehouseName: x.partWarehouseName,
          serial: x.serial,
          wholesalerName: x.wholesalerName,
          altWholesalerName: x.altWholesalerName,
          quantity: window.$gz.locale.decimalLocalized(
            x.quantity,
            vm.languageName
          )
        };
      });
    }
  },
  methods: {
    openWOItemPartRequest(item) {
      let requestId = 0;
      if (item) {
        requestId = item.workOrderItemPartRequestId;
      } else {
        requestId = this.obj.items[this.editPoItemIndex]
          .workOrderItemPartRequestId;
      }
      window.$gz.eventBus.$emit("openobject", {
        type: window.$gz.type.WorkOrderItemPartRequest,
        id: requestId
      });
    },
    appendSelectedRestocks() {
      let itemAdded = false;
      this.selectedRestocks.forEach(z => {
        this.obj.items.push({
          id: 0,
          purchaseOrderId: 0,
          partId: z.partId,
          partWarehouseId: z.partWarehouseId,
          quantityOrdered: z.requiredQuantity,
          quantityReceived: 0,
          purchaseOrderCost: 0,
          receivedCost: 0.0,
          receivedDate: null,
          partRequestedById: null,
          workOrderItemPartRequestId: null,
          purchaseTaxCodeId:
            window.$gz.store.state.globalSettings.defaultTaxPartPurchaseId,
          vendorPartNumber: null
        });

        if (!this.itemAdded) {
          this.formState.dirty = true;
          itemAdded = true;
        }
      });
      this.restockSelectDialog = false;
      if (itemAdded) {
        this.selectedRestocks = [];
        this.submit();
      }
    },

    async showRestockSelectDialog() {
      let vm = this;

      let url = API_BASE_URL + "restock-by-vendor/" + vm.obj.vendorId;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.get(url);

        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          //process add url dl token and id
          if (res.data) {
            vm.restockItems = res.data;
          } else {
            vm.restockItems = [];
          }
          vm.restockSelectDialog = true;
        }
      } catch (error) {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    async showRequestSelectDialog() {
      let vm = this;

      let url = API_BASE_URL + "requests-by-vendor/" + vm.obj.vendorId;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.get(url);

        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          //process add url dl token and id
          if (res.data) {
            vm.requestItems = res.data;
          } else {
            vm.requestItems = [];
          }
          vm.requestSelectDialog = true;
        }
      } catch (error) {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    appendSelectedRequests() {
      let itemAdded = false;
      this.selectedRequests.forEach(z => {
        this.obj.items.push({
          id: 0,
          purchaseOrderId: 0,
          partId: z.partId,
          partWarehouseId: z.partWarehouseId,
          quantityOrdered: z.quantity,
          quantityReceived: 0,
          purchaseOrderCost: 0,
          receivedCost: 0.0,
          receivedDate: null,
          partRequestedById: z.requestedByUserId,
          partRequestedByViz: z.requestedByUserName,
          workOrderItemPartRequestId: z.requestId,
          workOrderItemPartRequestViz: z.serial,
          purchaseTaxCodeId:
            window.$gz.store.state.globalSettings.defaultTaxPartPurchaseId,
          vendorPartNumber: null
        });

        if (!this.itemAdded) {
          this.formState.dirty = true;
          itemAdded = true;
        }
      });
      this.requestSelectDialog = false;
      if (itemAdded) {
        this.selectedRequests = [];
        this.submit();
      }
    },
    poItemsRowClasses: function(item) {
      const path = `Items[${item.index}].`;
      if (this.form().childRowHasError(this, path)) {
        return "font-weight-black font-italic error--text";
      }
    },
    receive: function(item) {
      receiveItem(item, this);
      this.editPoItemDialog = false;
    },
    receiveAll: function() {
      let vm = this;
      this.obj.items.forEach(item => receiveItem(item, vm));
      //set status to all received fwiw
      this.obj.status = 5;
    },
    editItem: function(item) {
      this.editPoItemIndex = item.index;
      this.editPoItemDialog = true;
    },
    newPOItem: function() {
      this.obj.items.push({
        id: 0,
        purchaseOrderId: 0,
        partId: null,
        partWarehouseId: 1,
        quantityOrdered: 1,
        quantityReceived: 0,
        purchaseOrderCost: 0,
        receivedCost: 0.0,
        receivedDate: null,
        partRequestedById: null,
        workOrderItemPartRequestId: null,
        purchaseTaxCodeId:
          window.$gz.store.state.globalSettings.defaultTaxPartPurchaseId,
        vendorPartNumber: null
      });

      this.editPoItemIndex = this.obj.items.length - 1;
      this.editPoItemDialog = true;
      this.formState.dirty = true;
    },
    deletePoItem: function(item) {
      this.editPoItemDialog = false;
      this.obj.items.splice(this.editPoItemIndex, 1);
      this.editPoItemIndex = 0;
      this.formState.dirty = true;
    },
    updatePartCostIcon(item) {
      if (item.receivedCost && item.purchaseOrderCost != item.receivedCost) {
        return "$ayiMagic";
      }
      return null;
    },
    async updatePartCost(item) {
      let vm = this;
      let dialogResult = await window.$gz.dialog.confirmGeneric(
        "ConfirmUpdatePartCost"
      );
      if (dialogResult == false) {
        return;
      }
      //send request
      let res = await window.$gz.api.put(
        `part/part-cost/${item.partId}`,
        item.receivedCost
      );
      if (res.error) {
        vm.formState.serverError = res.error;
        window.$gz.form.setErrorBoxErrors(vm);
      } else {
        window.$gz.eventBus.$emit("notify-success", vm.$ay.t("JobCompleted"));
      }
    },
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    },
    canDuplicate: function() {
      return this.formState.valid && !this.formState.dirty;
    },
    ayaTypes: function() {
      return window.$gz.type;
    },
    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (
        this.formState.ready &&
        !this.formState.loading &&
        !this.formState.readOnly
      ) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    async getDataFromApi(recordId) {
      let vm = this;
      window.$gz.form.setFormState({
        vm: vm,
        loading: true
      });
      if (!recordId) {
        throw new Error(FORM_KEY + "::getDataFromApi -> Missing recordID!");
      }
      let url = API_BASE_URL + recordId;
      try {
        window.$gz.form.deleteAllErrorBoxErrors(vm);

        let res = await window.$gz.api.get(url);

        if (res.error) {
          //Not found?
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj = res.data;
          //modify the menu as necessary
          generateMenu(vm);

          //Update the form status
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    },
    async submit() {
      let vm = this;
      if (vm.canSave == false) {
        return;
      }

      try {
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });
        let url = API_BASE_URL; // + vm.$route.params.recordid;
        //clear any errors vm might be around from previous submit
        window.$gz.form.deleteAllErrorBoxErrors(vm);

        let res = await window.$gz.api.upsert(url, vm.obj);

        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          //POST or PUT - whole new object returned which is a little different than other objects
          //so if it's new then need to navigate to it to update url with id
          if (vm.$route.params.recordid != 0) {
            //update of existing record
            vm.obj = res.data;
          } else {
            this.$router.replace({
              name: "inv-purchase-order",
              params: {
                recordid: res.data.id,
                obj: res.data // Pass data object to new form will prevent fetch
              }
            });
          }

          //Update the form status
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true
          });
        }
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    },
    async remove() {
      let vm = this;
      try {
        let dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }

        //do the delete
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });
        //No need to delete a new record, just abandon it...
        if (vm.$route.params.recordid == 0) {
          //this should not get offered for delete but to be safe and clear just in case:
          JUST_DELETED = true;
          // navigate backwards
          vm.$router.go(-1);
        } else {
          let url = API_BASE_URL + vm.$route.params.recordid;

          window.$gz.form.deleteAllErrorBoxErrors(vm);
          let res = await window.$gz.api.remove(url);
          if (res.error) {
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          } else {
            //workaround to prevent warning about leaving dirty record
            //For some reason I couldn't just reset isdirty in formstate
            JUST_DELETED = true;
            // navigate backwards
            vm.$router.go(-1);
          }
        }
      } catch (error) {
        //Update the form status
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },
    duplicate() {
      //Navigate to new record
      this.$router.push({
        name: "inv-purchase-order",
        params: {
          recordid: 0,
          obj: this.obj
        }
      });
    }
  }
};

/////////////////////////////
// RECEIVE
//
function receiveItem(item, vm) {
  if (item.quantityReceived < item.quantityOrdered) {
    item.quantityReceived = item.quantityOrdered;
    item.receivedDate = window.$gz.locale.nowUTC8601String();
    vm.obj.hasReceipt = true;
    vm.formState.dirty = true;
  }
}

/////////////////////////////
//
//
async function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "save":
        m.vm.submit();
        break;
      case "delete":
        m.vm.remove();
        break;
      case "new":
        m.vm.$router.push({
          name: "project-edit",
          params: { recordid: 0 }
        });
        break;
      case "duplicate":
        m.vm.duplicate();
        break;
      case "report":
        let res = await m.vm.$refs.reportSelector.open(
          {
            AType: window.$gz.type.PurchaseOrder,
            selectedRowIds: [m.vm.obj.id]
          },
          m.id
        );
        if (res == null) {
          return;
        }
        window.$gz.form.setLastReport(FORM_KEY, res);
        generateMenu(m.vm);
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: false,
    readOnly: vm.formState.readOnly,
    icon: "$ayiTruckLoading",
    title: "PurchaseOrder",
    helpUrl: "inv-purchase-orders",
    formData: {
      ayaType: window.$gz.type.PurchaseOrder,
      recordId: vm.$route.params.recordid,
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      recordName: vm.obj.serial == 0 ? null : vm.obj.serial.toString()
    },
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "Save",
      icon: "$ayiSave",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });
  }

  if (vm.rights.delete && vm.$route.params.recordid != 0) {
    menuOptions.menuItems.push({
      title: "Delete",
      icon: "$ayiTrashAlt",
      surface: false,
      key: FORM_KEY + ":delete",
      vm: vm
    });
  }

  //REPORTS
  //Report not Print, print is a further option
  menuOptions.menuItems.push({
    title: "Report",
    icon: "$ayiFileAlt",
    key: FORM_KEY + ":report",
    vm: vm
  });

  //get last report selected
  let lastReport = window.$gz.form.getLastReport(FORM_KEY);
  if (lastReport != null) {
    menuOptions.menuItems.push({
      title: lastReport.name,
      notrans: true,
      icon: "$ayiFileAlt",
      key: FORM_KEY + ":report:" + lastReport.id,
      vm: vm
    });
  }

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "New",
      icon: "$ayiPlus",
      key: FORM_KEY + ":new",
      vm: vm
    });
  }

  if (vm.rights.change && vm.$route.params.recordid != 0) {
    menuOptions.menuItems.push({
      title: "Duplicate",
      icon: "$ayiClone",
      key: FORM_KEY + ":duplicate",
      vm: vm
    });
  }

  menuOptions.menuItems.push({ divider: true, inset: false });

  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

let JUST_DELETED = false;

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText(vm);
  await window.$gz.formCustomTemplate.get(FORM_CUSTOM_TEMPLATE_KEY, vm);
  await populateSelectionLists(vm);
}

//////////////////////
//
//
async function populateSelectionLists(vm) {
  //ensure the pick lists required are pre-fetched
  await window.$gz.enums.fetchEnumList("purchaseorderstatus");
  vm.selectLists.status = window.$gz.enums.getSelectionList(
    "purchaseorderstatus"
  );
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText(vm) {
  await window.$gz.translation.cacheTranslations([
    "PurchaseOrder",
    "PurchaseOrderPONumber",
    "PurchaseOrderNotes",
    "PurchaseOrderVendorMemo",
    "PurchaseOrderDropShipToCustomerID",
    "PurchaseOrderReferenceNumber",
    "Vendor",
    "PurchaseOrderOrderedDate",
    "PurchaseOrderExpectedReceiveDate",
    "PurchaseOrderStatus",
    "Project",
    "PurchaseOrderReceiptText1",
    "PurchaseOrderReceiptText2",
    "PurchaseOrderReceiptItemPurchaseOrderItemID",
    "PurchaseOrderItemList",
    "PurchaseOrderItemQuantityOrdered",
    "PurchaseOrderItemQuantityReceived",
    "Part",
    "PartName",
    "PartWarehouse",
    "TaxCode",
    "PurchaseOrderItemVendorPartNumber",
    "PurchaseOrderItemPartRequestedByID",
    "PurchaseOrderItemWorkOrderNumber",
    "PurchaseOrderItemPurchaseOrderCost",
    "PurchaseOrderItemNetTotal",
    "PurchaseOrderItemLineTotal",
    "TaxCodeTaxA",
    "TaxCodeTaxB",
    "PurchaseOrderReceiptReceivedDate",
    "PurchaseOrderReceiptItemReceiptCost",
    "PurchaseOrderReceiptItemQuantityReceivedErrorInvalid",
    "PurchaseOrderItemSerialNumbers",
    "ReceiveAll",
    "JobCompleted",
    "ConfirmUpdatePartCost",
    "PurchaseOrderUIRestockList",
    "PartByWarehouseInventoryMinStockLevel",
    "PartInventoryBalance",
    "PartByWarehouseInventoryQuantityOnOrder",
    "PartByWarehouseInventoryReorderQuantity",
    "WorkOrderItemPartRequestList",
    "WorkOrderItemPartRequest",
    "WorkOrderItemPartRequestQuantity",
    "WorkOrder",
    "PartWholesalerID",
    "PartAlternativeWholesalerID",
    "PurchaseOrderUICopyToPurchaseOrder",
    "PartRestockRequiredByVendorList",
    "PurchaseOrderCustom1",
    "PurchaseOrderCustom2",
    "PurchaseOrderCustom3",
    "PurchaseOrderCustom4",
    "PurchaseOrderCustom5",
    "PurchaseOrderCustom6",
    "PurchaseOrderCustom7",
    "PurchaseOrderCustom8",
    "PurchaseOrderCustom9",
    "PurchaseOrderCustom10",
    "PurchaseOrderCustom11",
    "PurchaseOrderCustom12",
    "PurchaseOrderCustom13",
    "PurchaseOrderCustom14",
    "PurchaseOrderCustom15",
    "PurchaseOrderCustom16"
  ]);
}
/* {
        data: {
          id: 4,
          concurrency: 7343586,
          serial: 4,
          notes: "Eius tenetur magnam nostrum qui doloribus velit.",
          wiki: null,
          customFields: null,
          tags: ["black", "green", "zebra", "zone0"],
          vendorMemo: "Et quis eaque repellat.",
          dropShipToCustomerId: null,
          referenceNumber: "578929",
          vendorId: 2,
          orderedDate: "2020-05-03T07:57:42.014786Z",
          expectedReceiveDate: "2020-05-08T07:57:42.014786Z",
          status: 2,
          projectId: null,
          text1: "Natus pariatur.",
          text2: "Provident repudiandae nobis et.",
          items: [
            {
              id: 15,
              concurrency: 7343586,
              purchaseOrderId: 4,
              partId: 13,
              partWarehouseId: 2,
              quantityOrdered: 65.0,
              quantityReceived: 0.0,
              purchaseOrderCost: 15.6812,
              receivedCost: 0.0,
              receivedDate: null,
              partRequestedById: null,
              workOrderItemPartRequestId: null,
              purchaseTaxCodeId: 3,
              vendorPartNumber: "man-695831",
              partViz: "695831",
              warehouseViz: "WHS- Lera Brook",
              partRequestedByViz: null,
              workOrderItemPartRequestViz: null,
              purchaseTaxCodeViz: "Sales & Goods",
              netTotalViz: 1019.278,
              TaxAViz: 71.34946,
              TaxBViz: 71.34946,
              lineTotalViz: 1161.97692
            }
          ],
          hasSelectableWarehouses: true,
          hasPartRequest: false,
          hasTaxes: true,
          hasReceipt: false,
          hasVendorNumber: true,
          hasUnreceived: true
        }
      };
      
      
      
      //RESTOCK REQUIRED
  if (
    useInventory &&
    window.$gz.role.canOpen(window.$gz.type.WorkOrderItemPartRequest)
  ) {
    sub.push({
      title: "PurchaseOrderUIRestockList",
      icon: "$ayiClipboardList",
      route: "/inv-part-restocks",
      key: key++
    });
  }

  //PART REQUESTS
  if (
    useInventory &&
    window.$gz.role.canOpen(window.$gz.type.WorkOrderItemPartRequest)
  ) {
    sub.push({
      title: "WorkOrderItemPartRequestList",
      icon: "$ayiParachuteBox",
      route: "/inv-part-requests",
      key: key++
    });
  }

      */
</script>
