<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"
                >$ayiFan</v-icon
              >
              {{ $ay.t("WorkOrderItemUnitList") }}
              <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="canAdd" @click="showBulkUnitsDialog()">
              <v-list-item-icon>
                <v-icon>$ayiFan</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{
                $ay.t("AddMultipleUnits")
              }}</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="unitsTable"
            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="unittopform"></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, 'WorkOrderItemUnit')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-pick-list
            :ref="
              `Items[${activeWoItemIndex}].units[${activeItemIndex}].unitId`
            "
            v-model="
              value.items[activeWoItemIndex].units[activeItemIndex].unitId
            "
            :aya-type="$ay.ayt().Unit"
            :variant="'customerid:' + value.customerId"
            :show-edit-icon="!value.userIsRestrictedType"
            :readonly="
              formState.readOnly || isDeleted || value.userIsRestrictedType
            "
            :disabled="isDeleted"
            :label="$ay.t('Unit')"
            data-cy="units.unitId"
            :rules="[
              form().required(
                this,
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].unitId`
              )
            ]"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].unitId`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].unitId`
              )
            "
            @update:name="unitChange"
          ></gz-pick-list>
        </v-col>

        <v-col
          v-if="
            form().showMe(this, 'UnitWarrantyInfo') &&
              !value.userIsRestrictedType
          "
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <v-card>
            <v-card-title>{{ $ay.t("UnitWarrantyInfo") }}</v-card-title>
            <!-- eslint-disable vue/no-v-html -->
            <v-card-text
              v-html="
                value.items[activeWoItemIndex].units[activeItemIndex]
                  .warrantyViz
              "
            >
            </v-card-text>
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn color="primary" text @click="getWarrantyInfo">{{
                $ay.t("Search")
              }}</v-btn>
            </v-card-actions>
          </v-card>
        </v-col>

        <v-col
          v-if="
            form().showMe(this, 'WorkOrderItemUnitNotes') &&
              !value.userIsRestrictedType
          "
          cols="12"
        >
          <v-textarea
            :ref="`Items[${activeWoItemIndex}].units[${activeItemIndex}].notes`"
            v-model="
              value.items[activeWoItemIndex].units[activeItemIndex].notes
            "
            dense
            :readonly="formState.readOnly"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemUnitNotes')"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].notes`
              )
            "
            data-cy="unitUnitNotes"
            auto-grow
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].notes`
              )
            "
          ></v-textarea>
        </v-col>

        <v-col
          v-if="
            form().showMe(this, 'WorkOrderItemUnitTags') &&
              !value.userIsRestrictedType
          "
          cols="12"
        >
          <gz-tag-picker
            :ref="`Items[${activeWoItemIndex}].units[${activeItemIndex}].tags`"
            v-model="value.items[activeWoItemIndex].units[activeItemIndex].tags"
            :readonly="formState.readOnly"
            data-cy="unitTags"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].tags`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].tags`
              )
            "
          ></gz-tag-picker>
        </v-col>

        <v-col v-if="!value.userIsRestrictedType" cols="12">
          <gz-custom-fields
            :ref="
              `Items[${activeWoItemIndex}].units[${activeItemIndex}].customFields`
            "
            v-model="
              value.items[activeWoItemIndex].units[activeItemIndex].customFields
            "
            :form-key="formCustomTemplateKey"
            :readonly="formState.readOnly"
            :parent-v-m="this"
            key-start-with="WorkOrderItemUnitCustom"
            data-cy="unitCustomFields"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].customFields`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].customFields`
              )
            "
          ></gz-custom-fields>
        </v-col>

        <v-col
          v-if="
            form().showMe(this, 'WorkOrderItemUnitWiki') &&
              !value.userIsRestrictedType
          "
          cols="12"
        >
          <gz-wiki
            :ref="`Items[${activeWoItemIndex}].units[${activeItemIndex}].wiki`"
            v-model="value.items[activeWoItemIndex].units[activeItemIndex].wiki"
            :aya-type="$ay.ayt().WorkOrderItem"
            :aya-id="value.id"
            :readonly="formState.readOnly"
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].wiki`
              )
            "
          ></gz-wiki
        ></v-col>

        <v-col
          v-if="
            form().showMe(this, 'WorkOrderItemUnitAttachments') &&
              value.id &&
              !value.userIsRestrictedType
          "
          cols="12"
        >
          <gz-attachments
            :readonly="formState.readOnly"
            :aya-type="$ay.ayt().WorkOrderItemUnit"
            :aya-id="value.items[activeWoItemIndex].units[activeItemIndex].id"
          ></gz-attachments
        ></v-col>
      </template>
    </v-row>
    <!-- ################################################################################-->
    <!-- ##########################  BULK ADD UNITS FORM  ###############################-->
    <!-- ################################################################################-->
    <template>
      <v-row dense justify="center">
        <v-dialog v-model="bulkUnitsDialog" persistent max-width="600px">
          <v-card>
            <v-card-title>{{ $ay.t("AddMultipleUnits") }}</v-card-title>
            <v-card-text>
              <gz-tag-picker v-model="selectedBulkUnitTags"></gz-tag-picker>
              <gz-pick-list
                v-model="selectedBulkUnitCustomer"
                :aya-type="$ay.ayt().Customer"
                :show-edit-icon="false"
                :label="$ay.t('Customer')"
                :can-clear="true"
              ></gz-pick-list>

              <v-data-table
                v-model="selectedBulkUnits"
                dense
                :headers="bulkUnitTableHeaders"
                :items="availableBulkUnits"
                class="my-10"
                :disable-filtering="true"
                hide-default-footer
                :no-data-text="$ay.t('NoData')"
                show-select
                item-key="unitId"
              >
              </v-data-table>
            </v-card-text>
            <v-card-actions>
              <v-btn text color="primary" @click="bulkUnitsDialog = false">{{
                $ay.t("Cancel")
              }}</v-btn>
              <v-spacer></v-spacer>
              <v-btn
                :disabled="selectedBulkUnitTags.length == 0"
                color="primary"
                text
                @click="bulkUnitsSearch()"
                >{{ $ay.t("Search") }}</v-btn
              >
              <v-btn
                :disabled="selectedBulkUnits.length == 0"
                color="primary"
                text
                @click="addSelectedBulkUnits()"
                >{{ $ay.t("Add") }}</v-btn
              >
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-row>
    </template>
  </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
    },
    addNew: {
      default: null,
      type: Number
    }
  },
  data() {
    return {
      activeItemIndex: null,
      selectedRow: [],
      bulkUnitsDialog: false,
      selectedBulkUnitCustomer: this.value.customerId,
      availableBulkUnits: [],
      selectedBulkUnits: [],
      selectedBulkUnitTags: [],
      bulkUnitTableHeaders: []
    };
  },
  computed: {
    isDeleted: function() {
      if (
        this.value.items[this.activeWoItemIndex].units[this.activeItemIndex] ==
        null
      ) {
        this.setDefaultView();
        return true;
      }
      return (
        this.value.items[this.activeWoItemIndex].units[this.activeItemIndex]
          .deleted === true
      );
    },
    parentDeleted: function() {
      return this.value.items[this.activeWoItemIndex].deleted === true;
    },

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

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

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

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

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

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

      return headers;
    },
    itemList: function() {
      return this.value.items[this.activeWoItemIndex].units.map((x, i) => {
        return {
          index: i,
          id: x.id,
          unitViz: x.unitViz,
          unitModelVendorViz: x.unitModelVendorViz,
          unitModelNameViz: x.unitModelNameViz,
          unitDescriptionViz: x.unitDescriptionViz,
          notes: window.$gz.util.truncateString(
            x.notes,
            this.pvm.maxTableNotesLength
          )
        };
      });
    },
    formState: function() {
      return this.pvm.formState;
    },
    formCustomTemplateKey: function() {
      return this.pvm.formCustomTemplateKey;
    },
    hasData: function() {
      return this.value.items[this.activeWoItemIndex].units.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.unittopform;
          if (el) {
            el.scrollIntoView({ behavior: "smooth" });
          }
        });
      }
    }
  },
  created() {
    this.setDefaultView();
  },
  methods: {
    async updateContractIfApplicable() {
      const id = this.value.items[this.activeWoItemIndex].units[
        this.activeItemIndex
      ].unitId;
      if (!id || id == 0) {
        return;
      }
      const res = await window.$gz.api.get(`unit/work-order-info/${id}`);
      if (res.error) {
        window.$gz.eventBus.$emit(
          "notify-warning",
          window.$gz.errorHandler.errorToString(res, this)
        );
      } else {
        if (res.data.contract.id == 0) {
          //no contract, just bail
          return;
        }
        //has contract, if it differs from main work order contract then offer to set it
        if (res.data.contract.id == this.value.contractId) {
          //same contract, just bail
          //yes the date could not be different but we're not going to pick that nit, they can just unset and set if it matters
          return;
        }
        //Prompt user to use new contract
        const prompt = this.$ay
          .t("ApplyUnitContract")
          .replace("{0}", res.data.contract.name);

        const dialogResult = await window.$gz.dialog.confirmGenericPreTranslated(
          prompt,
          "question"
        );
        if (dialogResult == false) {
          return;
        } else {
          this.value.contractId = res.data.contract.id;
          this.value.isDirty = true;
          this.pvm.formState.dirty = true;
          this.$emit("change");
        }
      }
    },
    async getWarrantyInfo() {
      this.warrantyInfo = null;

      const id = this.value.items[this.activeWoItemIndex].units[
        this.activeItemIndex
      ].unitId;
      if (!id || id == 0) {
        return;
      }
      const res = await window.$gz.api.get(`unit/service-warranty-info/${id}`);
      if (res.error) {
        window.$gz.eventBus.$emit(
          "notify-warning",
          window.$gz.errorHandler.errorToString(res, this)
        );
      } else {
        const r = res.data;

        let WarrantyInfo = `${this.$ay.t("Warranty")}: `;
        let WarrantyExpiryInfo = "-";
        if (r.lifeTimeWarranty) {
          WarrantyExpiryInfo = this.$ay.t("UnitModelLifeTimeWarranty");
        } else {
          if (r.warrantyExpiryDate) {
            WarrantyExpiryInfo = `${this.$ay.t(
              "WarrantyExpires"
            )}:  ${window.$gz.locale.utcDateToShortDateAndTimeLocalized(
              r.warrantyExpiryDate,
              this.pvm.timeZoneName,
              this.pvm.languageName,
              this.pvm.hour12
            )}`;
          }
        }
        WarrantyInfo += WarrantyExpiryInfo;

        let PurchasedFrom = "-";
        if (r.purchaseFromVendorId) {
          PurchasedFrom = `<a href="/vendors/${r.purchaseFromVendorId}"> ${r.purchasedFromVendor}</a>`;
        }
        let PurchasedDate = "-";
        if (r.purchaseDate) {
          PurchasedDate = window.$gz.locale.utcDateToShortDateAndTimeLocalized(
            r.purchaseDate,
            this.pvm.timeZoneName,
            this.pvm.languageName,
            this.pvm.hour12
          );
        }
        const PurchaseInfo = `${this.$ay.t(
          "UnitPurchaseFromID"
        )}: ${PurchasedFrom}<br/>${this.$ay.t(
          "UnitPurchasedDate"
        )}: ${PurchasedDate}<br/>${this.$ay.t(
          "UnitReceipt"
        )}: ${r.purchaseReceiptNumber ?? "-"}`;

        let RecentWorkOrderList = "";
        if (r.recentWorkOrders.length > 0) {
          RecentWorkOrderList += "<br/>";
          r.recentWorkOrders.forEach(x => {
            RecentWorkOrderList += `<a href="/svc-workorders/${x.id}"> ${
              x.serial
            }<span class='ml-5'>${window.$gz.locale.utcDateToShortDateAndTimeLocalized(
              x.serviceDate,
              this.pvm.timeZoneName,
              this.pvm.languageName,
              this.pvm.hour12
            )}</span></a><br/>`;
          });
        } else {
          RecentWorkOrderList = "-";
        }

        const RecentWorkOrderInfo = `${this.$ay.t(
          "RecentWorkOrders"
        )}:${RecentWorkOrderList}`;

        const d = `<div>${WarrantyInfo}<br/>${PurchaseInfo}<br/>${RecentWorkOrderInfo}</div>`;

        this.value.items[this.activeWoItemIndex].units[
          this.activeItemIndex
        ].warrantyViz = d;
      }
    },
    showBulkUnitsDialog() {
      if (this.bulkUnitTableHeaders.length == 0) {
        //init bulk table headers
        this.bulkUnitTableHeaders = [
          { text: this.$ay.t("Customer"), value: "customerName" },
          { text: this.$ay.t("Unit"), value: "unitSerial" }
        ];
      }
      this.bulkUnitsDialog = true;
    },
    async bulkUnitsSearch() {
      this.selectedBulkUnits.splice(0);
      this.availableBulkUnits.splice(0);

      const res = await window.$gz.api.post(`unit/bulk-add-selection-list`, {
        tags: this.selectedBulkUnitTags,
        restrictToCustomerId: this.selectedBulkUnitCustomer
      });
      if (res.error) {
        window.$gz.eventBus.$emit(
          "notify-warning",
          window.$gz.errorHandler.errorToString(res, this)
        );
      } else {
        this.availableBulkUnits = res.data;
      }
    },
    addSelectedBulkUnits() {
      if (this.selectedBulkUnits.length > 0) {
        let newIndex = this.value.items[this.activeWoItemIndex].units.length;
        this.selectedBulkUnits.forEach(z => {
          newIndex++;
          this.value.items[this.activeWoItemIndex].units.push({
            id: 0,
            concurrency: 0,
            wiki: null,
            customFields: "{}",
            tags: [],
            notes: null,
            unitId: z.unitId, //zero to break rule on new
            isDirty: true,
            pmItemId: this.value.items[this.activeWoItemIndex].id,
            uid: Date.now(),
            unitViz: z.unitSerial,
            warrantyViz: null
          });
        });
        this.$emit("change");
        this.selectedRow = [{ index: newIndex }];
        this.activeItemIndex = newIndex;
      }
      this.bulkUnitsDialog = false;
    },
    async unitChange(newName) {
      this.value.items[this.activeWoItemIndex].units[
        this.activeItemIndex
      ].unitViz = newName;
      this.value.items[this.activeWoItemIndex].units[
        this.activeItemIndex
      ].warrantyViz = null;
      await this.updateContractIfApplicable();
    },
    newItem() {
      const newIndex = this.value.items[this.activeWoItemIndex].units.length;
      this.value.items[this.activeWoItemIndex].units.push({
        id: 0,
        concurrency: 0,
        wiki: null,
        customFields: "{}",
        tags: [],
        notes: null,
        unitId: 0, //zero to break rule on new
        isDirty: true,
        pmItemId: this.value.items[this.activeWoItemIndex].id,
        uid: Date.now(),
        unitViz: null,
        warrantyViz: null
      });

      this.$emit("change");
      this.selectedRow = [{ index: newIndex }];
      this.activeItemIndex = newIndex;
      //trigger rule breaking / validation
      this.$nextTick(() => {
        this.value.items[this.activeWoItemIndex].units[
          this.activeItemIndex
        ].unitId = null;
        this.fieldValueChanged(
          `Items[${this.activeWoItemIndex}].units[${this.activeItemIndex}].unitId`
        );
      });

      return newIndex; //for create new on goto
    },
    unDeleteItem() {
      this.value.items[this.activeWoItemIndex].units[
        this.activeItemIndex
      ].deleted = false;
      this.setDefaultView();
    },
    deleteItem() {
      this.value.items[this.activeWoItemIndex].units[
        this.activeItemIndex
      ].deleted = true;
      this.setDefaultView();
      this.$emit("change");
    },
    deleteAllItem() {
      this.value.items[this.activeWoItemIndex].units.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].units.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].units[
          this.activeItemIndex
        ].isDirty = true;
        window.$gz.form.fieldValueChanged(this.pvm, ref);
      }
    },
    itemRowClasses: function(item) {
      let ret = "";
      const isDeleted =
        this.value.items[this.activeWoItemIndex].units[item.index].deleted ===
        true;

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

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