<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="primary" 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="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="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>
        </v-menu>
      </v-col>

      <template v-if="showTable">
        <!-- ############################################################### -->
        <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="unitsTable"
            dense
            :item-class="itemRowClasses"
            @click:row="handleRowClick"
            :show-select="$vuetify.breakpoint.xs"
            single-select
          >
          </v-data-table>
        </v-col>
      </template>
      <template v-if="activeItemIndex != null">
        <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, 'WorkOrderItemUnitStartDate')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-date-time-picker
            :label="$ay.t('WorkOrderItemUnitStartDate')"
            v-model="
              value.items[activeWoItemIndex].units[activeItemIndex].startDate
            "
            :readonly="formState.readOnly"
            :disabled="isDeleted"
            :ref="
              `Items[${activeWoItemIndex}].units[${activeItemIndex}].startDate`
            "
            data-cy="startDate"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].startDate`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].startDate`
              )
            "
          ></gz-date-time-picker>
        </v-col>

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

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

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemUnitUserID')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-pick-list
            :aya-type="$ay.ayt().User"
            variant="tech"
            :show-edit-icon="true"
            v-model="
              value.items[activeWoItemIndex].units[activeItemIndex].userId
            "
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemUnitUserID')"
            :ref="
              `Items[${activeWoItemIndex}].units[${activeItemIndex}].userId`
            "
            data-cy="units.userid"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].userId`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].userId`
              )
            "
            @update:name="userChange"
          ></gz-pick-list>
        </v-col>

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemUnitServiceRateID')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-pick-list
            :aya-type="$ay.ayt().ServiceRate"
            :variant="'contractid:' + value.contractId"
            :show-edit-icon="true"
            v-model="
              value.items[activeWoItemIndex].units[activeItemIndex]
                .serviceRateId
            "
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemUnitServiceRateID')"
            :ref="
              `Items[${activeWoItemIndex}].units[${activeItemIndex}].serviceRateId`
            "
            data-cy="units.serviceRateId"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].serviceRateId`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].units[${activeItemIndex}].serviceRateId`
              )
            "
            @update:name="rateChange"
          ></gz-pick-list>
        </v-col>
      </template>
    </v-row>
  </div>
</template>
<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  XXXeslint-disable    */
////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
l.Add(new FormField { TKey = "WorkOrderItemUnitNotes", FieldKey = "WorkOrderItemUnitNotes", TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "Unit", FieldKey = "WorkOrderItemUnit", TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "Tags", FieldKey = "WorkOrderItemUnitTags", TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "Wiki", FieldKey = "WorkOrderItemUnitWiki", TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "Attachments", FieldKey = "WorkOrderItemUnitAttachments", TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom1", FieldKey = "WorkOrderItemUnitCustom1", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom2", FieldKey = "WorkOrderItemUnitCustom2", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom3", FieldKey = "WorkOrderItemUnitCustom3", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom4", FieldKey = "WorkOrderItemUnitCustom4", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom5", FieldKey = "WorkOrderItemUnitCustom5", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom6", FieldKey = "WorkOrderItemUnitCustom6", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom7", FieldKey = "WorkOrderItemUnitCustom7", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom8", FieldKey = "WorkOrderItemUnitCustom8", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom9", FieldKey = "WorkOrderItemUnitCustom9", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom10", FieldKey = "WorkOrderItemUnitCustom10", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom11", FieldKey = "WorkOrderItemUnitCustom11", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom12", FieldKey = "WorkOrderItemUnitCustom12", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom13", FieldKey = "WorkOrderItemUnitCustom13", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom14", FieldKey = "WorkOrderItemUnitCustom14", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom15", FieldKey = "WorkOrderItemUnitCustom15", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });
l.Add(new FormField { TKey = "WorkOrderItemUnitCustom16", FieldKey = "WorkOrderItemUnitCustom16", IsCustomField = true, TKeySection = "WorkOrderItemUnit" });


{
"0": {
"id": 39,
"concurrency": 8129666,
"notes": "Saepe quos omnis fugiat aliquam amet animi sit dolorum voluptatibus.",
"wiki": null,
"customFields": null,
"tags": [],
"unitId": 2,
"unitViz": "86876317",
"isDirty": false,
"workOrderItemId": 20
}
}


*/
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
    }
  },
  watch: {
    activeWoItemIndex(val, oldVal) {
      if (val != oldVal) {
        this.setDefaultView();
      }
    }
  },
  methods: {
    userChange(newName) {
      this.value.items[this.activeWoItemIndex].units[
        this.activeItemIndex
      ].userViz = newName;
    },
    rateChange(newName) {
      this.value.items[this.activeWoItemIndex].units[
        this.activeItemIndex
      ].serviceRateViz = newName;
    },
    newItem() {
      let newIndex = this.value.items[this.activeWoItemIndex].units.length;

      this.value.items[this.activeWoItemIndex].units.push({
        id: 0,
        concurrency: 0,
        userId: null,
        estimatedQuantity: 0,
        startDate: null,
        stopDate: null,
        serviceRateId: null,
        isDirty: true,
        workOrderItemId: this.value.items[this.activeWoItemIndex].id,
        uid: Date.now() //used for error tracking / display
      });
      this.$emit("change");
      this.selectedRow = [{ index: newIndex }];
      this.activeItemIndex = newIndex;
    },
    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");
    },
    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);

        // //set viz if applicable
        // if(ref==""){
        //    let selectedPartWarehouse = vm.$refs.partWarehouseId.getFullSelectionValue();
        // }
      }
    },
    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;
    }
  },
  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() {
      /*
  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, "WorkOrderItemUnit")) {
        headers.push({
          text: this.$ay.t("WorkOrderItemUnit"),
          align: "left",
          value: "unitViz"
        });
      }

      if (this.form().showMe(this, "WorkOrderItemUnitNotes")) {
        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,
          notes: window.$gz.util.truncateString(
            x.notes,
            this.pvm.maxTableNotesLength
          )
        };
      });
    },
    formState: function() {
      return this.pvm.formState;
    },
    formCustomTemplateKey: function() {
      return this.pvm.formCustomTemplateKey;
    },
    showTable: function() {
      return this.value.items[this.activeWoItemIndex].units.length > 1;
    },
    canAdd: function() {
      return this.pvm.rights.change && this.pvm.subRights.units.create;
    },
    canDelete: function() {
      return (
        this.activeItemIndex != null &&
        this.pvm.rights.change &&
        this.pvm.subRights.units.delete
      );
    }
  }
};
</script>
