<template>
  <v-dialog
    v-model="isVisible"
    max-width="600px"
    data-cy="dataTableFilterControl"
    @keydown.esc="close()"
  >
    <v-card>
      <v-card-title>{{ tableColumnData.text }}</v-card-title>

      <v-card-text>
        <!-- FILTER CONTROL -->
        <template v-if="editItem.isFilterable">
          <div class="pt-6">
            <!-- ******** BUILDER FOR EACH TYPE Tag, decimal,currency, bool, integer, string, datetime ******** -->
            <!-- NOTE: currently not implemented: TimeSpan=15, seems unsupportable for a filter  -->
            <!-- DATETIME BUILDER -->
            <!-- Note: date time is a bit unusual in that it presents the date tokens first as it would be the most common choice whereas the other types would do something
                       like that later -->
            <div v-if="editItem.uiFieldDataType === 1">
              <v-select
                v-model="editItem.tempFilterToken"
                :items="selectLists.dateFilterTokens"
                item-text="name"
                item-value="id"
                :label="$sock.t('Filter')"
                prepend-icon="$sockiFilter"
              ></v-select>
              <div v-if="editItem.tempFilterToken == '*select*'">
                <v-select
                  v-model="editItem.tempFilterOperator"
                  :items="selectLists.dateFilterOperators"
                  item-text="name"
                  item-value="id"
                ></v-select>
                <gz-date-time-picker
                  v-if="
                    editItem.tempFilterOperator != '*NOVALUE*' &&
                      editItem.tempFilterOperator != '*HASVALUE*'
                  "
                  v-model="editItem.tempFilterValue"
                ></gz-date-time-picker>
              </div>
              <v-btn
                v-if="editItem.tempFilterToken != null"
                large
                block
                @click="addFilterCondition(editItem)"
                ><v-icon large>$sockiPlus</v-icon></v-btn
              >
            </div>

            <!-- STRING(text-4, emailaddress-11, http-12, phone-16) BUILDER  -->
            <div
              v-if="
                editItem.uiFieldDataType === 4 ||
                  editItem.uiFieldDataType === 11 ||
                  editItem.uiFieldDataType === 12 ||
                  editItem.uiFieldDataType === 16
              "
            >
              <v-select
                v-model="editItem.tempFilterOperator"
                :items="selectLists.stringFilterOperators"
                item-text="name"
                item-value="id"
                :label="$sock.t('Filter')"
                prepend-icon="$sockiFilter"
              ></v-select>
              <v-text-field
                v-if="
                  editItem.tempFilterOperator != null &&
                    editItem.tempFilterOperator != '*NOVALUE*' &&
                    editItem.tempFilterOperator != '*HASVALUE*'
                "
                v-model="editItem.tempFilterValue"
                :clearable="!formState.readOnly"
              ></v-text-field>
              <v-btn
                v-if="editItem.tempFilterOperator != null"
                large
                block
                @click="addFilterCondition(editItem)"
                ><v-icon large>$sockiPlus</v-icon></v-btn
              >
            </div>

            <!-- INTEGER BUILDER  -->
            <!-- Also MemorySize type 14 are integers -->
            <div
              v-if="
                editItem.uiFieldDataType === 5 ||
                  editItem.uiFieldDataType === 14
              "
            >
              <v-select
                v-model="editItem.tempFilterOperator"
                :items="selectLists.integerFilterOperators"
                item-text="name"
                item-value="id"
                :label="$sock.t('Filter')"
                prepend-icon="$sockiFilter"
              ></v-select>
              <v-text-field
                v-if="
                  editItem.tempFilterOperator != null &&
                    editItem.tempFilterOperator != '*NOVALUE*' &&
                    editItem.tempFilterOperator != '*HASVALUE*'
                "
                v-model="editItem.tempFilterValue"
                :clearable="!formState.readOnly"
                type="number"
              ></v-text-field>
              <v-btn
                v-if="editItem.tempFilterOperator != null"
                large
                block
                @click="addFilterCondition(editItem)"
                ><v-icon large>$sockiPlus</v-icon></v-btn
              >
            </div>
            <!-- BOOL BUILDER  -->
            <div v-if="editItem.uiFieldDataType === 6">
              <v-select
                v-model="editItem.tempFilterOperator"
                :items="selectLists.boolFilterOperators"
                item-text="name"
                item-value="id"
                :label="$sock.t('Filter')"
                prepend-icon="$sockiFilter"
              ></v-select>
              <v-radio-group
                v-if="
                  editItem.tempFilterOperator != null &&
                    editItem.tempFilterOperator != '*NOVALUE*' &&
                    editItem.tempFilterOperator != '*HASVALUE*'
                "
                v-model="editItem.tempFilterValue"
                row
              >
                <v-radio :label="$sock.t('False')" :value="false"></v-radio>
                <v-radio :label="$sock.t('True')" :value="true"></v-radio>
              </v-radio-group>

              <v-btn
                v-if="editItem.tempFilterOperator != null"
                large
                block
                @click="addFilterCondition(editItem)"
                ><v-icon large>$sockiPlus</v-icon></v-btn
              >
            </div>

            <!-- DECIMAL BUILDER -->
            <div v-if="editItem.uiFieldDataType === 7">
              <v-select
                v-model="editItem.tempFilterOperator"
                :items="selectLists.decimalFilterOperators"
                item-text="name"
                item-value="id"
                :label="$sock.t('Filter')"
                prepend-icon="$sockiFilter"
              ></v-select>
              <gz-decimal
                v-if="
                  editItem.tempFilterOperator != null &&
                    editItem.tempFilterOperator != '*NOVALUE*' &&
                    editItem.tempFilterOperator != '*HASVALUE*'
                "
                v-model="editItem.tempFilterValue"
                :clearable="!formState.readOnly"
              ></gz-decimal>
              <v-btn
                v-if="editItem.tempFilterOperator != null"
                large
                block
                @click="addFilterCondition(editItem)"
                ><v-icon large>$sockiPlus</v-icon></v-btn
              >
            </div>
            <!-- CURRENCY BUILDER  -->
            <div v-if="editItem.uiFieldDataType === 8">
              <v-select
                v-model="editItem.tempFilterOperator"
                :items="selectLists.decimalFilterOperators"
                item-text="name"
                item-value="id"
                :label="$sock.t('Filter')"
                prepend-icon="$sockiFilter"
              ></v-select>
              <gz-currency
                v-if="
                  editItem.tempFilterOperator != null &&
                    editItem.tempFilterOperator != '*NOVALUE*' &&
                    editItem.tempFilterOperator != '*HASVALUE*'
                "
                v-model="editItem.tempFilterValue"
                :clearable="!formState.readOnly"
              ></gz-currency>
              <v-btn
                v-if="editItem.tempFilterOperator != null"
                large
                block
                @click="addFilterCondition(editItem)"
                ><v-icon large>$sockiPlus</v-icon></v-btn
              >
            </div>
            <!-- TAG BUILDER  -->
            <div v-if="editItem.uiFieldDataType === 9">
              <v-select
                v-model="editItem.tempFilterOperator"
                :items="selectLists.tagFilterOperators"
                item-text="name"
                item-value="id"
                :label="$sock.t('Filter')"
                prepend-icon="$sockiFilter"
              ></v-select>

              <gz-tag-picker
                v-if="editItem.tempFilterOperator != null"
                v-model="editItem.tempFilterValue"
              ></gz-tag-picker>

              <v-btn
                v-if="editItem.tempFilterOperator != null"
                large
                block
                @click="addFilterCondition(editItem)"
                ><v-icon large>$sockiPlus</v-icon></v-btn
              >
            </div>
            <!-- ROLE BUILDER  -->
            <div v-if="editItem.uiFieldDataType === 17">
              <v-select
                v-model="editItem.tempFilterOperator"
                :items="selectLists.roleFilterOperators"
                item-text="name"
                item-value="id"
                :label="$sock.t('Filter')"
                prepend-icon="$sockiFilter"
              ></v-select>
              <gz-role-picker
                v-if="editItem.tempFilterOperator != null"
                v-model="editItem.tempFilterValue"
              ></gz-role-picker>

              <v-btn
                v-if="editItem.tempFilterOperator != null"
                large
                block
                @click="addFilterCondition(editItem)"
                ><v-icon large>$sockiPlus</v-icon></v-btn
              >
            </div>
            <!-- ENUM BUILDER  -->
            <div v-if="editItem.uiFieldDataType === 10">
              <v-select
                v-model="editItem.tempFilterOperator"
                :items="selectLists.enumFilterOperators"
                item-text="name"
                item-value="id"
                :label="$sock.t('Filter')"
                prepend-icon="$sockiFilter"
              ></v-select>

              <v-select
                v-if="
                  editItem.tempFilterOperator != null &&
                    editItem.tempFilterOperator != '*NOVALUE*' &&
                    editItem.tempFilterOperator != '*HASVALUE*'
                "
                v-model="editItem.tempFilterValue"
                :items="enumSelectionList(editItem.enumType)"
                item-text="name"
                item-value="id"
              ></v-select>

              <v-btn
                v-if="editItem.tempFilterOperator != null"
                large
                block
                @click="addFilterCondition(editItem)"
                ><v-icon large>$sockiPlus</v-icon></v-btn
              >
            </div>

            <!-- INTERVAL / DURATION BUILDER  -->
            <div v-if="editItem.uiFieldDataType === 15">
              <v-select
                v-model="editItem.tempFilterOperator"
                :items="selectLists.intervalFilterOperators"
                item-text="name"
                item-value="id"
                :label="$sock.t('Filter')"
                prepend-icon="$sockiFilter"
              ></v-select>
              <!-- :show-seconds="false" -->
              <gz-duration-picker
                v-if="editItem.tempFilterOperator != null"
                v-model="editItem.tempFilterValue"
                :clearable="!formState.readOnly"
                :readonly="formState.readOnly"
              ></gz-duration-picker>
              <v-btn
                v-if="editItem.tempFilterOperator != null"
                large
                block
                @click="addFilterCondition(editItem)"
                ><v-icon large>$sockiPlus</v-icon></v-btn
              >
            </div>
          </div>

          <div class="pt-6">
            <!-- FILTER LIST -->
            <template v-if="editItem.filter.items.length > 0">
              <v-list elevation="2">
                <v-subheader v-if="editItem.filter.items.length > 1">
                  <!-- AND / OR FILTER CONDITIONS -->
                  <v-radio-group
                    v-model="editItem.filter.any"
                    row
                    @change="formState.dirty = true"
                  >
                    <v-radio
                      :label="$sock.t('GridFilterDialogAndRadioText')"
                      :value="false"
                    ></v-radio>
                    <v-radio
                      :label="$sock.t('GridFilterDialogOrRadioText')"
                      :value="true"
                    ></v-radio> </v-radio-group
                ></v-subheader>
                <v-list-item
                  v-for="(filterItem, index) in editItem.filter.items"
                  :key="index"
                >
                  <v-list-item-content>
                    <v-list-item-title v-text="filterItem.display">
                    </v-list-item-title>
                  </v-list-item-content>
                  <v-list-item-action>
                    <v-btn icon @click="removeFilterCondition(editItem, index)">
                      <v-icon>$sockiTrashAlt</v-icon>
                    </v-btn>
                  </v-list-item-action>
                </v-list-item>
              </v-list>
            </template>
          </div>
        </template>
      </v-card-text>
      <v-card-actions>
        <v-btn text color="primary" @click="close()">{{
          $sock.t("Cancel")
        }}</v-btn>
        <v-spacer />
        <v-btn
          v-if="editItem.filter.items.length > 0"
          text
          color="primary"
          @click="clearAllFilterConditions()"
          >{{ $sock.t("Delete") }}</v-btn
        >
        <v-spacer />
        <v-btn
          :disabled="formState.dirty == false"
          text
          color="primary"
          @click="saveAndExit()"
          >{{ $sock.t("Save") }}</v-btn
        >
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>
<script>
export default {
  components: {},

  props: {
    dataListKey: { type: String, default: null },
    activeFilterId: { type: Number, default: null }
  },
  data: () => ({
    isVisible: false,
    resolve: null,
    reject: null,
    tableColumnData: {}, //from table
    fieldDefinitions: [],
    editItem: { filter: { items: [] } },
    activeFilter: null,
    selectLists: {
      dateFilterOperators: [],
      dateFilterTokens: [],
      stringFilterOperators: [],
      integerFilterOperators: [],
      boolFilterOperators: [],
      decimalFilterOperators: [],
      tagFilterOperators: [],
      roleFilterOperators: [],
      enumFilterOperators: [],
      intervalFilterOperators: []
    },
    formState: {
      ready: false,
      dirty: false,
      valid: true,
      readOnly: false,
      loading: true,
      errorBoxMessage: undefined,
      appError: undefined,
      serverError: {}
    }
  }),
  async created() {
    await initForm(this);
  },
  methods: {
    async saveAndExit() {
      //turn activeFilter into object json.parse
      const af = JSON.parse(this.activeFilter.filter);

      //remove column filter if it is already there to replace
      if (af.length != 0) {
        const index = af.findIndex(z => z.column == this.tableColumnData.fk);
        if (index > -1) {
          af.splice(index, 1);
        }
      }

      const newColumnFilter = {
        column: this.tableColumnData.fk,
        any: this.editItem.filter.any,
        items: []
      };
      this.editItem.filter.items.forEach(function(z) {
        //de-arrayify tag filters
        let filterValue = z.value;
        if (Array.isArray(filterValue)) {
          filterValue = z.value.join(); //array to string
        }

        newColumnFilter.items.push({
          op: z.op,
          value: filterValue
        });
      });

      //add it *if* it has any filters at all
      if (newColumnFilter.items.length > 0) {
        af.push(newColumnFilter);
      }

      //turn activeFilter back into json and send back to server to save
      this.activeFilter.filter = JSON.stringify(af);

      //SAVE
      const res = await window.$gz.api.put(
        "data-list-filter",
        this.activeFilter
      );
      if (res.error) {
        throw new Error(window.$gz.errorHandler.errorToString(res, this));
      } else {
        this.close({ refresh: true });
      }
    },
    enumSelectionList: function(enumKey) {
      return window.$gz.enums.getSelectionList(enumKey);
    },
    addFilterCondition(editItem) {
      const filterItem = { op: null, value: null, display: null };
      let filterItemSet = false;

      //DATE relative token?
      if (editItem.uiFieldDataType === 1) {
        if (editItem.tempFilterToken) {
          //no or has value?

          //this redundancy is because there are two ways to select the no value and has value; both present in the relative pick list
          //and also in the select specific value picklist as the date filter picker for convenience so this is a workaround
          //to simulate if the user had done the full *select* first then picked novalue or has value

          if (editItem.tempFilterToken == "*NOVALUE*") {
            filterItem.op = "=";
            filterItem.value = "*NULL*";
            filterItemSet = true;
          } else if (editItem.tempFilterToken == "*HASVALUE*") {
            filterItem.op = "!=";
            filterItem.value = "*NULL*";
            filterItemSet = true;
          } else {
            //some kind of relative date token?
            if (editItem.tempFilterToken != "*select*") {
              //special relative token
              filterItem.op = "="; //equality
              filterItem.token = true;
              filterItem.value = editItem.tempFilterToken;
              filterItemSet = true;
            }
          }
        }
      }

      //BLANKS / NONBLANKS TOKENS?
      if (
        false == filterItemSet &&
        editItem.tempFilterOperator == "*NOVALUE*"
      ) {
        filterItem.op = "=";
        filterItem.value = "*NULL*";
        filterItemSet = true;
      }

      if (
        false == filterItemSet &&
        editItem.tempFilterOperator == "*HASVALUE*"
      ) {
        filterItem.op = "!=";
        filterItem.value = "*NULL*";
        filterItemSet = true;
      }

      //JUST REGULAR FILTER ITEM
      if (
        false == filterItemSet &&
        editItem.tempFilterOperator &&
        editItem.tempFilterValue != null
      ) {
        filterItem.op = editItem.tempFilterOperator;
        filterItem.value = editItem.tempFilterValue;

        //only add if there is both an op and a value
        //above here for tokens that isn't a restriction but
        //after passing through those conditions were at a point where there MUST be both
        if (filterItem.op && filterItem.value != null) {
          filterItemSet = true;
        }
      }

      if (filterItemSet) {
        //display
        filterItem.display = getDisplayForFilter(
          this,
          editItem.uiFieldDataType,
          filterItem.op,
          filterItem.value,
          editItem.enumType
        );

        //add only if not already in the collection (accidental double click)
        //some fits better here as it only test for truthiness and returns immediately on true
        //also the item is unique and display doesn't need to be compared for equality it's irrelevant
        //so only the op and the value need to be checked
        if (
          !editItem.filter.items.some(
            z => z.op == filterItem.op && z.value == filterItem.value
          )
        ) {
          editItem.filter.items.push(filterItem);
          window.$gz.form.setFormState({
            vm: this,
            dirty: true
          });
        }
        return;
      }
    },
    removeFilterCondition(editItem, index) {
      editItem.filter.items.splice(index, 1);
      window.$gz.form.setFormState({
        vm: this,
        dirty: true
      });
    },
    clearAllFilterConditions() {
      this.editItem.filter.items.splice(0, this.editItem.filter.items.length);
      this.editItem.filter.any = false;
      window.$gz.form.setFormState({
        vm: this,
        dirty: true
      });
    },
    async open(tableColumnData) {
      this.tableColumnData = tableColumnData;

      await fetchActiveFilter(this);
      initEditItem(this);
      this.formState.dirty = false;
      this.isVisible = true;
      return new Promise((resolve, reject) => {
        this.resolve = resolve;
        this.reject = reject;
      });
    },
    close(ret) {
      this.isVisible = false;

      this.resolve(ret);
    }
  }
};
/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText();
  populateSelectionLists(vm);
  await populateFieldDefinitions(vm);
}

////////////////////
//
async function populateFieldDefinitions(vm) {
  //get the field defs from cache or store them
  //they are unchanging in a session so no need to fetch each time
  //only a server update would modify them from last value
  const storageKey = `dataListFields:${vm.dataListKey}`;

  const ss = sessionStorage.getItem(storageKey);
  if (ss) {
    vm.fieldDefinitions = JSON.parse(ss);
    return;
  } else {
    const res = await window.$gz.api.get(
      "data-list/listfields?DataListKey=" + vm.dataListKey
    );
    if (res.error) {
      throw new Error(window.$gz.errorHandler.errorToString(res, vm));
    } else {
      vm.fieldDefinitions = res.data;
      sessionStorage.setItem(storageKey, JSON.stringify(res.data));
    }
  }
}

////////////////////
//
async function fetchActiveFilter(vm) {
  ///api/v8/data-list-filter/{id}
  const res = await window.$gz.api.get(`data-list-filter/${vm.activeFilterId}`);
  if (res.error) {
    throw new Error(window.$gz.errorHandler.errorToString(res, vm));
  } else {
    vm.activeFilter = res.data;
  }
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "Filter",
    "GridFilterDialogAndRadioText",
    "GridFilterDialogOrRadioText",
    "GridRowFilterDropDownBlanksItem",
    "GridRowFilterDropDownNonBlanksItem",
    "GridRowFilterDropDownEquals",
    "GridRowFilterDropDownGreaterThan",
    "GridRowFilterDropDownGreaterThanOrEqualTo",
    "GridRowFilterDropDownLessThan",
    "GridRowFilterDropDownLessThanOrEqualTo",
    "GridRowFilterDropDownNotEquals",
    "GridRowFilterDropDownDoesNotContain",
    "GridRowFilterDropDownContains",
    "GridRowFilterDropDownStartsWith",
    "GridRowFilterDropDownEndsWith",
    "SelectItem",
    "DateRangeYesterday",
    "DateRangeToday",
    "DateRangeTomorrow",
    "DateRangeLastWeek",
    "DateRangeThisWeek",
    "DateRangeNextWeek",
    "DateRangeLastMonth",
    "DateRangeThisMonth",
    "DateRangeNextMonth",
    "DateRange14DayWindow",
    "DateRangePast",
    "DateRangeFuture",
    "DateRangeLastYear",
    "DateRangeThisYear",
    "DateRangeInTheLastThreeMonths",
    "DateRangeInTheLastSixMonths",
    "DateRangePastYear",
    "DateRangePast90Days",
    "DateRangePast30Days",
    "DateRangePast7Days",
    "DateRangePast24Hours",
    "DateRangePast6Hours",
    "DateRangeJanuary",
    "DateRangeFebruary",
    "DateRangeMarch",
    "DateRangeApril",
    "DateRangeMay",
    "DateRangeJune",
    "DateRangeJuly",
    "DateRangeAugust",
    "DateRangeSeptember",
    "DateRangeOctober",
    "DateRangeNovember",
    "DateRangeDecember",
    "DateRangePreviousYearThisMonth",
    "DateRangePreviousYearLastMonth",
    "DateRangePreviousYearNextMonth",
    "True",
    "False"
  ]);
}

/////////////////////////////////
//
//
function populateSelectionLists(vm) {
  vm.selectLists.dateFilterOperators.push(
    ...[
      { name: vm.$sock.t("GridRowFilterDropDownBlanksItem"), id: "*NOVALUE*" },
      {
        name: vm.$sock.t("GridRowFilterDropDownNonBlanksItem"),
        id: "*HASVALUE*"
      },
      { name: vm.$sock.t("GridRowFilterDropDownEquals"), id: "=" },
      { name: vm.$sock.t("GridRowFilterDropDownGreaterThan"), id: ">" },
      {
        name: vm.$sock.t("GridRowFilterDropDownGreaterThanOrEqualTo"),
        id: ">="
      },
      { name: vm.$sock.t("GridRowFilterDropDownLessThan"), id: "<" },
      { name: vm.$sock.t("GridRowFilterDropDownLessThanOrEqualTo"), id: "<=" },
      { name: vm.$sock.t("GridRowFilterDropDownNotEquals"), id: "!=" }
    ]
  );

  vm.selectLists.dateFilterTokens.push(
    ...[
      { name: "(" + vm.$sock.t("SelectItem") + ")", id: "*select*" }, //If select then use entry in date /time picker
      { name: vm.$sock.t("GridRowFilterDropDownBlanksItem"), id: "*NOVALUE*" },
      {
        name: vm.$sock.t("GridRowFilterDropDownNonBlanksItem"),
        id: "*HASVALUE*"
      },
      { name: vm.$sock.t("DateRangeYesterday"), id: "*yesterday*" },
      { name: vm.$sock.t("DateRangeToday"), id: "*today*" },
      { name: vm.$sock.t("DateRangeTomorrow"), id: "*tomorrow*" },
      { name: vm.$sock.t("DateRangeLastWeek"), id: "*lastweek*" },
      { name: vm.$sock.t("DateRangeThisWeek"), id: "*thisweek*" },
      { name: vm.$sock.t("DateRangeNextWeek"), id: "*nextweek*" },
      { name: vm.$sock.t("DateRangeLastMonth"), id: "*lastmonth*" },
      { name: vm.$sock.t("DateRangeThisMonth"), id: "*thismonth*" },
      { name: vm.$sock.t("DateRangeNextMonth"), id: "*nextmonth*" },
      { name: vm.$sock.t("DateRange14DayWindow"), id: "*14daywindow*" },
      { name: vm.$sock.t("DateRangePast"), id: "*past*" },
      { name: vm.$sock.t("DateRangeFuture"), id: "*future*" },
      { name: vm.$sock.t("DateRangeLastYear"), id: "*lastyear*" }, //prior year from jan to dec
      { name: vm.$sock.t("DateRangeThisYear"), id: "*thisyear*" },
      {
        name: vm.$sock.t("DateRangeInTheLastThreeMonths"),
        id: "*last3months*"
      },
      {
        name: vm.$sock.t("DateRangeInTheLastSixMonths"),
        id: "*last6months*"
      },
      { name: vm.$sock.t("DateRangePastYear"), id: "*pastyear*" }, //last 365 days
      { name: vm.$sock.t("DateRangePast90Days"), id: "*past90days*" },
      { name: vm.$sock.t("DateRangePast30Days"), id: "*past30days*" },
      { name: vm.$sock.t("DateRangePast7Days"), id: "*past7days*" },
      { name: vm.$sock.t("DateRangePast24Hours"), id: "*past24hours*" },
      { name: vm.$sock.t("DateRangePast6Hours"), id: "*past6hours*" },
      { name: vm.$sock.t("DateRangeJanuary"), id: "*january*" },
      { name: vm.$sock.t("DateRangeFebruary"), id: "*february*" },
      { name: vm.$sock.t("DateRangeMarch"), id: "*march*" },
      { name: vm.$sock.t("DateRangeApril"), id: "*april*" },
      { name: vm.$sock.t("DateRangeMay"), id: "*may*" },
      { name: vm.$sock.t("DateRangeJune"), id: "*june*" },
      { name: vm.$sock.t("DateRangeJuly"), id: "*july*" },
      { name: vm.$sock.t("DateRangeAugust"), id: "*august*" },
      { name: vm.$sock.t("DateRangeSeptember"), id: "*september*" },
      { name: vm.$sock.t("DateRangeOctober"), id: "*october*" },
      { name: vm.$sock.t("DateRangeNovember"), id: "*november*" },
      { name: vm.$sock.t("DateRangeDecember"), id: "*december*" },
      {
        name: vm.$sock.t("DateRangePreviousYearThisMonth"),
        id: "*lastyearthismonth*"
      },
      {
        name: vm.$sock.t("DateRangePreviousYearLastMonth"),
        id: "*lastyearlastmonth*"
      },
      {
        name: vm.$sock.t("DateRangePreviousYearNextMonth"),
        id: "*lastyearnextmonth*"
      }
    ]
  );

  vm.selectLists.stringFilterOperators.push(
    ...[
      { name: vm.$sock.t("GridRowFilterDropDownBlanksItem"), id: "*NOVALUE*" },
      {
        name: vm.$sock.t("GridRowFilterDropDownNonBlanksItem"),
        id: "*HASVALUE*"
      },
      { name: vm.$sock.t("GridRowFilterDropDownEquals"), id: "=" },
      { name: vm.$sock.t("GridRowFilterDropDownGreaterThan"), id: ">" },
      {
        name: vm.$sock.t("GridRowFilterDropDownGreaterThanOrEqualTo"),
        id: ">="
      },
      { name: vm.$sock.t("GridRowFilterDropDownLessThan"), id: "<" },
      { name: vm.$sock.t("GridRowFilterDropDownLessThanOrEqualTo"), id: "<=" },
      { name: vm.$sock.t("GridRowFilterDropDownNotEquals"), id: "!=" },
      { name: vm.$sock.t("GridRowFilterDropDownDoesNotContain"), id: "!-%-" },
      { name: vm.$sock.t("GridRowFilterDropDownContains"), id: "-%-" },
      { name: vm.$sock.t("GridRowFilterDropDownStartsWith"), id: "%-" },
      { name: vm.$sock.t("GridRowFilterDropDownEndsWith"), id: "-%" }
    ]
  );

  vm.selectLists.integerFilterOperators.push(
    ...[
      { name: vm.$sock.t("GridRowFilterDropDownBlanksItem"), id: "*NOVALUE*" },
      {
        name: vm.$sock.t("GridRowFilterDropDownNonBlanksItem"),
        id: "*HASVALUE*"
      },
      { name: vm.$sock.t("GridRowFilterDropDownEquals"), id: "=" },
      { name: vm.$sock.t("GridRowFilterDropDownGreaterThan"), id: ">" },
      {
        name: vm.$sock.t("GridRowFilterDropDownGreaterThanOrEqualTo"),
        id: ">="
      },
      { name: vm.$sock.t("GridRowFilterDropDownLessThan"), id: "<" },
      { name: vm.$sock.t("GridRowFilterDropDownLessThanOrEqualTo"), id: "<=" },
      { name: vm.$sock.t("GridRowFilterDropDownNotEquals"), id: "!=" }
    ]
  );

  vm.selectLists.boolFilterOperators.push(
    ...[
      // { name: vm.$sock.t("GridRowFilterDropDownBlanksItem"), id: "*NOVALUE*" },
      // {
      //   name: vm.$sock.t("GridRowFilterDropDownNonBlanksItem"),
      //   id: "*HASVALUE*"
      // },
      { name: vm.$sock.t("GridRowFilterDropDownEquals"), id: "=" }
      //,      { name: vm.$sock.t("GridRowFilterDropDownNotEquals"), id: "!=" }
    ]
  );

  vm.selectLists.decimalFilterOperators.push(
    ...[
      { name: vm.$sock.t("GridRowFilterDropDownBlanksItem"), id: "*NOVALUE*" },
      {
        name: vm.$sock.t("GridRowFilterDropDownNonBlanksItem"),
        id: "*HASVALUE*"
      },
      { name: vm.$sock.t("GridRowFilterDropDownEquals"), id: "=" },
      { name: vm.$sock.t("GridRowFilterDropDownGreaterThan"), id: ">" },
      {
        name: vm.$sock.t("GridRowFilterDropDownGreaterThanOrEqualTo"),
        id: ">="
      },
      { name: vm.$sock.t("GridRowFilterDropDownLessThan"), id: "<" },
      { name: vm.$sock.t("GridRowFilterDropDownLessThanOrEqualTo"), id: "<=" },
      { name: vm.$sock.t("GridRowFilterDropDownNotEquals"), id: "!=" }
    ]
  );
  vm.selectLists.tagFilterOperators.push(
    ...[
      { name: vm.$sock.t("GridRowFilterDropDownBlanksItem"), id: "*NOVALUE*" },
      {
        name: vm.$sock.t("GridRowFilterDropDownNonBlanksItem"),
        id: "*HASVALUE*"
      },
      { name: vm.$sock.t("GridRowFilterDropDownEquals"), id: "=" },
      { name: vm.$sock.t("GridRowFilterDropDownNotEquals"), id: "!=" },
      { name: vm.$sock.t("GridRowFilterDropDownDoesNotContain"), id: "!-%-" },
      { name: vm.$sock.t("GridRowFilterDropDownContains"), id: "-%-" }
    ]
  );

  vm.selectLists.roleFilterOperators.push(
    ...[
      { name: vm.$sock.t("GridRowFilterDropDownEquals"), id: "=" },
      { name: vm.$sock.t("GridRowFilterDropDownNotEquals"), id: "!=" },
      { name: vm.$sock.t("GridRowFilterDropDownDoesNotContain"), id: "!-%-" },
      { name: vm.$sock.t("GridRowFilterDropDownContains"), id: "-%-" }
    ]
  );

  vm.selectLists.enumFilterOperators.push(
    ...[
      { name: vm.$sock.t("GridRowFilterDropDownBlanksItem"), id: "*NOVALUE*" },
      {
        name: vm.$sock.t("GridRowFilterDropDownNonBlanksItem"),
        id: "*HASVALUE*"
      },
      { name: vm.$sock.t("GridRowFilterDropDownEquals"), id: "=" },
      { name: vm.$sock.t("GridRowFilterDropDownNotEquals"), id: "!=" }
    ]
  );

  vm.selectLists.intervalFilterOperators.push(
    ...[
      // { name: vm.$sock.t("GridRowFilterDropDownEquals"), id: "=" },
      { name: vm.$sock.t("GridRowFilterDropDownGreaterThan"), id: ">" },
      {
        name: vm.$sock.t("GridRowFilterDropDownGreaterThanOrEqualTo"),
        id: ">="
      },
      { name: vm.$sock.t("GridRowFilterDropDownLessThan"), id: "<" },
      { name: vm.$sock.t("GridRowFilterDropDownLessThanOrEqualTo"), id: "<=" }
      //{ name: vm.$sock.t("GridRowFilterDropDownNotEquals"), id: "!=" }
    ]
  );
}

////////////////////
//
function initEditItem(vm) {
  if (vm.fieldDefinitions == null) {
    throw new Error(
      "sock-data-list::initEditItem - fieldDefinitions are not set"
    );
  }

  const fld = vm.fieldDefinitions.find(
    z => z.fieldKey == vm.tableColumnData.fk
  );
  const o = {
    key: fld.fieldKey,
    isFilterable: fld.isFilterable,
    enumType: fld.enumType,
    uiFieldDataType: fld.uiFieldDataType,
    isCustomField: fld.isCustomField,
    filter: { any: false, items: [] },
    tempFilterOperator: null,
    tempFilterToken: null,
    tempFilterValue: null
  };

  //re-hydrate the filter if already defined for this column
  //turn activeFilter into object json.parse
  const allActiveFilters = JSON.parse(vm.activeFilter.filter);

  const af = allActiveFilters.find(z => z.column == vm.tableColumnData.fk);
  if (af) {
    o.filter.any = af.any;
    o.filter.items = af.items;
  }

  //If it's a tag and it's not been set yet it needs to have an empty array to stat with for the picker
  //otherwise it needs to be converted to an array from a comma delimited string for the picker as well
  if (o.uiFieldDataType == 9) {
    if (o.tempFilterValue == null) {
      o.tempFilterValue = [];
    } else {
      //should be a comma delimited string, turn into array
      o.tempFilterValue = o.filter.items[0].split(",");
    }
  }

  //Add display text for filter item (same as in addFilterCondition)
  for (let j = 0; j < o.filter.items.length; j++) {
    const fi = o.filter.items[j];
    fi.display = getDisplayForFilter(
      vm,
      o.uiFieldDataType,
      fi.op,
      fi.value,
      o.enumType
    );
  }

  vm.editItem = o;

  //eoc
}

//////////////////////////////////////////////////////////
//
// Convert filter properties to translated / displayable
// used when making new filter and loading existing
//
function getDisplayForFilter(
  vm,
  uiFieldDataType,
  filterOperator,
  filterValue,
  enumType
) {
  //BLANKS FILTER
  if (filterOperator == "=" && filterValue == "*NULL*") {
    return vm.selectLists.stringFilterOperators.find(z => z.id == "*NOVALUE*")
      .name;
  }
  // NONBLANKS FILTER
  if (filterOperator == "!=" && filterValue == "*NULL*") {
    return vm.selectLists.stringFilterOperators.find(z => z.id == "*HASVALUE*")
      .name;
  }

  //DATE RELATIVE TOKEN FILTER
  if (uiFieldDataType === 1 && filterValue[0] == "*") {
    const valueDisplay = vm.selectLists.dateFilterTokens.find(
      z => z.id == filterValue
    ).name;

    return filterOperator + " " + valueDisplay;
  }

  //VALUE FILTER
  //Nothing more to do if there isn't both a value AND an operator at this point
  if (filterOperator == null || filterValue == null) {
    return "";
  }

  let valueDisplay = "selected value";
  switch (uiFieldDataType) {
    case 1: //date translate
      valueDisplay = window.$gz.locale.utcDateToShortDateAndTimeLocalized(
        filterValue
      );
      break;
    case 8: //currency translate
      valueDisplay = window.$gz.locale.currencyLocalized(filterValue);
      break;
    case 7: //decimal translate
      valueDisplay = window.$gz.locale.decimalLocalized(filterValue);
      break;
    case 6: //BOOL translate
      valueDisplay = vm.$sock.t(filterValue ? "True" : "False");
      break;
    case 10: //ENUM translate
      valueDisplay = window.$gz.enums.get(enumType, filterValue);
      break;
    case 15: //INTERVAL / DURATION translate
      valueDisplay = window.$gz.locale.durationLocalized(filterValue);
      break;
    case 17: //Authorization Roles
      {
        const availableRoles = window.$gz.enums.getSelectionList(
          "AuthorizationRoles"
        ); //will already be cached from viewing datatable
        const roles = filterValue;
        const roleNames = [];
        if (roles != null && roles != 0) {
          for (let i = 0; i < availableRoles.length; i++) {
            const role = availableRoles[i];
            if (roles & role.id) {
              roleNames.push(role.name);
            }
          }
        }
        valueDisplay = roleNames.join(", ");
      }
      break;
    default:
      valueDisplay = filterValue;
      break;
  }

  //Operator
  const opDisplay = vm.selectLists.stringFilterOperators.find(
    z => z.id == filterOperator
  ).name;

  return opDisplay + ' "' + valueDisplay + '"';

  //eoc
}
</script>
