<template>
  <v-container>
    <v-row v-if="formState.ready">
      <v-col>
        <v-form ref="form">
          <v-row>
            <v-col cols="12" mt-1 mb-2>
              <v-alert
                ref="errorbox"
                v-show="formState.errorBoxMessage"
                color="error"
                icon="fa-exclamation-circle "
                transition="scale-transition"
                class="multi-line"
                outlined
                >{{ formState.errorBoxMessage }}</v-alert
              >
            </v-col>

            <template v-for="item in obj">
              <v-col :key="item.key" cols="12" sm="6" lg="4" xl="3" px-2>
                <v-card>
                  <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="t('FormFieldVisible')"
                      :ref="item.key"
                      :disabled="item.stockRequired"
                      @change="visibleChanged(item)"
                    ></v-checkbox>
                    <v-checkbox
                      v-model="item.required"
                      :readOnly="formState.readOnly"
                      :label="t('FormFieldEntryRequired')"
                      :disabled="item.stockRequired"
                      @change="requiredChanged(item)"
                    ></v-checkbox>
                    <v-select
                      v-if="item.custom"
                      v-model="item.type"
                      :readOnly="formState.readOnly"
                      :items="selectLists.uiFieldDataTypes"
                      item-text="name"
                      item-value="id"
                      :label="t('UiFieldDataType')"
                      @input="dataTypeChanged(item)"
                    ></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>
  </v-container>
</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 = "FormCustom/";
export default {
  beforeRouteLeave(to, from, next) {
    //var vm = this;
    if (this.formState.dirty) {
      window.$gz.dialog.confirmLeaveUnsaved().then(dialogResult => {
        if (dialogResult == true) {
          next();
        } else {
          next(false);
        }
      });
    } else {
      next();
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  created() {
    var vm = this;

    initForm(vm)
      .then(() => {
        vm.formState.ready = true;
        vm.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 => {
        vm.formState.ready = true;
        window.$gz.errorHandler.handleFormError(err, vm);
      });
  },
  data() {
    return {
      obj: [],
      concurrencyToken: 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)
    };
  },

  methods: {
    t: function(tKey) {
      return window.$gz.translation.get(tKey);
    },
    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;
      enableSaveButton();
    },
    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;
      enableSaveButton();
    },
    dataTypeChanged: function(item) {
      //nothing to scan here just set form dirty
      this.formState.dirty = true;
      enableSaveButton();
    },
    submit() {
      var vm = this;
      var 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
      var newObj = {
        formKey: vm.formCustomTemplateKey,
        concurrencyToken: vm.concurrencyToken,
        template: "[]"
      };
      //temporary array to hold template for later stringification
      var temp = [];
      //Rules:
      for (var i = 0; i < vm.obj.length; i++) {
        var 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
            });
          }
        }
      }

      //now set the template as a json string
      newObj.template = JSON.stringify(temp);

      window.$gz.api
        .upsert(url, newObj)
        .then(res => {
          vm.formState.loading = false;
          if (res.error != undefined) {
            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.concurrencyToken,
              newObj.template
            );
            //set our local concurrency token value
            vm.concurrencyToken = res.data.concurrencyToken;

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

function enableSaveButton() {
  window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
}

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  var 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) {
  var menuOptions = {
    isMain: false,
    icon: "fa-sliders-h",
    title: window.$gz.translation.get("Customize"),
    helpUrl: "form-ay-customize",
    formData: {
      ayaType: window.$gz.type.FormCustom,
      formCustomTemplateKey: undefined
    },
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: window.$gz.translation.get("Save"),
      icon: "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: window.$gz.translation.get("Translation"),
    icon: "language",
    data: "adm-translation",
    key: "app:nav"
  });

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

/////////////////////////////////
//
//
function initForm(vm) {
  return new Promise(function(resolve, reject) {
    (async function() {
      try {
        await fetchTranslatedText(vm);
        await populateSelectionLists(vm);
        await ensureTemplateIsInStore(vm);
        await initDataObject(vm);
      } catch (err) {
        reject(err);
      }
      resolve();
    })();
  });
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
function fetchTranslatedText(vm) {
  var tKeysRequired = [
    "FormFieldEntryRequired",
    "FormFieldVisible",
    "UiFieldDataType",
    "UiFieldDataTypesCurrency",
    "UiFieldDataTypesDateOnly",
    "UiFieldDataTypesDateTime",
    "UiFieldDataTypesDecimal",
    "UiFieldDataTypesInteger",
    "UiFieldDataTypesText",
    "UiFieldDataTypesTimeOnly",
    "UiFieldDataTypesTrueFalse"
  ];

  return window.$gz.translation.fetch(tKeysRequired);
}

/////////////////////////////////
//
//
function populateSelectionLists(vm) {
  vm.selectLists.uiFieldDataTypes.push(
    ...[
      { name: vm.t("UiFieldDataTypesDateTime"), id: 1 },
      { name: vm.t("UiFieldDataTypesDateOnly"), id: 2 },
      { name: vm.t("UiFieldDataTypesTimeOnly"), id: 3 },
      { name: vm.t("UiFieldDataTypesText"), id: 4 },
      { name: vm.t("UiFieldDataTypesTrueFalse"), id: 6 },
      { name: vm.t("UiFieldDataTypesInteger"), id: 5 },
      { name: vm.t("UiFieldDataTypesDecimal"), id: 7 },
      { name: vm.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
  );
}

////////////////////
//
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)
  var url = "FormFieldsDefinitions/" + vm.$route.params.formCustomTemplateKey;
  return window.$gz.api.get(url).then(res => {
    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 (var i = 0; i < res.data.length; i++) {
      //get the formAvailableField record into an object to save typing
      var faf = res.data[i];
      //get the customTemplate record for this field if it exists

      var 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
        };
      }

      var objItem = {
        key: faf.fieldKey,
        title: window.$gz.translation.get(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.concurrencyToken = window.$gz.formCustomTemplate.getTemplateConcurrencyToken(
        vm.formCustomTemplateKey
      );
    }
  });
}
</script>
