<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>
            <v-col cols="12">
              <v-select
                v-model="templateId"
                :items="selectLists.pickListTemplates"
                item-text="name"
                item-value="id"
                :label="t('PickListTemplates')"
                @input="templateSelected"
              >
              </v-select>
            </v-col>
            template:
            {{ obj }}

            available fields:
            {{ availableFields }}
            <!-- <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-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 = "adm-global-select-templates";
const API_BASE_URL = "PickList/Template/";
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: {
        id: null,
        concurrencyToken: null,
        template: null
      },
      selectLists: {
        pickListTemplates: []
      },
      availableFields: [],
      workingArray: [],
      templateId: 0,
      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(ltkey) {
      return window.$gz.translation.get(ltkey);
    },
    templateSelected: function() {
      if (this.formState.dirty) {
        window.$gz.dialog.confirmLeaveUnsaved().then(dialogResult => {
          if (dialogResult != true) {
            return;
          }
        });
      }
      this.getDataFromApi();
    },
    getDataFromApi() {
      //COP*IED FROM WIDGET TO BE MODIFIED
      var vm = this;
      vm.formState.loading = true;
      if (!vm.templateId || vm.templateId == 0) {
        return;
      }

      window.$gz.form.deleteAllErrorBoxErrors(vm);

      //get available fields
      window.$gz.api
        .get(API_BASE_URL + "ListFields/" + vm.templateId)
        .then(res => {
          if (res.error != undefined) {
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          } else {
            vm.availableFields = res.data;
          }
        })
        .then(
          //get current edited template
          window.$gz.api.get(API_BASE_URL + vm.templateId).then(res => {
            if (res.error != undefined) {
              vm.formState.serverError = res.error;
              window.$gz.form.setErrorBoxErrors(vm);
            } else {
              vm.obj = res.data;

              //TODO: Here need to set workingArray to a synthesis of the active template, and available fields so it reflects the current state and provides the extra fields
              //then modify form so it uses workingArray to display like custom etc.  note if has rowId is required and must be included=true

              //Update the form status
              window.$gz.form.setFormState({
                vm: vm,
                dirty: false,
                valid: true,
                loading: false,
                readOnly: res.readOnly ? true : false
              });
            }
          })
        )
        .catch(function handleGetDataFromAPIError(error) {
          //Update the form status
          window.$gz.form.setFormState({
            vm: vm,
            loading: false
          });
          window.$gz.errorHandler.handleFormError(error, vm);
        });
    },
    submit() {
      //COPIED FROM CUSTOM TO BE MODIFIED
      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 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: null,
    title: window.$gz.translation.get("PickListTemplates"),
    helpUrl: "form-adm-global-select-templates",
    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
    });
  }

  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);
      } catch (err) {
        reject(err);
      }
      resolve();
    })();
  });
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
function fetchTranslatedText(vm) {
  var ltKeysRequired = ["Include"];

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

//////////////////////
//
//
function populateSelectionLists(vm) {
  return window.$gz.api.get(API_BASE_URL + "List").then(res => {
    if (res.error != undefined) {
      window.$gz.errorHandler.handleFormError(res.error, vm);
    } else {
      vm.selectLists.pickListTemplates = res.data;
      window.$gz.form.addNoSelectionItem(vm.selectLists.pickListTemplates);
    }
  });
}
</script>
