<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.serial"
              readonly
              :label="$ay.t('WorkOrderSerialNumber')"
              data-cy="serial"
            ></v-text-field>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              v-model="obj.customerViz"
              readonly
              :label="$ay.t('Customer')"
              data-cy="customerViz"
            ></v-text-field>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              v-model="obj.customerReferenceNumber"
              readonly
              :label="$ay.t('WorkOrderCustomerReferenceNumber')"
              data-cy="customerReferenceNumber"
            ></v-text-field>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              v-model="obj.customerContactName"
              readonly
              :label="$ay.t('WorkOrderCustomerContactName')"
              data-cy="customerContactName"
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              v-model="obj.invoiceNumber"
              readonly
              :label="$ay.t('WorkOrderInvoiceNumber')"
              data-cy="invoiceNumber"
            ></v-text-field>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-date-time-picker
              :label="$ay.t('WorkOrderServiceDate')"
              v-model="obj.serviceDate"
              readonly
              data-cy="serviceDate"
            ></gz-date-time-picker>
          </v-col>
          <v-col v-if="obj.canWiki" cols="12">
            <gz-wiki
              :aya-type="ayaType"
              :aya-id="obj.id"
              ref="wiki"
              v-model="obj.wiki"
              readonly
              data-cy="wiki"
            ></gz-wiki
          ></v-col>

          <v-col v-if="obj.canAttachments" cols="12">
            <gz-attachments
              readonly
              :aya-type="ayaType"
              :aya-id="obj.id"
              data-cy="attachments"
            ></gz-attachments
          ></v-col>
        </v-row>
      </v-form>
    </div>
    <v-overlay :value="!formState.ready || formState.loading">
      <v-progress-circular indeterminate :size="64" />
    </v-overlay>
  </div>
</template>

<script>
const FORM_KEY = "customer-workorder";
const API_BASE_URL = "workorder/customer/";
export default {
  async created() {
    const vm = this;

    try {
      await initForm();
      vm.formState.readOnly = true;
      window.$gz.eventBus.$on("menu-click", clickHandler);

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

      // generateMenu(vm);
      await vm.getDataFromApi(vm.$route.params.recordid);
    } catch (error) {
      window.$gz.errorHandler.handleFormError(error, vm);
    } finally {
      vm.formState.ready = true;
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  data() {
    return {
      obj: {
        id: 0,
        serial: 0,
        wiki: null,
        customerId: 0,
        customerViz: null,
        customerReferenceNumber: null,
        customerContactName: null,
        serviceDate: null,
        invoiceNumber: null,
        canWiki: false,
        canAttachments: false
      },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: true,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.readOnlyRightsObject(),
      ayaType: window.$gz.type.WorkOrder
    };
  },

  methods: {
    ayaTypes: function() {
      return window.$gz.type;
    },
    form() {
      return window.$gz.form;
    },
    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
          });
          vm.formState.readOnly = !vm.rights.change || vm.obj.status != 0;
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    }
  }
};

/////////////////////////////
//
//
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 "report":
        try {
          const res = await m.vm.$refs.reportSelector.open(
            {
              AType: window.$gz.type.WorkOrder,
              selectedRowIds: [m.vm.obj.id]
            },
            -100 //special code meaning customer workorder report which will be looked up at server
          );

          if (res == null) {
            return;
          }
        } catch (err) {
          window.$gz.errorHandler.handleFormError(err, 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: "$ayiTools",
    title: "WorkOrder",
    helpUrl: "customer-workorders",
    hideSearch: true,
    menuItems: []
  };

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

  menuOptions.menuItems.push({ divider: true, inset: false });
  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

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

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([]);
}
</script>
