<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"
                >$ayiUserClock</v-icon
              >
              {{ $ay.t("WorkOrderItemScheduledUserList") }}
              <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="hasSelection && !formState.readOnly"
              @click="convertToLabor"
            >
              <v-list-item-icon>
                <v-icon>$ayiHammer</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{
                $ay.t("WorkOrderConvertScheduledUserToLabor")
              }}</v-list-item-title>
            </v-list-item>
            <v-list-item
              v-if="!formState.readOnly && hasMultipleItems"
              @click="convertAllToLabor"
            >
              <v-list-item-icon>
                <v-icon>$ayiHammer</v-icon>
              </v-list-item-icon>
              <v-list-item-title>{{
                $ay.t("WorkOrderConvertAllScheduledUsersToLabor")
              }}</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">
        <!-- ################################ SCHEDULED USERS TABLE ############################### -->
        <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="scheduledUsersTable"
            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="scheduledusertopform"></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, 'WorkOrderItemScheduledUserStartDate')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-date-time-picker
            :ref="
              `Items[${activeWoItemIndex}].scheduledUsers[${activeItemIndex}].startDate`
            "
            v-model="
              value.items[activeWoItemIndex].scheduledUsers[activeItemIndex]
                .startDate
            "
            :label="$ay.t('WorkOrderItemScheduledUserStartDate')"
            :readonly="formState.readOnly || value.userIsRestrictedType"
            :disabled="isDeleted"
            data-cy="startDate"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].scheduledUsers[${activeItemIndex}].startDate`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].scheduledUsers[${activeItemIndex}].startDate`
              )
            "
          ></gz-date-time-picker>
        </v-col>

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

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

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

        <v-col
          v-if="form().showMe(this, 'WorkOrderItemScheduledUserServiceRateID')"
          cols="12"
          sm="6"
          lg="4"
          xl="3"
        >
          <gz-pick-list
            :ref="
              `Items[${activeWoItemIndex}].scheduledUsers[${activeItemIndex}].serviceRateId`
            "
            v-model="
              value.items[activeWoItemIndex].scheduledUsers[activeItemIndex]
                .serviceRateId
            "
            :aya-type="$ay.ayt().ServiceRate"
            :variant="'contractid:' + value.contractId"
            :show-edit-icon="!value.userIsRestrictedType"
            :readonly="
              formState.readOnly || isDeleted || value.userIsRestrictedType
            "
            :disabled="isDeleted"
            :label="$ay.t('WorkOrderItemScheduledUserServiceRateID')"
            data-cy="scheduledUsers.serviceRateId"
            :error-messages="
              form().serverErrors(
                this,
                `Items[${activeWoItemIndex}].scheduledUsers[${activeItemIndex}].serviceRateID`
              )
            "
            @input="
              fieldValueChanged(
                `Items[${activeWoItemIndex}].scheduledUsers[${activeItemIndex}].serviceRateId`
              )
            "
            @update:name="rateChange"
          ></gz-pick-list>
        </v-col>
      </template>
    </v-row>
  </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: []
    };
  },
  computed: {
    isDeleted: function() {
      if (
        this.value.items[this.activeWoItemIndex].scheduledUsers[
          this.activeItemIndex
        ] == null
      ) {
        this.setDefaultView();
        return true;
      }
      return (
        this.value.items[this.activeWoItemIndex].scheduledUsers[
          this.activeItemIndex
        ].deleted === true
      );
    },
    parentDeleted: function() {
      return this.value.items[this.activeWoItemIndex].deleted === true;
    },

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

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

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

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

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

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

      return headers;
    },
    itemList: function() {
      return this.value.items[this.activeWoItemIndex].scheduledUsers.map(
        (x, i) => {
          return {
            index: i,
            id: x.id,
            startDate: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
              x.startDate,
              this.pvm.timeZoneName,
              this.pvm.languageName,
              this.pvm.hour12
            ),
            stopDate: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
              x.stopDate,
              this.pvm.timeZoneName,
              this.pvm.languageName,
              this.pvm.hour12
            ),
            estimatedQuantity: window.$gz.locale.decimalLocalized(
              x.estimatedQuantity,
              this.pvm.languageName
            ),
            userViz: x.userViz,
            serviceRateViz: x.serviceRateViz
          };
        }
      );
    },
    formState: function() {
      return this.pvm.formState;
    },
    formCustomTemplateKey: function() {
      return this.pvm.formCustomTemplateKey;
    },
    hasData: function() {
      return this.value.items[this.activeWoItemIndex].scheduledUsers.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;
    },
    hasMultipleItems: function() {
      return this.value.items[this.activeWoItemIndex].scheduledUsers.length > 1;
    }
  },
  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.scheduledusertopform;
          if (el) {
            el.scrollIntoView({ behavior: "smooth" });
          }
        });
      }
    }
  },
  created() {
    this.setDefaultView();
  },
  methods: {
    convertAllToLabor() {
      this.value.items[this.activeWoItemIndex].scheduledUsers.forEach(z => {
        this.doConvertToLabor(z);
      });
    },
    convertToLabor() {
      this.doConvertToLabor(
        this.value.items[this.activeWoItemIndex].scheduledUsers[
          this.activeItemIndex
        ]
      );
    },
    doConvertToLabor(s) {
      this.value.items[this.activeWoItemIndex].labors.push({
        id: 0,
        concurrency: 0,
        userId: s.userId,
        serviceStartDate: s.startDate,
        serviceStopDate: s.stopDate,
        serviceRateId: s.serviceRateId,
        serviceDetails: null,
        serviceRateQuantity: s.estimatedQuantity,
        noChargeQuantity: 0,
        taxCodeSaleId:
          window.$gz.store.state.globalSettings.defaultTaxRateSaleId,
        price: 0,
        priceOverride: null,
        isDirty: true,
        quoteItemId: this.value.items[this.activeWoItemIndex].id,
        uid: Date.now(),
        userViz: s.userViz,
        serviceRateViz: s.serviceRateViz,
        taxCodeViz: null
      });
      this.$emit("change");
    },
    userChange(newName) {
      this.value.items[this.activeWoItemIndex].scheduledUsers[
        this.activeItemIndex
      ].userViz = newName;
    },
    rateChange(newName) {
      this.value.items[this.activeWoItemIndex].scheduledUsers[
        this.activeItemIndex
      ].serviceRateViz = newName;
    },
    newItem() {
      const newIndex = this.value.items[this.activeWoItemIndex].scheduledUsers
        .length;

      this.value.items[this.activeWoItemIndex].scheduledUsers.push({
        id: 0,
        concurrency: 0,
        userId: this.$store.getters.isScheduleableUser
          ? this.$store.state.userId
          : null,
        estimatedQuantity: 0,
        startDate: null,
        stopDate: null,
        serviceRateId: null,
        isDirty: true,
        quoteItemId: this.value.items[this.activeWoItemIndex].id,
        uid: Date.now(),
        userViz: this.$store.getters.isScheduleableUser
          ? this.$store.state.userName
          : null,
        serviceRateViz: null
      });
      this.$emit("change");
      this.selectedRow = [{ index: newIndex }];
      this.activeItemIndex = newIndex;
      return newIndex; //for create new on goto
    },
    unDeleteItem() {
      this.value.items[this.activeWoItemIndex].scheduledUsers[
        this.activeItemIndex
      ].deleted = false;
      this.setDefaultView();
    },
    deleteItem() {
      this.value.items[this.activeWoItemIndex].scheduledUsers[
        this.activeItemIndex
      ].deleted = true;
      this.setDefaultView();
      this.$emit("change");
    },
    deleteAllItem() {
      this.value.items[this.activeWoItemIndex].scheduledUsers.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].scheduledUsers.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].scheduledUsers[
          this.activeItemIndex
        ].isDirty = true;
        window.$gz.form.fieldValueChanged(this.pvm, ref);
        //------- SPECIAL HANDLING OF CHANGES -----------
        const isNew =
          this.value.items[this.activeWoItemIndex].scheduledUsers[
            this.activeItemIndex
          ].id == 0;

        //Auto calculate dates / quantities / global defaults
        const dStart = this.value.items[this.activeWoItemIndex].scheduledUsers[
          this.activeItemIndex
        ].startDate;
        const dStop = this.value.items[this.activeWoItemIndex].scheduledUsers[
          this.activeItemIndex
        ].stopDate;
        if (ref.includes("startDate") && dStart != null) {
          this.handleStartDateChange(isNew, dStart, dStop);
        }
        if (ref.includes("stopDate") && dStop != null) {
          this.handleStopDateChange(isNew, dStart, dStop);
        }
        //------------------------------------------------------
      }
    },
    handleStartDateChange: function(isNew, dStart, dStop) {
      const globalMinutes =
        window.$gz.store.state.globalSettings.workLaborScheduleDefaultMinutes;

      if (isNew) {
        if (globalMinutes != 0) {
          dStop = window.$gz.locale.addMinutesToUTC8601String(
            dStart,
            globalMinutes
          );
          //set stop date based on start date and global minutes
          this.value.items[this.activeWoItemIndex].scheduledUsers[
            this.activeItemIndex
          ].stopDate = dStop;
        }
      }
      {
        //Existing record or both dates filled, just update quantity
        if (dStop != null) {
          this.value.items[this.activeWoItemIndex].scheduledUsers[
            this.activeItemIndex
          ].estimatedQuantity = window.$gz.locale.diffHoursFromUTC8601String(
            dStart,
            dStop
          );
        }
      }
    },
    handleStopDateChange: function(isNew, dStart, dStop) {
      const globalMinutes =
        window.$gz.store.state.globalSettings.workLaborScheduleDefaultMinutes;

      if (isNew && dStart == null) {
        if (globalMinutes != 0) {
          dStart = window.$gz.locale.addMinutesToUTC8601String(
            dStop,
            0 - globalMinutes
          );
          //set start date based on stop date and global minutes
          this.value.items[this.activeWoItemIndex].scheduledUsers[
            this.activeItemIndex
          ].startDate = dStart;
        }
      }
      {
        //Existing record or both dates filled, just update quantity
        if (dStart != null) {
          this.value.items[this.activeWoItemIndex].scheduledUsers[
            this.activeItemIndex
          ].estimatedQuantity = window.$gz.locale.diffHoursFromUTC8601String(
            dStart,
            dStop
          );
        }
      }
    },
    itemRowClasses: function(item) {
      let ret = "";
      const isDeleted =
        this.value.items[this.activeWoItemIndex].scheduledUsers[item.index]
          .deleted === true;

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

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