<template>
  <div>
    <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 dense>
          <v-col
            v-if="obj.serial != 0 && canEditSerial"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <v-text-field
              ref="serial"
              v-model="obj.serial"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderPONumber')"
              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
              ref="vendorId"
              v-model="obj.vendorId"
              :aya-type="ayaTypes().Vendor"
              show-edit-icon
              :allow-no-selection="false"
              :readonly="formState.readOnly"
              :label="$ay.t('Vendor')"
              data-cy="vendorId"
              :error-messages="form().serverErrors(this, 'vendorId')"
              :rules="[form().required(this, 'vendorId')]"
              @input="fieldValueChanged('vendorId')"
            ></gz-pick-list>
          </v-col>
          <v-col
            v-if="form().showMe(this, 'Status')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <v-select
              ref="status"
              v-model="obj.status"
              dense
              :items="selectLists.status"
              item-text="name"
              item-value="id"
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderStatus')"
              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
              ref="orderedDate"
              v-model="obj.orderedDate"
              :label="$ay.t('PurchaseOrderOrderedDate')"
              :readonly="formState.readOnly"
              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
              ref="expectedReceiveDate"
              v-model="obj.expectedReceiveDate"
              :label="$ay.t('PurchaseOrderExpectedReceiveDate')"
              :readonly="formState.readOnly"
              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
              ref="referenceNumber"
              v-model="obj.referenceNumber"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderReferenceNumber')"
              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
              ref="projectId"
              v-model="obj.projectId"
              :aya-type="ayaTypes().Project"
              show-edit-icon
              :readonly="formState.readOnly"
              :label="$ay.t('Project')"
              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
              ref="vendorMemo"
              v-model="obj.vendorMemo"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderVendorMemo')"
              :error-messages="form().serverErrors(this, 'vendorMemo')"
              data-cy="vendorMemo"
              auto-grow
              @input="fieldValueChanged('vendorMemo')"
            ></v-textarea>
          </v-col>

          <v-col
            v-if="form().showMe(this, 'Text1')"
            cols="12"
            sm="6"
            lg="4"
            xl="3"
          >
            <v-text-field
              ref="text1"
              v-model="obj.text1"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderReceiptText1')"
              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
              ref="text2"
              v-model="obj.text2"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderReceiptText2')"
              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
              ref="dropShipToCustomerId"
              v-model="obj.dropShipToCustomerId"
              :aya-type="ayaTypes().Customer"
              show-edit-icon
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderDropShipToCustomerID')"
              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
              ref="notes"
              v-model="obj.notes"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('PurchaseOrderNotes')"
              :error-messages="form().serverErrors(this, 'notes')"
              data-cy="notes"
              auto-grow
              @input="fieldValueChanged('notes')"
            ></v-textarea>
          </v-col>

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

          <v-col cols="12" class="mb-6">
            <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 v-if="rights.change" offset-y>
                    <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
                        :disabled="!obj.hasUnreceived"
                        @click="receiveAll"
                      >
                        <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 v-else class="text-h6">
                    {{ $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
              ref="tags"
              v-model="obj.tags"
              :readonly="formState.readOnly"
              data-cy="tags"
              :error-messages="form().serverErrors(this, 'tags')"
              @input="fieldValueChanged('tags')"
            ></gz-tag-picker>
          </v-col>

          <v-col cols="12">
            <gz-custom-fields
              ref="customFields"
              v-model="obj.customFields"
              :form-key="formCustomTemplateKey"
              :readonly="formState.readOnly"
              :parent-v-m="this"
              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
              ref="wiki"
              v-model="obj.wiki"
              :aya-type="ayaType"
              :aya-id="obj.id"
              :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 dense 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 dense>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-pick-list
                    ref="Items.PartId"
                    v-model="obj.items[editPoItemIndex].partId"
                    :aya-type="ayaTypes().Part"
                    :allow-no-selection="false"
                    show-edit-icon
                    :readonly="formState.readOnly"
                    :label="$ay.t('Part')"
                    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"
                    ref="Items.PartWarehouseId"
                    v-model="obj.items[editPoItemIndex].partWarehouseId"
                    :aya-type="ayaTypes().PartWarehouse"
                    :allow-no-selection="false"
                    show-edit-icon
                    :readonly="formState.readOnly"
                    :label="$ay.t('PartWarehouse')"
                    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
                    ref="Items.QuantityOrdered"
                    v-model="obj.items[editPoItemIndex].quantityOrdered"
                    :readonly="
                      formState.readOnly ||
                        obj.items[editPoItemIndex].workOrderItemPartRequestId !=
                          null
                    "
                    :label="$ay.t('PurchaseOrderItemQuantityOrdered')"
                    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
                    ref="Items.QuantityReceived"
                    v-model="obj.items[editPoItemIndex].quantityReceived"
                    :readonly="formState.readOnly"
                    :label="$ay.t('PurchaseOrderItemQuantityReceived')"
                    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
                    ref="Items.ReceivedDate"
                    v-model="obj.items[editPoItemIndex].receivedDate"
                    :label="$ay.t('PurchaseOrderReceiptReceivedDate')"
                    :readonly="formState.readOnly"
                    :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
                    ref="Items.PurchaseOrderCost"
                    v-model="obj.items[editPoItemIndex].purchaseOrderCost"
                    :readonly="formState.readOnly"
                    :label="$ay.t('PurchaseOrderItemPurchaseOrderCost')"
                    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
                    ref="Items.ReceivedCost"
                    v-model="obj.items[editPoItemIndex].receivedCost"
                    :readonly="formState.readOnly"
                    :label="$ay.t('PurchaseOrderReceiptItemReceiptCost')"
                    :append-outer-icon="
                      updatePartCostIcon(obj.items[editPoItemIndex])
                    "
                    data-cy="Items.ReceivedCost"
                    :rules="[
                      form().decimalValid(this, 'Items.ReceivedCost'),
                      form().required(this, 'Items.ReceivedCost')
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `Items[${editPoItemIndex}].ReceivedCost`
                      )
                    "
                    @gz-append-outer="
                      updatePartCost(obj.items[editPoItemIndex])
                    "
                    @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')"
                    ref="Items.PurchaseTaxCodeId"
                    v-model="obj.items[editPoItemIndex].purchaseTaxCodeId"
                    :aya-type="ayaTypes().TaxCode"
                    show-edit-icon
                    :readonly="formState.readOnly"
                    :label="$ay.t('TaxCode')"
                    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
                    ref="Items.VendorPartNumber"
                    v-model="obj.items[editPoItemIndex].vendorPartNumber"
                    dense
                    :readonly="formState.readOnly"
                    :clearable="!formState.readOnly"
                    :label="$ay.t('PurchaseOrderItemVendorPartNumber')"
                    data-cy="Items.VendorPartNumber"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `Items[${editPoItemIndex}].VendorPartNumber`
                      )
                    "
                    @click:clear="fieldValueChanged('Items.VendorPartNumber')"
                    @input="
                      fieldValueChanged(
                        `Items[${editPoItemIndex}].VendorPartNumber`
                      )
                    "
                  ></v-text-field>
                </v-col>

                <v-col v-if="form().showMe(this, 'Items.Serials')" cols="12">
                  <v-textarea
                    ref="Items.Serials"
                    v-model="obj.items[editPoItemIndex].serials"
                    dense
                    outlined
                    :readonly="formState.readOnly"
                    :label="$ay.t('PurchaseOrderItemSerialNumbers')"
                    :rows="$vuetify.breakpoint.xs ? 3 : 5"
                    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
                  class="ml-4"
                  @click="newPOItem()"
                  >{{ $ay.t("New") }}</v-btn
                >
                <v-btn
                  v-if="
                    obj.items[editPoItemIndex].quantityReceived <
                      obj.items[editPoItemIndex].quantityOrdered
                  "
                  color="blue darken-1"
                  text
                  class="ml-4"
                  @click="receive(obj.items[editPoItemIndex])"
                  ><v-icon left> $ayiBoxOpen </v-icon
                  >{{ $ay.t("ReceiveAll") }}</v-btn
                >
                <v-btn
                  color="blue darken-1"
                  text
                  class="ml-4"
                  @click="submit()"
                  >{{ $ay.t("Save") }}</v-btn
                >
              </template>
              <template v-else>
                <!-- MOBILE FORMAT -->
                <v-row dense>
                  <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
                    v-if="
                      obj.items[editPoItemIndex].quantityReceived <
                        obj.items[editPoItemIndex].quantityOrdered
                    "
                    class="mt-4"
                    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 densejustify="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
                  v-model="selectedRestocks"
                  :headers="restockHeaderList"
                  :items="restockItemList"
                  item-key="index"
                  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 dense 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
                  v-model="selectedRequests"
                  :headers="requestHeaderList"
                  :items="requestItemList"
                  item-key="index"
                  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>
const FORM_KEY = "inv-purchase-order-edit";
const API_BASE_URL = "purchase-order/";
const FORM_CUSTOM_TEMPLATE_KEY = "PurchaseOrder";
export default {
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      editPoItemDialog: false,
      editPoItemIndex: 0,
      restockSelectDialog: false,
      restockItems: [],
      selectedRestocks: [],
      requestSelectDialog: false,
      requestItems: [],
      selectedRequests: [],
      selectLists: {
        status: []
      },
      headers: [],
      obj: {
        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()
    };
  },
  computed: {
    headerList: function() {
      const headers = [];
      headers.push({
        text: this.$ay.t("Part"),
        align: "left",
        value: "partNameViz"
      });

      if (this.form().showMe(this, "Items.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.obj.hasSelectableWarehouses) {
        headers.push({
          text: this.$ay.t("PartWarehouse"),
          align: "left",
          value: "warehouseViz"
        });
      }

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

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

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

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

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

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

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

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

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

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

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

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

      if (!this.formState.readOnly) {
        headers.push({ text: "", value: "actions" });
      }
      return headers;
    },
    itemList: function() {
      return this.obj.items.map((x, i) => {
        return {
          index: i,
          id: x.id,
          quantityOrdered: window.$gz.locale.decimalLocalized(
            x.quantityOrdered,
            this.languageName
          ),
          quantityReceived: window.$gz.locale.decimalLocalized(
            x.quantityReceived,
            this.languageName
          ),
          purchaseOrderCost: window.$gz.locale.currencyLocalized(
            x.purchaseOrderCost,
            this.languageName,
            this.currencyName
          ),
          receivedCost: window.$gz.locale.currencyLocalized(
            x.receivedCost,
            this.languageName,
            this.currencyName
          ),
          receivedDate: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
            x.receivedDate,
            this.timeZoneName,
            this.languageName,
            this.hour12
          ),
          vendorPartNumber: x.vendorPartNumber,
          partDescriptionViz: x.partDescriptionViz,
          partNameViz: x.partNameViz,
          upcViz: x.upcViz,
          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,
            this.languageName,
            this.currencyName
          ),
          taxAViz: window.$gz.locale.currencyLocalized(
            x.taxAViz,
            this.languageName,
            this.currencyName
          ),
          taxBViz: window.$gz.locale.currencyLocalized(
            x.taxBViz,
            this.languageName,
            this.currencyName
          ),
          lineTotalViz: window.$gz.locale.currencyLocalized(
            x.lineTotalViz,
            this.languageName,
            this.currencyName
          )
        };
      });
    },
    restockHeaderList: function() {
      const headers = [];
      headers.push({
        text: this.$ay.t("Part"),
        align: "left",
        value: "partName"
      });

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

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

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

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

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

      return headers;
    },
    restockItemList: function() {
      return this.restockItems.map((x, i) => {
        return {
          index: i,
          partId: x.partId,
          partWarehouseId: x.partWarehouseId,
          partName: x.partName,
          warehouseViz: x.warehouseViz,

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

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

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

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

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

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

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

      return headers;
    },
    requestItemList: function() {
      return this.requestItems.map((x, i) => {
        return {
          index: i,
          requestId: x.requestId,
          requestedByUserId: x.requestedByUserId,
          requestedByUserViz: x.requestedByUserName,
          partId: x.partId,
          partWarehouseId: x.partWarehouseId,
          partName: x.partName,
          partWarehouseName: x.partWarehouseName,
          serial: x.serial,
          wholesalerName: x.wholesalerName,
          altWholesalerName: x.altWholesalerName,
          quantity: window.$gz.locale.decimalLocalized(
            x.quantity,
            this.languageName
          )
        };
      });
    }
  },
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }
        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");
        }
        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
    }
  },
  async created() {
    const 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;
      //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);
        }
      } 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: true
      });
      //----------------------------
      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);
  },
  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() {
      const vm = this;
      const url = API_BASE_URL + "restock-by-vendor/" + vm.obj.vendorId;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const 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() {
      const vm = this;
      const url = API_BASE_URL + "requests-by-vendor/" + vm.obj.vendorId;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const 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() {
      const 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() {
      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) {
      const vm = this;
      const dialogResult = await window.$gz.dialog.confirmGeneric(
        "ConfirmUpdatePartCost"
      );
      if (dialogResult == false) {
        return;
      }
      //send request
      const 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) {
      const vm = this;
      window.$gz.form.setFormState({
        vm: vm,
        loading: true
      });
      if (!recordId) {
        throw new Error(FORM_KEY + "::getDataFromApi -> Missing recordID!");
      }
      try {
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const res = await window.$gz.api.get(API_BASE_URL + recordId);
        if (res.error) {
          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;
          generateMenu(vm);
          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() {
      const vm = this;
      if (vm.canSave == false) {
        return;
      }

      try {
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        // const res = await window.$gz.api.upsert(API_BASE_URL, vm.obj);
        let strippedObj = window.$gz.util.deepCopySkip(vm.obj);
        //deep copy skip is flat so need to do items individually as well
        for (let i = 0; i < strippedObj.items.length; i++) {
          strippedObj.items[i] = window.$gz.util.deepCopySkip(
            strippedObj.items[i]
          );
        }
        const res = await window.$gz.api.upsert(API_BASE_URL, strippedObj);

        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          //POST or PUT 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
              }
            });
          }
          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() {
      try {
        const dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }
        window.$gz.form.setFormState({
          vm: this,
          loading: true
        });
        if (this.$route.params.recordid == 0) {
          JUST_DELETED = true;

          this.$router.go(-1);
        } else {
          window.$gz.form.deleteAllErrorBoxErrors(this);
          const res = await window.$gz.api.remove(
            API_BASE_URL + this.$route.params.recordid
          );
          if (res.error) {
            this.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(this);
          } else {
            JUST_DELETED = true;
            this.$router.go(-1);
          }
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, this);
      } finally {
        window.$gz.form.setFormState({
          vm: this,
          loading: false
        });
      }
    },
    duplicate() {
      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;
  }
  const 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: "inv-purchase-order",
          params: { recordid: 0 }
        });
        break;
      case "duplicate":
        m.vm.duplicate();
        break;
      case "report":
        {
          const 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.setLastReportMenuItem(FORM_KEY, res, m.vm);
        }
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  const 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
    });
  }

  menuOptions.menuItems.push({
    title: "Report",
    icon: "$ayiFileAlt",
    key: FORM_KEY + ":report",
    vm: vm
  });

  const 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
    });
  }

  if (vm.rights.delete && vm.$route.params.recordid != 0) {
    menuOptions.menuItems.push({
      title: "Delete",
      icon: "$ayiTrashAlt",
      surface: false,
      key: FORM_KEY + ":delete",
      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();
  await window.$gz.formCustomTemplate.get(FORM_CUSTOM_TEMPLATE_KEY, vm);
  await populateSelectionLists(vm);
}

//////////////////////
//
//
async function populateSelectionLists(vm) {
  await window.$gz.enums.fetchEnumList("purchaseorderstatus");
  vm.selectLists.status = window.$gz.enums.getSelectionList(
    "purchaseorderstatus"
  );
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "PurchaseOrder",
    "PurchaseOrderPONumber",
    "PurchaseOrderNotes",
    "PurchaseOrderVendorMemo",
    "PurchaseOrderDropShipToCustomerID",
    "PurchaseOrderReferenceNumber",
    "Vendor",
    "PurchaseOrderOrderedDate",
    "PurchaseOrderExpectedReceiveDate",
    "PurchaseOrderStatus",
    "Project",
    "PurchaseOrderReceiptText1",
    "PurchaseOrderReceiptText2",
    "PurchaseOrderItemList",
    "PurchaseOrderItemQuantityOrdered",
    "PurchaseOrderItemQuantityReceived",
    "Part",
    "PartName",
    "PartUPC",
    "PartDescription",
    "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",
    "UnitOfMeasure",
    "PartWholesalerID",
    "PartAlternativeWholesalerID",
    "PurchaseOrderUICopyToPurchaseOrder",
    "PartRestockRequiredByVendorList",
    "PurchaseOrderCustom1",
    "PurchaseOrderCustom2",
    "PurchaseOrderCustom3",
    "PurchaseOrderCustom4",
    "PurchaseOrderCustom5",
    "PurchaseOrderCustom6",
    "PurchaseOrderCustom7",
    "PurchaseOrderCustom8",
    "PurchaseOrderCustom9",
    "PurchaseOrderCustom10",
    "PurchaseOrderCustom11",
    "PurchaseOrderCustom12",
    "PurchaseOrderCustom13",
    "PurchaseOrderCustom14",
    "PurchaseOrderCustom15",
    "PurchaseOrderCustom16"
  ]);
}
</script>
