<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>
      <v-form ref="form">
        <v-row>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              v-model="obj.serial"
              :readonly="formState.readOnly"
              :clearable="!formState.readOnly"
              @click:clear="fieldValueChanged('serial')"
              :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')"
              type="number"
            ></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="true"
              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')"
            ></gz-pick-list>
          </v-col>
          <v-col
            v-if="form().showMe(this, 'PurchaseOrderStatus')"
            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"
              test-id="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"
              test-id="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="true"
              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="true"
              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"
              class="elevation-1"
              disable-pagination
              disable-filtering
              disable-sort
              hide-default-footer
              data-cy="itemsTable"
              dense
              :item-class="poItemsRowClasses"
            >
              <!-- <template v-slot:top>
                <div class="mb-4 ml-4">
                  <span class="title">{{
                    $ay.t("PurchaseOrderItemList")
                  }}</span>
                </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-h6">
                        {{ $ay.t("PurchaseOrderItemList") }}</span
                      ><v-btn icon v-bind="attrs" v-on="on">
                        <v-icon small>$ayiEllipsisV</v-icon>
                      </v-btn>
                    </template>
                    <v-list>
                      <v-list-item @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 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>
    <template v-if="!formState.ready">
      <v-progress-circular
        indeterminate
        color="primary"
        :size="60"
      ></v-progress-circular>
    </template>
    <!-- ########################## PURCHASE ORDER ITEM EDIT FORM  ###############################-->
    <template v-if="obj.items.length">
      <v-row justify="center">
        <v-dialog v-model="editPoItemDialog" persistent>
          <v-card>
            <v-card-title>
              <!-- <span class="headline">{{
                $ay.t("PurchaseOrderReceiptItemPurchaseOrderItemID")
              }}</span> -->
            </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="true"
                    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')]"
                  ></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"
                    :show-edit-icon="true"
                    v-model="obj.items[editPoItemIndex].partWarehouseId"
                    :readonly="formState.readOnly"
                    :label="$ay.t('PartWarehouse')"
                    ref="Items.PartWarehouseId"
                    data-cy="Items.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"
                    :label="$ay.t('PurchaseOrderItemQuantityOrdered')"
                    ref="Items.QuantityOrdered"
                    data-cy="Items.QuantityOrdered"
                    :rules="[
                      form().decimalValid(this, 'Items.QuantityOrdered'),
                      form().required(this, 'Items.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')
                    ]"
                  ></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.ReceivedDate')
                    "
                    @input="fieldValueChanged('Items.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')
                    ]"
                  ></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')"
                    ref="Items.ReceivedCost"
                    data-cy="Items.ReceivedCost"
                    :rules="[
                      form().decimalValid(this, 'Items.ReceivedCost'),
                      form().required(this, 'Items.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="true"
                    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.PurchaseTaxCodeId')
                    "
                    @input="fieldValueChanged('Items.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.VendorPartNumber')
                    "
                    @input="fieldValueChanged('Items.VendorPartNumber')"
                  ></v-text-field>
                </v-col>
              </v-row>
            </v-card-text>
            <v-card-actions>
              <v-btn
                color="blue darken-1"
                text
                @click="editPoItemDialog = false"
                >{{ $ay.t("Cancel") }}</v-btn
              >
              <v-spacer></v-spacer>
              <v-btn color="blue darken-1" text @click="receive(item)"
                ><v-icon left> $ayiBoxOpen </v-icon
                >{{ $ay.t("Receive") }}</v-btn
              >
              <v-btn color="blue darken-1" text @click="submit()">{{
                $ay.t("Save")
              }}</v-btn>
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-row>
    </template>
  </div>
</template>

<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
const FORM_KEY = "inv-purchase-order";
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);

      //id 0 means create a new record don't load one
      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;
          window.$gz.form.setFormState({
            vm: vm,
            loading: false
          });
        } else {
          await vm.getDataFromApi(vm.$route.params.recordid); //let getdata handle loading
        }
      } else {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
      window.$gz.form.setFormState({
        vm: vm,
        dirty: false,
        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);
  },
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      editPoItemDialog: false,
      editPoItemIndex: 0,
      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: null,
          notes: null,
          wiki: null,
          customFields: null,
          tags: [],
          vendorMemo: null,
          dropShipToCustomerId: null,
          referenceNumber: null,
          vendorId: null,
          orderedDate: window.$gz.locale.nowUTC8601String(),
          expectedReceiveDate: null,
          status: null,
          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(),
      ayaType: window.$gz.type.PurchaseOrder,
      currencyName: window.$gz.locale.getCurrencyName(),
      timeZoneName: window.$gz.locale.getResolvedTimeZoneName(),
      languageName: window.$gz.locale.getBrowserLanguages(),
      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: "displayPartNumber"
      });

      if (vm.obj.hasSelectableWarehouses) {
        headers.push({
          text: vm.$ay.t("PartWarehouse"),
          align: "left",
          value: "displayWarehouse"
        });
      }
      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: "displayTaxCode"
        });
      }

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

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

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

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

      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: "displayRequestUser"
          });
        }
        if (vm.form().showMe(vm, "Items.WorkorderItemPartRequestId")) {
          headers.push({
            text: vm.$ay.t("PurchaseOrderItemWorkOrderNumber"),
            align: "left",
            value: "displayRequestWorkorder"
          });
        }
      }

      if (!vm.formState.readOnly) {
        headers.push({ text: "", value: "actions" });
      }
      return headers;
    },
    itemList: function() {
      let vm = this;
      /*
        
		"items": [
			{
				"id": 1,
				"concurrency": 7281388,
				"purchaseOrderId": 1,
				"partId": 18,
				"partWarehouseId": 2,
				"quantityOrdered": 28,
				"quantityReceived": 28,
				"purchaseOrderCost": 10.8204,
				"receivedCost": 10,
				"receivedDate": "2021-01-16T13:49:59.346006Z",
				"partRequestedById": null,
				"workorderItemPartRequestId": null,
				"purchaseTaxCodeId": 3,
				"vendorPartNumber": null,
				"displayPartNumber": "733980",
				"displayWarehouse": "WHS- Carlotta Hollow",
				"displayRequestUser": null,
				"displayRequestWorkorder": null,
				"displayTaxCode": "Sales & Goods",
				"displayNetTotal": 302.9712,
				"displayTaxA": 21.207984,
				"displayTaxB": 21.207984,
				"displayLineTotal": 345.387168
			},
        */

      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,
          displayPartNumber: x.displayPartNumber,
          displayWarehouse: x.displayWarehouse,
          displayRequestUser: x.displayRequestUser,
          displayRequestWorkorder: x.displayRequestWorkorder,
          displayTaxCode: x.displayTaxCode,
          displayNetTotal: window.$gz.locale.currencyLocalized(
            x.displayNetTotal,
            vm.languageName,
            vm.currencyName
          ),
          displayTaxA: window.$gz.locale.currencyLocalized(
            x.displayTaxA,
            vm.languageName,
            vm.currencyName
          ),
          displayTaxB: window.$gz.locale.currencyLocalized(
            x.displayTaxB,
            vm.languageName,
            vm.currencyName
          ),
          displayLineTotal: window.$gz.locale.currencyLocalized(
            x.displayLineTotal,
            vm.languageName,
            vm.currencyName
          )
        };
      });
    }
  },
  methods: {
    poItemsRowClasses: function(item) {
      if (this.form().childRowHasError(this, "Items", item.index)) {
        return "font-weight-black font-italic error--text";
      }
    },
    receive: function(item) {},
    receiveAll: function() {},
    editItem: function(item) {
      this.editPoItemIndex = item.index;
      this.editPoItemDialog = true;
    },
    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
          vm.obj = res.data;
          //Change URL to new record
          //NOTE: will not cause a page re-render, almost nothing does unless forced with a KEY property or using router.GO()

          // this.$router.push({
          //   name: "inv-purchase-order",
          //   params: {
          //     recordid: res.data.id,
          //     obj: res.data // Pass data object to new form
          //   }
          // });

          //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);
      }
    },
    async duplicate() {
      let vm = this;
      if (!vm.canDuplicate || vm.$route.params.recordid == 0) {
        return;
      }
      window.$gz.form.setFormState({
        vm: vm,
        loading: true
      });
      let url = API_BASE_URL + "duplicate/" + vm.$route.params.recordid;

      try {
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        let res = await window.$gz.api.upsert(url);
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          //Navigate to new record
          this.$router.push({
            name: "project-edit",
            params: {
              recordid: res.data.id,
              obj: res.data // Pass data object to new form
            }
          });
        }
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    }
    //end methods
  }
};

/////////////////////////////
//
//
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, new: true }
        });
        break;
      case "duplicate":
        m.vm.duplicate();
        break;
      case "report":
        if (m.id != null) {
          //last report selected is in m.id
          m.vm.$router.push({
            name: "ay-report",
            params: { recordid: m.id, ayatype: window.$gz.type.PurchaseOrder }
          });
        } else {
          //general report selector chosen

          let res = await m.vm.$refs.reportSelector.open({
            ObjectType: window.$gz.type.PurchaseOrder,
            selectedRowIds: [m.vm.obj.id]
          });

          //if null for no selection
          //just bail out
          if (res == null) {
            return;
          }
          //persist last report selected
          window.$gz.form.setLastReport(FORM_KEY, res);

          //Now open the report viewer...
          m.vm.$router.push({
            name: "ay-report",
            params: { recordid: res.id, ayatype: window.$gz.type.PurchaseOrder }
          });
        }
        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: "$ayiDollyFlatbed",
    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
    },
    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,
      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) {
    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);
  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",
    "PartWarehouse",
    "TaxCode",
    "PurchaseOrderItemVendorPartNumber",
    "PurchaseOrderItemPartRequestedByID",
    "PurchaseOrderItemWorkOrderNumber",
    "PurchaseOrderItemPurchaseOrderCost",
    "PurchaseOrderItemNetTotal",
    "PurchaseOrderItemLineTotal",
    "TaxCodeTaxA",
    "TaxCodeTaxB",
    "PurchaseOrderReceiptReceivedDate",
    "PurchaseOrderReceiptItemReceiptCost",
    "PurchaseOrderReceiptItemQuantityReceivedErrorInvalid",
    "ReceiveAll",
    "Receive",
    "PurchaseOrderCustom1",
    "PurchaseOrderCustom2",
    "PurchaseOrderCustom3",
    "PurchaseOrderCustom4",
    "PurchaseOrderCustom5",
    "PurchaseOrderCustom6",
    "PurchaseOrderCustom7",
    "PurchaseOrderCustom8",
    "PurchaseOrderCustom9",
    "PurchaseOrderCustom10",
    "PurchaseOrderCustom11",
    "PurchaseOrderCustom12",
    "PurchaseOrderCustom13",
    "PurchaseOrderCustom14",
    "PurchaseOrderCustom15",
    "PurchaseOrderCustom16"
  ]);
}
</script>
