<template>
  <div v-if="value != null" class="mt-8">
    <v-row>
      <v-col cols="12">
        <v-menu offset-y>
          <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
            :headers="headerList"
            :items="itemList"
            item-key="index"
            v-model="selectedRow"
            class="elevation-1"
            disable-pagination
            disable-filtering
            disable-sort
            hide-default-footer
            data-cy="loansTable"
            dense
            :item-class="itemRowClasses"
            @click:row="handleRowClick"
            :show-select="$vuetify.breakpoint.xs"
            single-select
          >
          </v-data-table>
        </v-col>
      </template>
      <template v-if="hasData && hasSelection">
        <div ref="loantopform"></div>
        <v-btn
          v-if="canDelete && isDeleted"
          large
          @click="unDeleteItem"
          color="primary"
          >{{ $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
            :aya-type="$ay.ayt().LoanUnit"
            :show-edit-icon="true"
            v-model="
              value.items[activeWoItemIndex].loans[activeItemIndex].loanUnitId
            "
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemLoanUnit')"
            :ref="
              `Items[${activeWoItemIndex}].loans[${activeItemIndex}].loanUnitId`
            "
            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')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <v-select
            v-model="value.items[activeWoItemIndex].loans[activeItemIndex].rate"
            :items="pvm.selectLists.loanUnitRateUnits"
            item-text="name"
            item-value="id"
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemLoanRate')"
            :ref="`Items[${activeWoItemIndex}].loans[${activeItemIndex}].rate`"
            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')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-decimal
            v-model="
              value.items[activeWoItemIndex].loans[activeItemIndex].quantity
            "
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemLoanQuantity')"
            :ref="
              `Items[${activeWoItemIndex}].loans[${activeItemIndex}].quantity`
            "
            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
            :label="$ay.t('WorkOrderItemLoanOutDate')"
            v-model="
              value.items[activeWoItemIndex].loans[activeItemIndex].outDate
            "
            :readonly="formState.readOnly"
            :disabled="isDeleted"
            :ref="
              `Items[${activeWoItemIndex}].loans[${activeItemIndex}].outDate`
            "
            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
            :label="$ay.t('WorkOrderItemLoanDueDate')"
            v-model="
              value.items[activeWoItemIndex].loans[activeItemIndex].dueDate
            "
            :readonly="formState.readOnly"
            :disabled="isDeleted"
            :ref="
              `Items[${activeWoItemIndex}].loans[${activeItemIndex}].dueDate`
            "
            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
            :label="$ay.t('WorkOrderItemLoanReturnDate')"
            v-model="
              value.items[activeWoItemIndex].loans[activeItemIndex].returnDate
            "
            :readonly="formState.readOnly"
            :disabled="isDeleted"
            :ref="
              `Items[${activeWoItemIndex}].loans[${activeItemIndex}].returnDate`
            "
            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')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-pick-list
            :aya-type="$ay.ayt().TaxCode"
            :show-edit-icon="true"
            v-model="
              value.items[activeWoItemIndex].loans[activeItemIndex].taxCodeId
            "
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemLoanTaxCodeID')"
            :ref="
              `Items[${activeWoItemIndex}].loans[${activeItemIndex}].taxCodeId`
            "
            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')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-currency
            v-model="
              value.items[activeWoItemIndex].loans[activeItemIndex]
                .priceOverride
            "
            can-clear
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('PriceOverride')"
            :ref="
              `Items[${activeWoItemIndex}].loans[${activeItemIndex}].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
            v-model="
              value.items[activeWoItemIndex].loans[activeItemIndex].notes
            "
            :readonly="formState.readOnly"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemLoanNotes')"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].loans[${activeItemIndex}].notes`
              )
            "
            :ref="`Items[${activeWoItemIndex}].loans[${activeItemIndex}].notes`"
            data-cy="loanUnitNotes"
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].loans[${activeItemIndex}].notes`
              )
            "
            auto-grow
          ></v-textarea>
        </v-col>
      </template>
    </v-row>
  </div>
</template>
<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  XXXeslint-disable    */
////////////////////////////////////////////////////////////////////////////////////////////////////////////

export default {
  created() {
    this.setDefaultView();
  },
  data() {
    return {
      activeItemIndex: null,
      selectedRow: []
    };
  },
  props: {
    value: {
      default: null,
      type: Object
    },
    pvm: {
      default: null,
      type: Object
    },
    activeWoItemIndex: {
      default: null,
      type: Number
    },
    gotoIndex: {
      default: null,
      type: Number
    }
  },
  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" });
          }
        });
      }
    }
  },
  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() {
      let 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: null,
        loanUnitId: 0, //zero to break rule on new
        quantity: 1,
        rate: 1,
        cost: 0,
        priceOverride: null,
        isDirty: true,
        workOrderItemId: 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;
    }
    //---
  },
  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() {
      /*
  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 = [];

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

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

      if (this.form().showMe(this, "WorkOrderItemLoanQuantity")) {
        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")) {
        headers.push({
          text: this.$ay.t("Cost"),
          align: "right",
          value: "cost"
        });
      }

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

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

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

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

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

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

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

      if (this.form().showMe(this, "LoanLineTotalViz")) {
        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.pvm.subRights.loans.create;
    },
    canDelete: function() {
      return this.activeItemIndex != null && this.canDeleteAll;
    },
    canDeleteAll: function() {
      return this.pvm.rights.change && this.pvm.subRights.loans.delete;
    }

    //----
  }
};
</script>
