<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"
                >$ayiTasks</v-icon
              >
              {{ $ay.t("WorkOrderItemTasks") }}
              <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="taskGroupDialog = true">
              <v-list-item-icon>
                <v-icon>$ayiTasks</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{ $ay.t("TaskGroup") }}</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="expensesTable"
            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="tasktopform"></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, 'WorkOrderItemTaskSequence')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <v-text-field
            v-model="
              value.items[activeWoItemIndex].tasks[activeItemIndex].sequence
            "
            :readonly="formState.readOnly"
            :disabled="isDeleted"
            :label="$ay.t('Sequence')"
            :ref="
              `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].sequence`
            "
            :rules="[
              form().integerValid(
                this,
                `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].sequence`
              )
            ]"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].sequence`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].sequence`
              )
            "
            type="number"
          ></v-text-field>
        </v-col>

        <v-col
          v-if="
            form().showMe(
              this,
              'WorkOrderItemTaskWorkOrderItemTaskCompletionType'
            )
          "
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <v-select
            v-model="
              value.items[activeWoItemIndex].tasks[activeItemIndex].status
            "
            :items="pvm.selectLists.woItemTaskCompletionTypes"
            item-text="name"
            item-value="id"
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemTaskWorkOrderItemTaskCompletionType')"
            :ref="
              `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].status`
            "
            data-cy="usertype"
            :rules="[
              form().integerValid(
                this,
                `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].status`
              )
            ]"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].status`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].status`
              )
            "
            @change="statusChange"
          ></v-select>
        </v-col>

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemTaskUser')"
          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].tasks[activeItemIndex]
                .completedByUserId
            "
            :readonly="formState.readOnly || isDeleted"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemTaskUser')"
            :ref="
              `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].completedByUserId`
            "
            data-cy="expenseUser"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].completedByUserId`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].completedByUserId`
              )
            "
            @update:name="userChange"
          ></gz-pick-list>
        </v-col>

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

        <v-col v-if="form().showMe(this, 'WorkOrderItemTaskTaskID')" cols="12">
          <v-textarea
            v-model="value.items[activeWoItemIndex].tasks[activeItemIndex].task"
            :readonly="formState.readOnly"
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemTaskTaskID')"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].task`
              )
            "
            :rules="[
              form().required(
                this,
                `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].task`
              )
            ]"
            :ref="`Items[${activeWoItemIndex}].tasks[${activeItemIndex}].task`"
            data-cy="expenseDescription"
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].task`
              )
            "
            auto-grow
          ></v-textarea>
        </v-col>
      </template>
    </v-row>
    <!-- ################################################################################-->
    <!-- ##########################  GROUP SELECTOR FORM  ###############################-->
    <!-- ################################################################################-->
    <template>
      <v-row justify="center">
        <v-dialog max-width="600px" v-model="taskGroupDialog">
          <v-card>
            <v-card-title> </v-card-title>
            <v-card-text>
              <gz-pick-list
                :aya-type="$ay.ayt().TaskGroup"
                :show-edit-icon="true"
                v-model="selectedTaskGroup"
                :label="$ay.t('TaskGroupList')"
                ref="selectedTaskGroup"
                data-cy="selectedTaskGroup"
              ></gz-pick-list>
            </v-card-text>
            <v-card-actions>
              <v-btn text @click="taskGroupDialog = false" color="primary">{{
                $ay.t("Cancel")
              }}</v-btn>
              <v-spacer></v-spacer>
              <v-btn
                :disabled="selectedTaskGroup == null"
                color="primary"
                text
                @click="addTaskGroup()"
                class="ml-4"
                >{{ $ay.t("Add") }}</v-btn
              >
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-row>
    </template>
  </div>
</template>
<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  XXXeslint-disable    */
////////////////////////////////////////////////////////////////////////////////////////////////////////////

export default {
  created() {
    this.setDefaultView();
  },
  data() {
    return {
      activeItemIndex: null,
      selectedRow: [],
      taskGroupDialog: false,
      selectedTaskGroup: null
    };
  },
  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.tasktopform;
          if (el) {
            el.scrollIntoView({ behavior: "smooth" });
          }
        });
      }
    }
  },
  methods: {
    async addTaskGroup() {
      let res = await window.$gz.api.get(
        `task-group/${this.selectedTaskGroup}`
      );
      if (res.data && res.data.items) {
        let newIndex = this.value.items[this.activeWoItemIndex].tasks.length;
        let incompleteViz = this.pvm.selectLists.woItemTaskCompletionTypes.find(
          s => s.id == 1 //incomplete
        ).name;
        res.data.items.forEach(z => {
          newIndex++;

          this.value.items[this.activeWoItemIndex].tasks.push({
            id: 0,
            concurrency: 0,
            sequence: newIndex,
            task: z.task,
            status: 1, //incomplete==1
            statusViz: incompleteViz,
            completedByUserId: null,
            completedDate: null,
            isDirty: true,
            workOrderItemId: this.value.items[this.activeWoItemIndex].id,
            uid: Date.now(),
            completedByUserViz: null
          });
        });
        this.$emit("change");
        this.selectedRow = [{ index: newIndex }];
        this.activeItemIndex = newIndex;
      }

      this.taskGroupDialog = false;
    },
    userChange(newName) {
      this.value.items[this.activeWoItemIndex].tasks[
        this.activeItemIndex
      ].completedByUserViz = newName;
    },
    statusChange(newStatusId) {
      this.value.items[this.activeWoItemIndex].tasks[
        this.activeItemIndex
      ].statusViz = this.pvm.selectLists.woItemTaskCompletionTypes.find(
        s => s.id == newStatusId
      ).name;

      //completed date auto set by status change if not a todo
      if (newStatusId != 1) {
        this.value.items[this.activeWoItemIndex].tasks[
          this.activeItemIndex
        ].completedDate = window.$gz.locale.nowUTC8601String();
      } else {
        this.value.items[this.activeWoItemIndex].tasks[
          this.activeItemIndex
        ].completedDate = null;
      }
    },
    newItem() {
      let newIndex = this.value.items[this.activeWoItemIndex].tasks.length;
      this.value.items[this.activeWoItemIndex].tasks.push({
        id: 0,
        concurrency: 0,
        sequence: newIndex + 1, //indexes are zero based but sequences are visible to user so 1 based
        task: undefined, //to trigger validation on new
        status: 1, //incomplete==1
        completedByUserId: null,
        completedDate: null,
        isDirty: true,
        workOrderItemId: this.value.items[this.activeWoItemIndex].id,
        uid: Date.now(),
        completedByUserViz: null,
        statusViz: null
      });
      this.$emit("change");
      this.selectedRow = [{ index: newIndex }];
      this.activeItemIndex = newIndex;
      //trigger rule breaking / validation
      this.$nextTick(() => {
        this.value.items[this.activeWoItemIndex].tasks[
          this.activeItemIndex
        ].task = null;
        this.fieldValueChanged(
          `Items[${this.activeWoItemIndex}].tasks[${this.activeItemIndex}].task`
        );
      });
      return newIndex; //for create new on goto
    },
    unDeleteItem() {
      this.value.items[this.activeWoItemIndex].tasks[
        this.activeItemIndex
      ].deleted = false;
      this.setDefaultView();
    },
    deleteItem() {
      this.value.items[this.activeWoItemIndex].tasks[
        this.activeItemIndex
      ].deleted = true;
      this.setDefaultView();
      this.$emit("change");
    },
    deleteAllItem() {
      this.value.items[this.activeWoItemIndex].tasks.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].tasks.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].tasks[
          this.activeItemIndex
        ].isDirty = true;
        window.$gz.form.fieldValueChanged(this.pvm, ref);
      }
    },
    itemRowClasses: function(item) {
      let ret = "";
      const isDeleted =
        this.value.items[this.activeWoItemIndex].tasks[item.index].deleted ===
        true;

      const hasError = this.form().childRowHasError(
        this,
        `Items[${this.activeWoItemIndex}].Tasks[${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].tasks[this.activeItemIndex] ==
        null
      ) {
        this.setDefaultView();
        return true;
      }
      return (
        this.value.items[this.activeWoItemIndex].tasks[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, "WorkOrderItemTaskSequence")) {
        headers.push({
          text: this.$ay.t("Sequence"),
          align: "left",
          value: "sequence"
        });
      }

      if (this.form().showMe(this, "WorkOrderItemTaskTaskID")) {
        headers.push({
          text: this.$ay.t("WorkOrderItemTaskTaskID"),
          align: "start",
          value: "task"
        });
      }

      if (this.form().showMe(this, "WorkOrderItemTaskUser")) {
        headers.push({
          text: this.$ay.t("WorkOrderItemTaskUser"),
          align: "start",
          value: "completedByUserViz"
        });
      }

      if (
        this.form().showMe(
          this,
          "WorkOrderItemTaskWorkOrderItemTaskCompletionType"
        )
      ) {
        headers.push({
          text: this.$ay.t("WorkOrderItemTaskWorkOrderItemTaskCompletionType"),
          align: "start",
          value: "statusViz"
        });
      }

      if (this.form().showMe(this, "WorkOrderItemTaskCompletedDate")) {
        headers.push({
          text: this.$ay.t("WorkOrderItemTaskCompletedDate"),
          align: "right",
          value: "completedDate"
        });
      }
      return headers;
    },
    itemList: function() {
      return this.value.items[this.activeWoItemIndex].tasks
        .map((x, i) => {
          return {
            index: i,
            id: x.id,
            sequence: x.sequence,
            task: x.task,
            completedByUserViz: x.completedByUserViz,
            statusViz: x.statusViz,
            completedDate: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
              x.completedDate,
              this.pvm.timeZoneName,
              this.pvm.languageName,
              this.pvm.hour12
            )
          };
        })
        .sort((a, b) => a.sequence - b.sequence);
    },
    formState: function() {
      return this.pvm.formState;
    },
    formCustomTemplateKey: function() {
      return this.pvm.formCustomTemplateKey;
    },
    hasData: function() {
      return this.value.items[this.activeWoItemIndex].tasks.length > 0;
    },
    hasSelection: function() {
      return this.activeItemIndex != null;
    },
    canAdd: function() {
      return this.pvm.rights.change && this.pvm.subRights.tasks.create;
    },
    canDelete: function() {
      return this.activeItemIndex != null && this.canDeleteAll;
    },
    canDeleteAll: function() {
      return this.pvm.rights.change && this.pvm.subRights.tasks.delete;
    }
  }
};
</script>
