<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"
                >$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
            v-model="selectedRow"
            :headers="headerList"
            :items="itemList"
            item-key="index"
            class="elevation-1"
            disable-pagination
            disable-filtering
            disable-sort
            hide-default-footer
            data-cy="expensesTable"
            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="tasktopform"></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, 'Sequence')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <v-text-field
            :ref="
              `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].sequence`
            "
            v-model="
              value.items[activeWoItemIndex].tasks[activeItemIndex].sequence
            "
            dense
            :readonly="formState.readOnly || value.userIsRestrictedType"
            :disabled="isDeleted"
            :label="$ay.t('Sequence')"
            :rules="[
              form().integerValid(
                this,
                `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].sequence`
              )
            ]"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].sequence`
              )
            "
            type="number"
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].sequence`
              )
            "
          ></v-text-field>
        </v-col>

        <v-col
          v-if="
            form().showMe(
              this,
              'WorkOrderItemTaskWorkOrderItemTaskCompletionType'
            )
          "
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <v-select
            :ref="
              `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].status`
            "
            v-model="
              value.items[activeWoItemIndex].tasks[activeItemIndex].status
            "
            dense
            :items="pvm.selectLists.woItemTaskCompletionTypes"
            item-text="name"
            item-value="id"
            :readonly="
              formState.readOnly || isDeleted || isNotRestrictedUsersRecord
            "
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemTaskWorkOrderItemTaskCompletionType')"
            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
            :ref="
              `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].completedByUserId`
            "
            v-model="
              value.items[activeWoItemIndex].tasks[activeItemIndex]
                .completedByUserId
            "
            :aya-type="$ay.ayt().User"
            variant="tech"
            :show-edit-icon="!value.userIsRestrictedType"
            :readonly="
              formState.readOnly || isDeleted || value.userIsRestrictedType
            "
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemTaskUser')"
            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
            :ref="
              `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].completedDate`
            "
            v-model="
              value.items[activeWoItemIndex].tasks[activeItemIndex]
                .completedDate
            "
            :label="$ay.t('WorkOrderItemTaskCompletedDate')"
            :readonly="formState.readOnly || isNotRestrictedUsersRecord"
            :disabled="isDeleted"
            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
            :ref="`Items[${activeWoItemIndex}].tasks[${activeItemIndex}].task`"
            v-model="value.items[activeWoItemIndex].tasks[activeItemIndex].task"
            dense
            :readonly="formState.readOnly || value.userIsRestrictedType"
            :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`
              )
            ]"
            data-cy="task"
            auto-grow
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].tasks[${activeItemIndex}].task`
              )
            "
          ></v-textarea>
        </v-col>
      </template>
    </v-row>
    <!-- ################################################################################-->
    <!-- ##########################  GROUP SELECTOR FORM  ###############################-->
    <!-- ################################################################################-->
    <template>
      <v-row dense justify="center">
        <v-dialog v-model="taskGroupDialog" max-width="600px">
          <v-card>
            <v-card-title> </v-card-title>
            <v-card-text>
              <gz-pick-list
                ref="selectedTaskGroup"
                v-model="selectedTaskGroup"
                :aya-type="$ay.ayt().TaskGroup"
                show-edit-icon
                :label="$ay.t('TaskGroupList')"
                data-cy="selectedTaskGroup"
              ></gz-pick-list>
              <gz-pick-list
                v-model="selectedTaskGroupUser"
                :aya-type="$ay.ayt().User"
                variant="tech"
                :show-edit-icon="!value.userIsRestrictedType"
                :label="$ay.t('WorkOrderItemTaskUser')"
                @update:name="selectedTaskGroupUserChange"
              ></gz-pick-list>
            </v-card-text>
            <v-card-actions>
              <v-btn text color="primary" @click="taskGroupDialog = false">{{
                $ay.t("Cancel")
              }}</v-btn>
              <v-spacer></v-spacer>
              <v-btn
                :disabled="selectedTaskGroup == null"
                color="primary"
                text
                class="ml-4"
                @click="addTaskGroup()"
                >{{ $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
    }
  },
  data() {
    return {
      activeItemIndex: null,
      selectedRow: [],
      taskGroupDialog: false,
      selectedTaskGroup: null,
      selectedTaskGroupUser: null,
      selectedTaskGroupUserName: null
    };
  },
  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() {
      const headers = [];

      if (this.form().showMe(this, "Sequence")) {
        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.value.userIsRestrictedType;
    },
    canDelete: function() {
      return (
        this.activeItemIndex != null &&
        this.canDeleteAll &&
        !this.value.userIsRestrictedType
      );
    },
    canDeleteAll: function() {
      return this.pvm.rights.change && !this.value.userIsRestrictedType;
    },
    isNotRestrictedUsersRecord: function() {
      if (this.value.userIsRestrictedType) {
        return (
          this.value.items[this.activeWoItemIndex].tasks[this.activeItemIndex]
            .completedByUserId != this.$store.state.userId
        );
      }
      return false;
    }
  },
  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" });
          }
        });
      }
    }
  },
  created() {
    this.setDefaultView();
  },
  methods: {
    async addTaskGroup() {
      const res = await window.$gz.api.get(
        `task-group/${this.selectedTaskGroup}`
      );
      if (res.data && res.data.items) {
        //If there is one empty task line only then they likely just want to append the group and ditch the default empty item so remove it here
        if (
          this.value.items[this.activeWoItemIndex].tasks.length == 1 &&
          this.value.items[this.activeWoItemIndex].tasks[0].task == null &&
          this.value.items[this.activeWoItemIndex].tasks[0].id == 0
        ) {
          //but first need to unbreak rule from initial add empty in case it's the only broken validation rule preventing saving
          this.value.items[this.activeWoItemIndex].tasks[0].task = "..";
          this.fieldValueChanged(
            `Items[${this.activeWoItemIndex}].tasks[${this.activeItemIndex}].task`
          );
          //Now we can remove it
          this.value.items[this.activeWoItemIndex].tasks.splice(0, 1);
        }

        let newIndex = this.value.items[this.activeWoItemIndex].tasks.length;
        const 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: this.selectedTaskGroupUser,
            completedDate: null,
            isDirty: true,
            pmItemId: this.value.items[this.activeWoItemIndex].id,
            uid: Date.now(),
            completedByUserViz: this.selectedTaskGroupUserName
          });
        });
        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() {
      const 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,
        pmItemId: 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;
    },
    selectedTaskGroupUserChange(newName) {
      this.selectedTaskGroupUserName = newName;
    }
  }
};
</script>
