<template>
  <div>
    <gz-report-selector ref="reportSelector"></gz-report-selector>
    <div v-if="formState.ready">
      <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
      <v-form ref="form">
        <v-row>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              v-model="obj.name"
              :readonly="formState.readOnly"
              :label="$ay.t('TaskGroupName')"
              :rules="[form().required(this, 'name')]"
              :error-messages="form().serverErrors(this, 'name')"
              ref="name"
              data-cy="name"
              @input="fieldValueChanged('name')"
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-checkbox
              v-model="obj.active"
              :readonly="formState.readOnly"
              :label="$ay.t('Active')"
              ref="active"
              data-cy="active"
              :error-messages="form().serverErrors(this, 'active')"
              @change="fieldValueChanged('active')"
            ></v-checkbox>
          </v-col>
          <v-col cols="12" class="mb-10">
            <span class="text-subtitle-2"> {{ $ay.t("TaskList") }}</span
            ><v-btn v-if="!formState.readOnly" large icon @click="addItem()">
              <v-icon small color="primary">$ayiPlus</v-icon>
            </v-btn>

            <v-simple-table>
              <template v-slot:default>
                <thead>
                  <tr>
                    <th class="text-left">
                      {{ $ay.t("Task") }}
                    </th>
                    <th class="text-right">
                      {{ $ay.t("Sequence") }}
                    </th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="item in itemList"
                    :key="item.Id"
                    :class="
                      form().childRowErrorClass(thisVm(), 'Items', item.index)
                    "
                  >
                    <td class="text-left">
                      {{ item.task }}
                    </td>
                    <th class="text-right">
                      {{ $ay.dec(item.sequence) }}
                    </th>

                    <td class="text-right">
                      <v-btn
                        v-if="!formState.readOnly"
                        large
                        icon
                        @click="editItem(item.index)"
                        class="ml-4"
                      >
                        <v-icon small>
                          $ayiEdit
                        </v-icon>
                      </v-btn>
                    </td>
                  </tr>
                </tbody>
              </template>
            </v-simple-table>
          </v-col>
          <!------------------------------------->
          <v-col cols="12">
            <v-textarea
              v-model="obj.notes"
              :readonly="formState.readOnly"
              :label="$ay.t('TaskGroupNotes')"
              :error-messages="form().serverErrors(this, 'notes')"
              ref="notes"
              data-cy="notes"
              @input="fieldValueChanged('notes')"
              auto-grow
            ></v-textarea>
          </v-col>
        </v-row>
      </v-form>
    </div>
    <v-overlay :value="!formState.ready || formState.loading">
      <v-progress-circular indeterminate :size="64" />
    </v-overlay>
    <!-- #########################################################################################################-->
    <!-- ##########################  ITEM EDIT FORM  ###############################-->
    <!-- #########################################################################################################-->
    <template v-if="obj.items.length && editItemIndex != -1">
      <v-row justify="center">
        <v-dialog v-model="editItemDialog">
          <v-card>
            <v-card-title> </v-card-title>
            <v-card-text>
              <v-row>
                <v-col cols="12">
                  <v-textarea
                    v-model="obj.items[editItemIndex].task"
                    :readonly="formState.readOnly"
                    :label="$ay.t('Task')"
                    :error-messages="
                      form().serverErrors(this, `Items[${editItemIndex}].task`)
                    "
                    @input="fieldValueChanged(`Items[${editItemIndex}].task`)"
                    ref="task"
                    data-cy="task"
                    auto-grow
                  ></v-textarea>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-text-field
                    v-model="obj.items[editItemIndex].sequence"
                    :readonly="formState.readOnly"
                    :label="$ay.t('Sequence')"
                    ref="Items.sequence"
                    data-cy="Items.sequence"
                    :rules="[
                      form().integerValid(this, 'Items.sequence'),
                      form().required(this, 'Items.sequence')
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `Items[${editItemIndex}].sequence`
                      )
                    "
                    @input="
                      fieldValueChanged(`Items[${editItemIndex}].sequence`)
                    "
                    type="number"
                  ></v-text-field>
                </v-col>
              </v-row>
            </v-card-text>
            <v-card-actions>
              <template v-if="!$vuetify.breakpoint.xs">
                <v-btn color="red darken-1" text @click="deleteItem()">{{
                  $ay.t("Delete")
                }}</v-btn>
                <v-spacer></v-spacer>

                <v-btn
                  color="blue darken-1"
                  text
                  @click="addItem()"
                  class="ml-4"
                  >{{ $ay.t("New") }}</v-btn
                >

                <v-btn
                  color="blue darken-1"
                  text
                  @click="editItemDialog = false"
                  class="ml-4"
                  >{{ $ay.t("OK") }}</v-btn
                >
              </template>
              <template v-else>
                <!-- MOBILE FORMAT -->
                <v-row>
                  <v-btn
                    class="mt-4"
                    block
                    text
                    color="blue darken-1"
                    @click="editItemDialog = false"
                    >{{ $ay.t("OK") }}</v-btn
                  >
                  <v-btn
                    class="mt-4"
                    block
                    text
                    color="blue darken-1"
                    @click="addItem()"
                    >{{ $ay.t("New") }}</v-btn
                  >

                  <v-btn
                    class="mt-8 mb-6"
                    block
                    text
                    color="red darken-1"
                    @click="deleteItem()"
                    >{{ $ay.t("Delete") }}</v-btn
                  >
                </v-row>
              </template>
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-row>
    </template>
  </div>
</template>
<script>
const FORM_KEY = "svc-task-group-edit";
const API_BASE_URL = "task-group/";
export default {
  async created() {
    const vm = this;
    try {
      await initForm(vm);
      vm.rights = window.$gz.role.getRights(
        window.$gz.type.WorkOrderItemStatus
      );
      vm.formState.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      //id 0 means create or duplicate to new
      if (vm.$route.params.recordid != 0) {
        //is there already an obj from a prior operation?
        if (this.$route.params.obj) {
          //yes, no need to fetch it
          this.obj = this.$route.params.obj;
          window.$gz.form.setFormState({
            vm: vm,
            loading: false
          });
        } else {
          await vm.getDataFromApi(vm.$route.params.recordid);
        }
      } else {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
      window.$gz.form.setFormState({
        vm: vm,
        dirty: false,
        valid: true
      });

      generateMenu(vm);
    } catch (error) {
      window.$gz.errorHandler.handleFormError(error, vm);
    } finally {
      vm.formState.ready = true;
    }
  },
  async beforeRouteLeave(to, from, next) {
    if (!this.formState.dirty || JUST_DELETED) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  data() {
    return {
      obj: {
        id: 0,
        concurrency: 0,
        name: null,
        active: true,
        notes: null,
        items: []
      },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject(),
      ayaType: window.$gz.type.TaskGroup,
      selectedItem: null,
      editItemDialog: false,
      editItemIndex: 0
    };
  },
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }

        if (val.dirty && val.valid && !val.readOnly) {
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
        } else {
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
        }

        if (!val.dirty && val.valid && !val.readOnly) {
          window.$gz.eventBus.$emit(
            "menu-enable-item",
            FORM_KEY + ":duplicate"
          );
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":new");
        } else {
          window.$gz.eventBus.$emit(
            "menu-disable-item",
            FORM_KEY + ":duplicate"
          );
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":new");
        }
      },
      deep: true
    }
  },
  methods: {
    addItem: function() {
      const newIndex = this.obj.items.length;
      this.editItemIndex =
        this.obj.items.push({
          id: 0,
          taskGroupId: this.obj.id,
          sequence: newIndex + 1, //indexes are zero based but sequences are visible to user so 1 based
          task: null
        }) - 1;

      this.editItemDialog = true;
      this.formState.dirty = true;
    },
    editItem: function(index) {
      this.editItemIndex = index;
      this.editItemDialog = true;
    },
    deleteItem: function() {
      this.editItemDialog = false;
      this.obj.items.splice(this.editItemIndex, 1);
      this.editItemIndex = -1;
      this.formState.dirty = true;
    },
    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    },
    canDuplicate: function() {
      return this.formState.valid && !this.formState.dirty;
    },

    form() {
      return window.$gz.form;
    },
    thisVm() {
      return this;
    },
    fieldValueChanged(ref) {
      if (
        this.formState.ready &&
        !this.formState.loading &&
        !this.formState.readOnly
      ) {
        //This was necessary because for some reason the color control was triggering field value changed *before* the form reference was set
        //which is strange but this resolve it
        if (this.$refs.form) {
          window.$gz.form.fieldValueChanged(this, ref);
        }
      }
    },
    async getDataFromApi(recordId) {
      const vm = this;
      window.$gz.form.setFormState({
        vm: vm,
        loading: true
      });
      if (!recordId) {
        throw new Error(FORM_KEY + "::getDataFromApi -> Missing recordID!");
      }
      try {
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const res = await window.$gz.api.get(API_BASE_URL + recordId);
        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj = res.data;
          generateMenu(vm);
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    },
    async submit() {
      const vm = this;
      if (vm.canSave == false) {
        return;
      }

      try {
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const res = await window.$gz.api.upsert(API_BASE_URL, vm.obj);
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          if (res.data.id) {
            //POST
            vm.obj = res.data;
            this.$router.replace({
              name: "svc-task-group",
              params: {
                recordid: res.data.id,
                obj: res.data
              }
            });
          } else {
            //PUT
            vm.obj.concurrency = res.data.concurrency;
          }

          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true
          });
        }
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    },
    async remove() {
      try {
        const dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }

        window.$gz.form.setFormState({
          vm: this,
          loading: true
        });

        if (this.$route.params.recordid == 0) {
          JUST_DELETED = true;

          this.$router.go(-1);
        } else {
          window.$gz.form.deleteAllErrorBoxErrors(this);
          const res = await window.$gz.api.remove(
            API_BASE_URL + this.$route.params.recordid
          );
          if (res.error) {
            this.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(this);
          } else {
            JUST_DELETED = true;
            this.$router.go(-1);
          }
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, this);
      } finally {
        window.$gz.form.setFormState({
          vm: this,
          loading: false
        });
      }
    }
  },
  computed: {
    itemList: function() {
      return this.obj.items
        .map((x, i) => {
          return {
            index: i,
            id: x.id,
            sequence: x.sequence,
            task: x.task
          };
        })
        .sort((a, b) => a.sequence - b.sequence);
    }
  }
};

/////////////////////////////
//
//
async function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "save":
        m.vm.submit();
        break;
      case "delete":
        m.vm.remove();
        break;
      case "list":
        m.vm.$router.push({
          name: "svc-task-groups"
        });
        break;
      case "report":
        const res = await m.vm.$refs.reportSelector.open(
          {
            AType: window.$gz.type.TaskGroup,
            selectedRowIds: [m.vm.obj.id]
          },
          m.id
        );
        if (res == null) {
          return;
        }
        window.$gz.form.setLastReport(FORM_KEY, res);
        generateMenu(m.vm);
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  const menuOptions = {
    isMain: false,
    readOnly: vm.formState.readOnly,
    icon: "$ayiTasks",
    title: "TaskGroup",
    helpUrl: "svc-task-groups",
    formData: {
      ayaType: window.$gz.type.TaskGroup,
      recordId: vm.$route.params.recordid,
      recordName: vm.obj.name
    },
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "Save",
      icon: "$ayiSave",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });
  }

  if (
    vm.rights.delete &&
    vm.$route.params.recordid != 0 &&
    !vm.formState.readOnly
  ) {
    menuOptions.menuItems.push({
      title: "Delete",
      icon: "$ayiTrashAlt",
      surface: false,
      key: FORM_KEY + ":delete",
      vm: vm
    });
  }

  menuOptions.menuItems.push({
    title: "Report",
    icon: "$ayiFileAlt",
    key: FORM_KEY + ":report",
    vm: vm
  });

  const lastReport = window.$gz.form.getLastReport(FORM_KEY);
  if (lastReport != null) {
    menuOptions.menuItems.push({
      title: lastReport.name,
      notrans: true,
      icon: "$ayiFileAlt",
      key: FORM_KEY + ":report:" + lastReport.id,
      vm: vm
    });
  }

  menuOptions.menuItems.push({ divider: true, inset: false });

  menuOptions.menuItems.push({
    title: "TaskGroupList",
    icon: "$ayiTasks",
    key: FORM_KEY + ":list",
    vm: vm
  });

  menuOptions.menuItems.push({ divider: true, inset: false });

  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

let JUST_DELETED = false;

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText();
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "TaskGroupName",
    "TaskGroupNotes",
    "Task",
    "TaskList",
    "Sequence",
    "TaskGroupList"
  ]);
}
</script>
