<template>
  <v-row v-if="formState.ready">
    <v-col>
      <v-form ref="form">
        <v-row>
          <gz-error :errorBoxMessage="formState.errorBoxMessage"></gz-error>
          <template v-for="item in obj">
            <v-col :key="item.key" cols="12" sm="6" lg="4" xl="3" px-2>
              <v-card :data-cy="!!$ay.dev ? item.key : false">
                <v-card-title>
                  {{ item.title }}
                </v-card-title>
                <v-card-subtitle>
                  {{ item.key }}
                </v-card-subtitle>
                <v-card-text>
                  <v-checkbox
                    v-model="item.visible"
                    :readonly="formState.readOnly"
                    :label="$ay.t('FormFieldVisible')"
                    :ref="item.key"
                    :disabled="item.stockRequired || formState.readOnly"
                    @change="visibleChanged(item)"
                    :data-cy="!!$ay.dev ? item.key + 'Visible' : false"
                  ></v-checkbox>
                  <v-checkbox
                    v-model="item.required"
                    :readonly="formState.readOnly"
                    :label="$ay.t('FormFieldEntryRequired')"
                    :disabled="requiredDisabled(item) || formState.readOnly"
                    @change="requiredChanged(item)"
                  ></v-checkbox>
                  <v-select
                    v-if="item.custom"
                    v-model="item.type"
                    :readonly="formState.readOnly"
                    :disabled="formState.readOnly"
                    :items="selectLists.uiFieldDataTypes"
                    item-text="name"
                    item-value="id"
                    :label="$ay.t('UiFieldDataType')"
                    @input="dataTypeChanged(item)"
                    :data-cy="!!$ay.dev ? item.key + 'SelectType' : false"
                  ></v-select>
                  <!-- <v-divider></v-divider>
                    <div>{{ item }}</div> -->
                </v-card-text>
              </v-card>
            </v-col>
          </template>
        </v-row>
      </v-form>
    </v-col>
  </v-row>
</template>
<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//NOTE: This is a simple form with no need for business rules or validation so stripped out any extraneous code related to all that
//
const FORM_KEY = "customize";
const API_BASE_URL = "form-custom/";
export default {
  async beforeRouteLeave(to, from, next) {
    if (!this.formState.dirty) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  async created() {
    let vm = this;
    try {
      await initForm(vm);

      vm.formState.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      //NOTE: this would normally be in getDataFromAPI but this form doesn't really need that function so doing it here
      //modify the menu as necessary
      generateMenu(vm, false); //default is never read only and passing in this vm
      //init disable save button so it can be enabled only on edit to show dirty form
      window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
    } catch (err) {
      window.$gz.errorHandler.handleFormError(err, vm);
    } finally {
      vm.formState.ready = true;
      vm.formState.loading = false;
    }
  },
  data() {
    return {
      enableCypress: true,
      obj: [],
      concurrency: undefined,
      formCustomTemplateKey: this.$route.params.formCustomTemplateKey,
      selectLists: {
        uiFieldDataTypes: []
      },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.getRights(window.$gz.type.FormCustom)
    };
  },
  //WATCHERS
  watch: {
    formState: {
      handler: function(val) {
        //,oldval is available here too if necessary
        if (this.formState.loading) {
          return;
        }

        //enable / disable save button
        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");
        }
      },
      deep: true
    }
  },
  methods: {
    visibleChanged: function(item) {
      //Note: stock items can't be changed so no need to take that into account
      if (item.required && item.visible == false) {
        item.required = false;
      }
      this.formState.dirty = true;
    },
    requiredChanged: function(item) {
      //Note: stock items can't be changed so no need to take that into account
      if (item.required && item.visible == false) {
        item.visible = true;
      }
      this.formState.dirty = true;
    },
    requiredDisabled: function(item) {
      if (item.stockRequired) {
        return true;
      }
      if (item.key == "Wiki" || item.key == "Attachments") {
        return true;
      }
      return false;
    },
    dataTypeChanged: function(item) {
      //nothing to scan here just set form dirty
      this.formState.dirty = true;
    },
    async submit() {
      let vm = this;

      vm.formState.loading = true;
      let url = API_BASE_URL + vm.formCustomTemplateKey;

      //clear any errors vm might be around from previous submit
      window.$gz.form.deleteAllErrorBoxErrors(vm);

      //Create template data object here....
      //Note that server expects to see a string array of json template, not actual json
      let newObj = {
        formKey: vm.formCustomTemplateKey,
        concurrency: vm.concurrency,
        template: "[]"
      };
      //temporary array to hold template for later stringification
      let temp = [];
      //Rules:
      for (let i = 0; i < vm.obj.length; i++) {
        let fldItem = vm.obj[i];
        if (fldItem.custom == false) {
          //Process regular stock field
          //If it's *not* set to stockRequired (i.e. built in field with biz rules that can't be hidden or changed)
          // and it's also set to hidden or required then it's template-worthy
          if (
            !fldItem.stockRequired &&
            (fldItem.visible == false || fldItem.required == true)
          ) {
            temp.push({
              fld: fldItem.key,
              required: fldItem.required,
              hide: !fldItem.visible
            });
          }
        } else {
          //Process custom field
          //If it's not visible then don't add it at all
          if (fldItem.visible == true) {
            temp.push({
              fld: fldItem.key,
              required: fldItem.required,
              type: fldItem.type
            });
          }
        }
      }
      try {
        //now set the template as a json string
        newObj.template = JSON.stringify(temp);
        let res = await window.$gz.api.upsert(url, newObj);
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          //Handle "put" of an existing record (UPDATE) (there is no POST of a new record for this particular object)

          //Set store values for template and token
          //(update our local cached copy of the form customizations)
          window.$gz.formCustomTemplate.set(
            vm.formCustomTemplateKey,
            res.data.concurrency,
            newObj.template
          );
          //set our local concurrency token value
          vm.concurrency = res.data.concurrency;

          //form is now clean
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false
          });
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      } finally {
        vm.formState.loading = false;
      }
    }
  }
};

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "save":
        m.vm.submit();
        break;

      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: false,
    icon: "fa-sliders-h",
    title: vm.$ay.t("Customize"),
    helpUrl: "form-ay-customize",
    formData: {
      ayaType: window.$gz.type.FormCustom,
      formCustomTemplateKey: undefined
    },
    menuItems: []
  };

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

  //Extra link to it here so people can stumble their way onto it
  //plus it's related to this form and people think Customize for the whole shebang
  menuOptions.menuItems.push({
    title: vm.$ay.t("Translation"),
    icon: "fa-language",
    data: "adm-translation",
    key: "app:nav"
  });

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

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

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText(vm) {
  //NOTE: This form expects to arrive here from the form being customized
  //so it does *not* attempt to fetch the translations for the field names of the form in question
  //since they should already be set by that form.
  await window.$gz.translation.cacheTranslations([
    "FormFieldEntryRequired",
    "FormFieldVisible",
    "UiFieldDataType",
    "UiFieldDataTypesCurrency",
    "UiFieldDataTypesDateOnly",
    "UiFieldDataTypesDateTime",
    "UiFieldDataTypesDecimal",
    "UiFieldDataTypesInteger",
    "UiFieldDataTypesText",
    "UiFieldDataTypesTimeOnly",
    "UiFieldDataTypesTrueFalse"
  ]);
}

/////////////////////////////////
//
//
function populateSelectionLists(vm) {
  vm.selectLists.uiFieldDataTypes.push(
    ...[
      { name: vm.$ay.t("UiFieldDataTypesDateTime"), id: 1 },
      { name: vm.$ay.t("UiFieldDataTypesDateOnly"), id: 2 },
      { name: vm.$ay.t("UiFieldDataTypesTimeOnly"), id: 3 },
      { name: vm.$ay.t("UiFieldDataTypesText"), id: 4 },
      { name: vm.$ay.t("UiFieldDataTypesTrueFalse"), id: 6 },
      { name: vm.$ay.t("UiFieldDataTypesInteger"), id: 5 },
      { name: vm.$ay.t("UiFieldDataTypesDecimal"), id: 7 },
      { name: vm.$ay.t("UiFieldDataTypesCurrency"), id: 8 }
    ]
  );
}

////////////////////
//
function ensureTemplateIsInStore(vm) {
  //Pre-cache if necessary the form customization settings that have been set before now

  return window.$gz.formCustomTemplate.get(
    vm.$route.params.formCustomTemplateKey
  );
}

////////////////////
//
async function initDataObject(vm) {
  //Get all the fields *available* to this form (all the fields for the object defined in AyaFormFieldDefinitions.cs as SERVER)
  //Note: this is not the actual customization data, just the list of fields that could be customized (or not if required mandatory)
  let url = "form-field-definition/" + vm.$route.params.formCustomTemplateKey;
  let res = await window.$gz.api.get(url);
  if (res.error) {
    throw res.error;
  }
  //set vm.obj to the combined synthesized snapshot array of template and availble fields for working data for this form
  //	- {key, ltdisplay, hideable, custom, required, hide, type}
  //Iterate ObjectFields
  //create a new object based on the f.a.f. item and any existing template values for that item

  for (let i = 0; i < res.data.length; i++) {
    //get the formAvailableField record into an object to save typing
    let faf = res.data[i];
    //get the customTemplate record for this field if it exists

    let templateItem = window.$gz.formCustomTemplate.getFieldTemplateValue(
      vm.formCustomTemplateKey,
      faf.fieldKey
    );

    //handle non-existent template item (expected)
    if (templateItem == null) {
      templateItem = {
        required: false,
        hide: faf.isCustomField ? true : false, //hide if custom because it's not set to display if it's not present, all others are stock fields
        type: 4 //text
      };
    }

    let objItem = {
      key: faf.fieldKey,
      title: vm.$ay.t(faf.tKey),
      stockRequired: !faf.hideable,
      custom: faf.isCustomField,
      required: faf.hideable === false || templateItem.required === true,
      visible: templateItem.hide !== true,
      type: templateItem.type
    };

    vm.obj.push(objItem);
    vm.concurrency = window.$gz.formCustomTemplate.getTemplateConcurrencyToken(
      vm.formCustomTemplateKey
    );
  }
}
</script>
