<template>
  <div v-if="value != null" class="mt-8">
    <v-row dense>
      <v-col cols="12">
        <v-menu offset-y max-width="600px">
          <template v-slot:activator="{ on, attrs }">
            <div class="text-h6">
              <v-icon large :color="hasData ? 'primary' : null" class="mr-2"
                >$ayiPlug</v-icon
              >
              {{ $ay.t("WorkOrderItemLoanList") }}
              <v-btn v-if="!parentDeleted" large icon v-bind="attrs" v-on="on">
                <v-icon small color="primary">$ayiEllipsisV</v-icon>
              </v-btn>
            </div>
          </template>
          <v-list>
            <v-list-item v-if="canAdd" @click="newItem">
              <v-list-item-icon>
                <v-icon>$ayiPlus</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{
                $ay.t("New")
              }}</v-list-item-title> </v-list-item
            ><v-list-item v-if="canDelete && isDeleted" @click="unDeleteItem">
              <v-list-item-icon>
                <v-icon>$ayiTrashRestoreAlt</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{ $ay.t("Undelete") }}</v-list-item-title>
            </v-list-item>
            <v-list-item v-if="canDelete && !isDeleted" @click="deleteItem">
              <v-list-item-icon>
                <v-icon>$ayiTrashAlt</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{ $ay.t("SoftDelete") }}</v-list-item-title>
            </v-list-item>
            <v-list-item v-if="canDeleteAll" @click="deleteAllItem">
              <v-list-item-icon>
                <v-icon>$ayiDumpster</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{
                $ay.t("SoftDeleteAll")
              }}</v-list-item-title>
            </v-list-item>
          </v-list>
        </v-menu>
      </v-col>

      <template v-if="hasData">
        <!-- ############################################################### -->
        <v-col cols="12" class="mb-10">
          <v-data-table
            v-model="selectedRow"
            :headers="headerList"
            :items="itemList"
            item-key="index"
            class="elevation-1"
            disable-pagination
            disable-filtering
            disable-sort
            hide-default-footer
            data-cy="loansTable"
            dense
            :item-class="itemRowClasses"
            :show-select="$vuetify.breakpoint.xs"
            single-select
            @click:row="handleRowClick"
          >
          </v-data-table>
        </v-col>
      </template>
      <template v-if="hasData && hasSelection">
        <div ref="loantopform"></div>
        <v-btn
          v-if="canDelete && isDeleted"
          large
          color="primary"
          @click="unDeleteItem"
          >{{ $ay.t("Undelete")
          }}<v-icon right large>$ayiTrashRestoreAlt</v-icon></v-btn
        >

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

        <v-col
          v-if="
            form().showMe(this, 'WorkOrderItemLoanRate') &&
              !value.userIsRestrictedType
          "
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <v-select
            :ref="`Items[${activeWoItemIndex}].loans[${activeItemIndex}].rate`"
            v-model="value.items[activeWoItemIndex].loans[activeItemIndex].rate"
            dense
            :items="pvm.selectLists.loanUnitRateUnits"
            item-text="name"
            item-value="id"
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemLoanRate')"
            data-cy="loanUnitRateUnit"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].loans[${activeItemIndex}].rate`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].loans[${activeItemIndex}].rate`
              )
            "
            @change="loanUnitRateUnitChange"
          ></v-select>
        </v-col>

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

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemLoanOutDate')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-date-time-picker
            :ref="
              `Items[${activeWoItemIndex}].loans[${activeItemIndex}].outDate`
            "
            v-model="
              value.items[activeWoItemIndex].loans[activeItemIndex].outDate
            "
            :label="$ay.t('WorkOrderItemLoanOutDate')"
            :readonly="formState.readOnly || value.userIsRestrictedType"
            :disabled="isDeleted"
            data-cy="loanUnitOutDate"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].loans[${activeItemIndex}].outDate`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].loans[${activeItemIndex}].outDate`
              )
            "
          ></gz-date-time-picker>
        </v-col>

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemLoanDueDate')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-date-time-picker
            :ref="
              `Items[${activeWoItemIndex}].loans[${activeItemIndex}].dueDate`
            "
            v-model="
              value.items[activeWoItemIndex].loans[activeItemIndex].dueDate
            "
            :label="$ay.t('WorkOrderItemLoanDueDate')"
            :readonly="formState.readOnly || value.userIsRestrictedType"
            :disabled="isDeleted"
            data-cy="loanUnitDueDate"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].loans[${activeItemIndex}].dueDate`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].loans[${activeItemIndex}].dueDate`
              )
            "
          ></gz-date-time-picker>
        </v-col>

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemLoanReturnDate')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-date-time-picker
            :ref="
              `Items[${activeWoItemIndex}].loans[${activeItemIndex}].returnDate`
            "
            v-model="
              value.items[activeWoItemIndex].loans[activeItemIndex].returnDate
            "
            :label="$ay.t('WorkOrderItemLoanReturnDate')"
            :readonly="formState.readOnly || value.userIsRestrictedType"
            :disabled="isDeleted"
            data-cy="loanUnitReturnDate"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].loans[${activeItemIndex}].returnDate`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].loans[${activeItemIndex}].returnDate`
              )
            "
          ></gz-date-time-picker>
        </v-col>

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

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

        <v-col v-if="form().showMe(this, 'WorkOrderItemLoanNotes')" cols="12">
          <v-textarea
            :ref="`Items[${activeWoItemIndex}].loans[${activeItemIndex}].notes`"
            v-model="
              value.items[activeWoItemIndex].loans[activeItemIndex].notes
            "
            dense
            :readonly="formState.readOnly || value.userIsRestrictedType"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemLoanNotes')"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].loans[${activeItemIndex}].notes`
              )
            "
            data-cy="loanUnitNotes"
            auto-grow
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].loans[${activeItemIndex}].notes`
              )
            "
          ></v-textarea>
        </v-col>
      </template>
    </v-row>
  </div>
</template>
<script>
export default {
  props: {
    value: {
      default: null,
      type: Object
    },
    pvm: {
      default: null,
      type: Object
    },
    activeWoItemIndex: {
      default: null,
      type: Number
    },
    gotoIndex: {
      default: null,
      type: Number
    }
  },
  data() {
    return {
      activeItemIndex: null,
      selectedRow: []
    };
  },
  computed: {
    isDeleted: function() {
      if (
        this.value.items[this.activeWoItemIndex].loans[this.activeItemIndex] ==
        null
      ) {
        this.setDefaultView();
        return true;
      }
      return (
        this.value.items[this.activeWoItemIndex].loans[this.activeItemIndex]
          .deleted === true
      );
    },
    parentDeleted: function() {
      return this.value.items[this.activeWoItemIndex].deleted === true;
    },

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

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

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

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

      if (this.form().showMe(this, "WorkOrderItemLoanOutDate")) {
        headers.push({
          text: this.$ay.t("WorkOrderItemLoanOutDate"),
          align: "right",
          value: "outDate"
        });
      }

      if (this.form().showMe(this, "WorkOrderItemLoanDueDate")) {
        headers.push({
          text: this.$ay.t("WorkOrderItemLoanDueDate"),
          align: "right",
          value: "dueDate"
        });
      }

      if (this.form().showMe(this, "WorkOrderItemLoanReturnDate")) {
        headers.push({
          text: this.$ay.t("WorkOrderItemLoanReturnDate"),
          align: "right",
          value: "returnDate"
        });
      }

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

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

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

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

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

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

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

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

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

      if (
        this.form().showMe(this, "LoanLineTotalViz") &&
        !this.value.userIsRestrictedType
      ) {
        headers.push({
          text: this.$ay.t("LineTotal"),
          align: "right",
          value: "lineTotalViz"
        });
      }
      return headers;
    },
    itemList: function() {
      return this.value.items[this.activeWoItemIndex].loans.map((x, i) => {
        return {
          index: i,
          id: x.id,
          loanUnitViz: x.loanUnitViz,
          unitOfMeasureViz: x.unitOfMeasureViz,
          quantity: window.$gz.locale.decimalLocalized(
            x.quantity,
            this.pvm.languageName
          ),
          outDate: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
            x.outDate,
            this.pvm.timeZoneName,
            this.pvm.languageName,
            this.pvm.hour12
          ),
          dueDate: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
            x.dueDate,
            this.pvm.timeZoneName,
            this.pvm.languageName,
            this.pvm.hour12
          ),
          returnDate: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
            x.returnDate,
            this.pvm.timeZoneName,
            this.pvm.languageName,
            this.pvm.hour12
          ),
          notes: window.$gz.util.truncateString(
            x.notes,
            this.pvm.maxTableNotesLength
          ),

          cost: window.$gz.locale.currencyLocalized(
            x.cost,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          listPrice: window.$gz.locale.currencyLocalized(
            x.listPrice,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          priceViz: window.$gz.locale.currencyLocalized(
            x.priceViz,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          taxCodeViz: x.taxCodeViz,
          priceOverride: window.$gz.locale.currencyLocalized(
            x.priceOverride,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          netViz: window.$gz.locale.currencyLocalized(
            x.netViz,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          taxAViz: window.$gz.locale.currencyLocalized(
            x.taxAViz,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          taxBViz: window.$gz.locale.currencyLocalized(
            x.taxBViz,
            this.pvm.languageName,
            this.pvm.currencyName
          ),
          lineTotalViz: window.$gz.locale.currencyLocalized(
            x.lineTotalViz,
            this.pvm.languageName,
            this.pvm.currencyName
          )
        };
      });
    },
    formState: function() {
      return this.pvm.formState;
    },
    formCustomTemplateKey: function() {
      return this.pvm.formCustomTemplateKey;
    },
    hasData: function() {
      return this.value.items[this.activeWoItemIndex].loans.length > 0;
    },
    hasSelection: function() {
      return this.activeItemIndex != null;
    },
    canAdd: function() {
      return this.pvm.rights.change && !this.value.userIsRestrictedType;
    },
    canDelete: function() {
      return (
        this.activeItemIndex != null &&
        this.canDeleteAll &&
        !this.value.userIsRestrictedType
      );
    },
    canDeleteAll: function() {
      return this.pvm.rights.change && !this.value.userIsRestrictedType;
    }
  },
  watch: {
    activeWoItemIndex(val, oldVal) {
      if (val != oldVal) {
        this.setDefaultView();
      }
    },
    gotoIndex(val, oldVal) {
      if (val != oldVal) {
        let gotoIndex = val;
        if (val < 0) {
          //it's a create request
          gotoIndex = this.newItem();
        }
        this.selectedRow = [{ index: gotoIndex }];
        this.activeItemIndex = gotoIndex;
        this.$nextTick(() => {
          const el = this.$refs.loantopform;
          if (el) {
            el.scrollIntoView({ behavior: "smooth" });
          }
        });
      }
    }
  },
  created() {
    this.setDefaultView();
  },
  methods: {
    loanUnitRateUnitChange(newId) {
      this.value.items[this.activeWoItemIndex].loans[
        this.activeItemIndex
      ].unitOfMeasureViz = this.pvm.selectLists.loanUnitRateUnits.find(
        s => s.id == newId
      ).name;
    },
    loanUnitChange(newName) {
      this.value.items[this.activeWoItemIndex].loans[
        this.activeItemIndex
      ].loanUnitViz = newName;
    },
    taxCodeChange(newName) {
      this.value.items[this.activeWoItemIndex].loans[
        this.activeItemIndex
      ].taxCodeViz = newName;
    },
    newItem() {
      const newIndex = this.value.items[this.activeWoItemIndex].loans.length;

      this.value.items[this.activeWoItemIndex].loans.push({
        id: 0,
        concurrency: 0,
        notes: null,
        outDate: null,
        dueDate: null,
        returnDate: null,
        taxCodeId: window.$gz.store.state.globalSettings.defaultTaxPartSaleId,
        loanUnitId: 0, //zero to break rule on new
        quantity: 1,
        rate: 1,
        cost: 0,
        priceOverride: null,
        isDirty: true,
        pmItemId: this.value.items[this.activeWoItemIndex].id,
        uid: Date.now(),
        loanUnitViz: null,
        taxCodeViz: null,
        unitOfMeasureViz: null
      });
      this.$emit("change");
      this.selectedRow = [{ index: newIndex }];
      this.activeItemIndex = newIndex;
      //trigger rule breaking / validation
      this.$nextTick(() => {
        this.value.items[this.activeWoItemIndex].loans[
          this.activeItemIndex
        ].loanUnitId = null;
        this.fieldValueChanged(
          `Items[${this.activeWoItemIndex}].loans[${this.activeItemIndex}].loanUnitId`
        );
      });
      return newIndex; //for create new on goto
    },
    unDeleteItem() {
      this.value.items[this.activeWoItemIndex].loans[
        this.activeItemIndex
      ].deleted = false;
      this.setDefaultView();
    },
    deleteItem() {
      this.value.items[this.activeWoItemIndex].loans[
        this.activeItemIndex
      ].deleted = true;
      this.setDefaultView();
      this.$emit("change");
    },
    deleteAllItem() {
      this.value.items[this.activeWoItemIndex].loans.forEach(
        z => (z.deleted = true)
      );
      this.setDefaultView();
      this.$emit("change");
    },
    setDefaultView: function() {
      //if only one record left then display it otherwise just let the datatable show what the user can click on
      if (this.value.items[this.activeWoItemIndex].loans.length == 1) {
        this.selectedRow = [{ index: 0 }];
        this.activeItemIndex = 0;
      } else {
        this.selectedRow = [];
        this.activeItemIndex = null; //select nothing in essence resetting a child selects and this one too clearing form
      }
    },
    handleRowClick: function(item) {
      this.activeItemIndex = item.index;
      this.selectedRow = [{ index: item.index }];
    },
    form() {
      return window.$gz.form;
    },
    fieldValueChanged(ref) {
      if (!this.formState.loading && !this.formState.readonly) {
        //flag this record dirty so it gets picked up by save
        this.value.items[this.activeWoItemIndex].loans[
          this.activeItemIndex
        ].isDirty = true;
        window.$gz.form.fieldValueChanged(this.pvm, ref);
      }
    },
    itemRowClasses: function(item) {
      let ret = "";
      const isDeleted =
        this.value.items[this.activeWoItemIndex].loans[item.index].deleted ===
        true;

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

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