import axios from 'axios'
import store from '@/store'
import dataSetUtils from '../../../classes/dataSetUtils'
import { uuid } from 'vue-uuid'

export default {
  addLog: ({ commit }, payload) => {
    commit('ADD_LOG', payload)
  },
  setSessionId: ({ commit }, payload) => {
    commit('SET_SESSIONID', payload)
  },
  setLanguageSuffix: ({ commit }, payload) => {
    commit('SET_LANGUAGESUFFIX', payload)
  },
  setLookupDefVisible: ({ commit, getters }, payload) => {
    let lookupDef = getters.getDataSetLookupDef(
      payload.appWindowIdent,
      payload.dataSetIdent,
      payload.dataFieldIdent
    )
    let lookupVisible = payload.lookupVisible
    let appWindow = getters.getAppWindow(lookupDef.appWindowIdentLookup)
    commit('SET_LOOKUP_DEF_VISIBLE', { 
      lookupDef: lookupDef, 
      lookupVisible: lookupVisible, 
      dataSet: payload.dataSet, 
      row: payload.row, 
      appWindowUniqIdent: payload.appWindowIdent 
    })
    commit('SET_APPWINDOW_LOOKUP_DEF', { 
      lookupDef, 
      appWindow
    })
  },
  setLookupDefSelection: async ({ dispatch, commit, getters }, payload) => {
    let lookupDef = getters.getAppWindowLookupDef(payload.appWindowIdent)
    if (lookupDef !== null) {
      let lookupVisible = false
      await commit('SET_LOOKUP_DEF_VISIBLE', { 
        lookupDef: lookupDef, 
        lookupVisible: lookupVisible, 
        dataSet: payload.dataSet, 
        row: payload.row
      })
      await dispatch('deleteDataSetWhereListsItem', {
        appWindowIdent: lookupDef.appWindowUniqIdent,
        dataSetIdent: lookupDef.dataSetIdent,
        dataFieldIdent: lookupDef.dataFieldIdent
      })
      await dispatch('fillDataSetsFromSetters', {
        appWindowIdent: payload.appWindowIdent,
        lookupAppWindowIdent: lookupDef.appWindowUniqIdent,
        lookupDataSetIdent: lookupDef.dataSetIdent,
        lookupDataFieldIdent: lookupDef.dataFieldIdent,
        lookupIsMultiSelect: lookupDef.isMultiSelect
      })
    }
  },
  fillDataSetWhere: async ({ dispatch, getters }, payload) => {
    let appWindowIdentFrom
    let dataSetIdentFrom
    let dataSetsFrom
    let dataSetsFromItem
    let dataSetFrom
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    let whereList
    if (dataSet) {
      dataSetsFrom = dataSet.dataSetsFrom
    }
    if (dataSetsFrom != null) {
      for (let i = 0; i < dataSetsFrom.length; i++) {
        dataSetsFromItem = dataSetsFrom[i]
        appWindowIdentFrom = dataSetsFromItem.appWindowIdentFrom
        dataSetIdentFrom = dataSetsFromItem.dataSetIdentFrom
        dataSetFrom = getters.getDataSet(appWindowIdentFrom, dataSetIdentFrom)
        whereList = dataSetFrom.whereLists ? dataSetFrom.whereLists[dataSetsFromItem.dataFieldIdentFrom] : null
        await dispatch('setDataSetFieldValue', {
          sourceKind: dataSetsFromItem.sourceKindTo,
          dataSet: dataSet,
          dataFieldIdent: dataSetsFromItem.dataFieldIdentTo,
          dataFieldValue: getters.getDataSetFieldValue(
            dataSetsFromItem.sourceKindFrom,
            dataSetFrom,
            dataSetsFromItem.dataFieldIdentFrom
          ),
        })
        if (dataSetsFromItem.sourceKindTo === 'where' && whereList) {
          dispatch('setDataSetWhereListsFieldValue', {
            dataSet: dataSet,
            lookupDataFieldIdent: dataSetsFromItem.dataFieldIdentTo,
            whereListValue: null
          })
          await whereList.forEach(whereListItem =>{
            dispatch('setDataSetWhereListsFieldValue', {
              dataSet: dataSet,
              lookupDataFieldIdent: dataSetsFromItem.dataFieldIdentTo,
              whereListValue: whereListItem
            })
          })
        }
      }
    }
  },
  fillDataSetsFromGetters: async ({ dispatch, getters }, payload) => {
    let lookupGetters = getters.getAppWindowLookupGetters(
      payload.appWindowIdent
    )
    await lookupGetters.forEach(lookupGetter => {
      if (
        payload.dataSetIdent === null ||
        payload.dataSetIdent === undefined ||
        lookupGetter.dataSetIdentTo === payload.dataSetIdent
      ) {
        let dataSetTo = getters.getDataSet(
          lookupGetter.appWindowIdentTo,
          lookupGetter.dataSetIdentTo
        )
        let dataSetFrom = getters.getDataSet(
          lookupGetter.appWindowIdentFrom,
          lookupGetter.dataSetIdentFrom
        )
        dispatch('setDataSetFieldValue', {
          sourceKind: lookupGetter.sourceKindTo,
          dataSet: dataSetTo,
          dataFieldIdent: lookupGetter.dataFieldIdentTo,
          dataFieldValue: getters.getDataSetFieldValue(
            lookupGetter.sourceKindFrom,
            dataSetFrom,
            lookupGetter.dataFieldIdentFrom
          )
        })
        if (
          lookupGetter.sourceKindFrom === 'where' &&
          lookupGetter.sourceKindTo === 'where'
        ) {
          let whereListValue =
            dataSetFrom.whereLists[lookupGetter.dataFieldIdentFrom] || null
          if (whereListValue)
            whereListValue.forEach(whereListItem => {
              dispatch('setDataSetWhereListsFieldValue', {
                dataSet: dataSetTo,
                lookupDataFieldIdent: lookupGetter.dataFieldIdentTo,
                whereListValue: whereListItem
              })
            })
          else {
            dispatch('setDataSetWhereListsFieldValue', {
              dataSet: dataSetTo,
              lookupDataFieldIdent: lookupGetter.dataFieldIdentTo,
              whereListValue: null
            })
          }
        }
      }
    })
  },
  refreshDataOnQueryChange: async ({ dispatch, getters }, payload) => {
    if (getters.checkAppWindowQueryDataSetsTo(payload.appWindowIdent)) {
      await dispatch('fillDataSetsFromQuery', {
        appWindowIdent: payload.appWindowIdent,
        query: getters.getRoute.query
      })
      await dispatch('setAppWindowData', {
        appWindowIdent: payload.appWindowIdent,
        serverSide: payload.serverSide
      })
    }
  },
  refreshDataOnFromQuery: async ({ dispatch }, payload) => {
    if (!payload.query) return
    await dispatch('fillDataSetsFromQuery', {
      appWindowIdent: payload.appWindowIdent,
      query: payload.query
    })
    await dispatch('setAppWindowData', {
      appWindowIdent: payload.appWindowIdent,
      serverSide: payload.serverSide
    })
  },
  fillDataSetsFromQuery: async ({ dispatch, getters, commit }, payload) => {
    let appwindow = getters.getAppWindow(payload.appWindowIdent)
    if (!appwindow) return
    let queryDataSetsTo = appwindow.queryDataSetsTo
    if (!queryDataSetsTo) return
    let query = payload.query
    if (!query) return
    queryDataSetsTo.forEach(async item => {
      let dataSet = getters.getDataSet(
        payload.appWindowIdent,
        item.dataSetIdent
      )
      if (query[item.linkedParamName] !== undefined) {
        if (item.linkedParamName == 'pageSize') {
          commit('SET_DATASET_PAGESIZE', {
            dataSet: dataSet,
            pageSize: query[item.linkedParamName]
          })
        } else {
          await dispatch('setDataSetWhereFieldValue', {
            appWindowIdent: payload.appWindowIdent,
            dataSet: dataSet,
            dataFieldIdent: item.dataFieldIdent,
            dataFieldValue: query[item.linkedParamName]
          })
        }
        await dispatch('setDataSetRefReq', {
          appWindowIdent: payload.appWindowIdent,
          dataSetIdent: item.dataSetIdent,
          refreshAggregates: 1
        })
      } 
      else {
        let whereFieldsIdent = getters.getDataSetWhereFieldsIdentsDataField(dataSet, item.dataFieldIdent)
        let whereFieldsIdentValue = whereFieldsIdent != null ? whereFieldsIdent.dataFieldValueDef : null;
        if(item.linkedParamName != null) {
          await dispatch('setDataSetWhereFieldValue', {
            appWindowIdent: payload.appWindowIdent,
            dataSet: dataSet,
            dataFieldIdent: item.dataFieldIdent,
            dataFieldValue: whereFieldsIdentValue
          })
          await dispatch('setDataSetRefReq', {
            appWindowIdent: payload.appWindowIdent,
            dataSetIdent: item.dataSetIdent,
            refreshAggregates: 1
          })
        }
      }
    })
  },
  fillDataSetsAttribFromQuery: async ({ getters, commit }, payload) => {
    let appwindow = getters.getAppWindow(payload.appWindowIdent)
    if (!appwindow) return
    let queryDataSetsTo = appwindow.queryDataSetsTo
    if (!queryDataSetsTo) return
    let query = payload.query || getters.getRoute.query
    if (!query) return
    queryDataSetsTo.forEach(async item => {
      if (query[item.linkedParamName] !== undefined) {
        let dataSet = getters.getDataSet(
          payload.appWindowIdent,
          item.dataSetIdent
        )
        if (item.linkedParamName == 'pageSize') {
          commit('SET_DATASET_PAGESIZE', {
            dataSet: dataSet,
            pageSize: query[item.linkedParamName]
          })
        } else if (item.linkedParamName == 'pageNo') {
          let pageNo = query[item.linkedParamName]
          let pagesCount = pageNo
          commit('SET_DATASET_PAGENO', { dataSet, pagesCount, pageNo })
        }
      }
    })
  },
  fillDataSetsFromData: async ({ dispatch, getters }, payload) => {
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    let data = payload.data
    let filter = payload.filter
    let row = filter ?
      getters.appWindowDataSetFindRow(
        payload.appWindowIdent,
        payload.dataSetIdent,
        filter
      ) : payload.row
    let sourceKindTo = payload.sourceKindTo || 'where'
    let onCFLock = payload.onCFLock
    if (!data) return
    data.forEach(async item => {
      if (item.dataFieldIdent) {
        await dispatch(
          sourceKindTo === 'where'
            ? 'setDataSetWhereFieldValue'
            : 'setDataSetRowsFieldValue',
          {
            appWindowIdent: payload.appWindowIdent,
            dataSet: dataSet,
            row: row,
            dataFieldIdent: item.dataFieldIdent,
            dataFieldValue: item.dataFieldValue,
            onCFLock: onCFLock
          }
        )
      }
    })
  },
  addRow: async ({ commit }, payload) => {
    let dataSet = payload.dataSet
    let fieldsIdents = payload.fieldsIdents
    let row = payload.row
    await commit('ADD_ROW', { dataSet, fieldsIdents, row })
  },
  deleteRow: async ({ commit }, payload) => {
    let dataSet = payload.dataSet
    let row = payload.row
    await commit('DELETE_ROW', { dataSet, row })
  },
  addFile: async ({ commit }, payload) => {
    let dataSet = payload.dataSet
    let file = payload.file
    await commit('ADD_FILE', { dataSet, file })
  },
  deleteFile: async ({ commit }, payload) => {
    let dataSet = payload.dataSet
    let file = payload.file
    await commit('DELETE_FILE', { dataSet, file })
  },
  addSelectedRow: async ({ commit, getters, dispatch }, payload) => {
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    if (!dataSet.keyFieldsIdents || dataSet.keyFieldsIdents.length === 0) {
      await commit('SET_ERRORS', {
        appWindowIdent: payload.appWindowIdent,
        dataSetIdent: payload.dataSetIdent,
        errors: 'Brak zdefiniowanych pól kluczowych dla źródła danych: ' + payload.dataSetIdent
      })
      return -1
    }
    let row = payload.row
    await commit('ADD_SELECTED_ROW', { dataSet, row })
    dispatch('refreshDataSetDependence', {
      appWindowIdent: payload.appWindowIdent,
      parentDataSetIdent: dataSet.dataSetIdent,
      refreshAggregates: 1,
      sourceKindFrom: 'selectedRows'
    })
  },
  addAllSelectedRow: async ({ commit, getters, dispatch }, payload) => {
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    if (!dataSet.keyFieldsIdents || dataSet.keyFieldsIdents.length === 0) {
      await commit('SET_ERRORS', {
        appWindowIdent: payload.appWindowIdent,
        dataSetIdent: payload.dataSetIdent,
        errors: 'Brak zdefiniowanych pól kluczowych dla źródła danych: ' + payload.dataSetIdent
      })
      return -1
    }
    if (dataSet && dataSet.rows) await dataSet.rows.forEach(row => {
      commit('ADD_SELECTED_ROW', { dataSet, row })
    })
    dispatch('refreshDataSetDependence', {
      appWindowIdent: payload.appWindowIdent,
      parentDataSetIdent: dataSet.dataSetIdent,
      refreshAggregates: 1,
      sourceKindFrom: 'selectedRows'
    })
  },
  deleteSelectedRow: async ({ commit, getters, dispatch }, payload) => {
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    let row = payload.row
    await commit('DELETE_SELECTED_ROW', { dataSet, row })
    dispatch('refreshDataSetDependence', {
      appWindowIdent: payload.appWindowIdent,
      parentDataSetIdent: dataSet.dataSetIdent,
      refreshAggregates: 1,
      sourceKindFrom: 'selectedRows'
    })
  },
  deleteAllSelectedRow: async ({ commit, getters }, payload) => {
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    commit('DELETE_ALL_SELECTED_ROW', { dataSet })
  },
  fillDataSetsFromSetters: async ({ dispatch, getters }, payload) => {
    let lookupSetters = getters.getAppWindowLookupSetters(
      payload.appWindowIdent
    )
    let lookupAppWindowIdent = getters.getAppWindowIdent(payload.lookupAppWindowIdent)
    if (!payload.lookupIsMultiSelect)
      await lookupSetters.forEach(lookupSetter => {
        dispatch('setDataSetFieldValue', {
          sourceKind: lookupSetter.sourceKindTo,
          appWindowIdent: lookupSetter.appWindowIdentTo === lookupAppWindowIdent ? payload.lookupAppWindowIdent : lookupSetter.appWindowIdentTo,
          dataSet: getters.getDataSet(
            lookupSetter.appWindowIdentTo === lookupAppWindowIdent ? payload.lookupAppWindowIdent : lookupSetter.appWindowIdentTo,
            lookupSetter.dataSetIdentTo
          ),
          dataFieldIdent: lookupSetter.dataFieldIdentTo,
          dataFieldValue: getters.getDataSetFieldValue(
            lookupSetter.sourceKindFrom,
            getters.getDataSet(
              lookupSetter.appWindowIdentFrom,
              lookupSetter.dataSetIdentFrom
            ),
            lookupSetter.dataFieldIdentFrom
          )
        })
      })
    if (payload.lookupIsMultiSelect) {
      let whereLists = []
      await lookupSetters.forEach(lookupSetter => {
        let dataSetFrom = getters.getDataSet(
          lookupSetter.appWindowIdentFrom,
          lookupSetter.dataSetIdentFrom
        )
        if (
          lookupSetter.sourceKindFrom === 'rows' &&
          dataSetFrom.selectedRows.length > 0
        ) {
          dataSetFrom.selectedRows.forEach((row, index) => {
            if (whereLists[index] === undefined) {
              let _keyFieldsValues = getters.getDataSetRowsKeyFieldsValues(dataSetFrom, row)
              whereLists.push({
                [lookupSetter.dataFieldIdentTo]: row[lookupSetter.dataFieldIdentFrom],
                _keyFieldsValues: _keyFieldsValues || undefined
              })
            } else {
              whereLists[index][[lookupSetter.dataFieldIdentTo]] =
                row[lookupSetter.dataFieldIdentFrom]
            }
          })
        }
      })
      await whereLists.forEach(whereListValue => {
        dispatch('setDataSetWhereListsFieldValue', {
          dataSet: getters.getDataSet(
            payload.lookupAppWindowIdent,
            payload.lookupDataSetIdent
          ),
          lookupDataFieldIdent: payload.lookupDataFieldIdent,
          whereListValue: whereListValue
        })
      })
    }
  },
  clearDataSetsFromSetters: async ({ dispatch, getters }, payload) => {
    let lookupDef =
      getters.getDataSetLookupDef(
        payload.appWindowIdent,
        payload.dataSetIdent,
        payload.dataFieldIdent
      ) || {}
    let lookupSetters = lookupDef.lookupSetters || []
    await lookupSetters.forEach(lookupSetter => {
      dispatch(
        lookupSetter.sourceKindTo === 'where'
          ? 'setDataSetWhereFieldValue'
          : 'setDataSetRowsFieldValue',
        {
          appWindowIdent: payload.appWindowIdent,
          dataSet: getters.getDataSet(
            lookupSetter.appWindowIdentTo,
            lookupSetter.dataSetIdentTo
          ),
          dataFieldIdent: lookupSetter.dataFieldIdentTo,
          dataFieldValue: null
        }
      )
    })
  },
  clearLookupDataSetsSelection: async ({ dispatch, getters }, payload) => {
    let lookupDef =
      getters.getDataSetLookupDef(
        payload.appWindowIdent,
        payload.dataSetIdent,
        payload.dataFieldIdent
      ) || {}
    let lookupSettersRefresh = lookupDef.lookupSettersRefresh || []
    await lookupSettersRefresh.forEach(async item => {
      await dispatch('deleteAllSelectedRow', {
        appWindowIdent: item.appWindowIdentFrom,
        dataSetIdent: item.dataSetIdentFrom
      })
    })
  },
  refreshDataSetFromSetters: async ({ dispatch, getters }, payload) => {
    let lookupSettersRefresh = getters.getAppWindowLookupSettersRefresh(
      payload.appWindowIdent
    )
    for (let i = 0; i < lookupSettersRefresh.length; i++) {
      await dispatch('refreshDataSet', {
        appWindowIdent: lookupSettersRefresh[i].appWindowIdentFrom,
        dataSetIdent: lookupSettersRefresh[i].dataSetIdentFrom,
        refreshAggregates: 1
      })
    }
  },
  refreshDataSets: ({ dispatch }, payload) => {
    let appWindowsIdents = []
    if (payload.dataSetIdents !== null) {
      for (let i = 0; i < payload.dataSetIdents.length; i++) {
        if (
          !appWindowsIdents.find(
            item => item === payload.dataSetIdents[i].appWindowIdent
          )
        )
          appWindowsIdents.push(payload.dataSetIdents[i].appWindowIdent)
        dispatch('setDataSetRefReq', {
          appWindowIdent: payload.dataSetIdents[i].appWindowIdent,
          dataSetIdent: payload.dataSetIdents[i].dataSetIdent,
          refreshAggregates: payload.refreshAggregates
        })
      }
    }
    for (let i = 0; i < appWindowsIdents.length; i++) {
      dispatch('setAppWindowData', {
        appWindowIdent: appWindowsIdents[i]
      })
    }
  },
  refreshDataSet: ({ dispatch }, payload) => {
    dispatch('refreshDataSets', {
      dataSetIdents: [
        {
          appWindowIdent: payload.appWindowIdent,
          dataSetIdent: payload.dataSetIdent
        }
      ],
      refreshAggregates: payload.refreshAggregates
    })
  },
  refreshDataSetDependence: ({ dispatch, getters }, payload) => {
    dispatch('refreshDataSets', {
      dataSetIdents: getters.getDataSetsDependency(
        getters.getDataSet(payload.appWindowIdent, payload.parentDataSetIdent),
        payload.sourceKindFrom
      ),
      refreshAggregates: payload.refreshAggregates
    })
  },
  addStartWindows: async ({ dispatch, getters }, payload) => {
    let appWindowIdent = payload.appWindowIdent
    if (appWindowIdent === 'dist') appWindowIdent = getters.mainAppWindowIdent
    let setActive = payload.setActive
    let path = payload.path
    let query = payload.query
    let serverSide = payload.serverSide
    let router = payload.router
    if (serverSide){
      await dispatch('deleteAppWindowsAll')
    }
    if (appWindowIdent !== getters.mainAppWindowIdent) {
      await dispatch('addAppWindow', {
        appWindowIdent: getters.mainAppWindowIdent,
        setActive: false,
        lookupDef: null,
        addRoutingData: true,
        path: null,
        query: query,
        serverSide: serverSide,
        router: router
      })
    }
    await dispatch('addAppWindow', {
      appWindowIdent: appWindowIdent,
      setActive: setActive,
      lookupDef: null,
      addRoutingData: false,
      path: path,
      query: query,
      serverSide: serverSide,
      router: router
    })
  },
  addLookupWindow: async ({getters, dispatch, commit}, payload) => {
    let appWindows = Object.values(getters.csAppWindows)
    for (var i = 0; i < appWindows.length; i++){
      let lookupDef = appWindows[i].lookupDef
      if (!lookupDef || lookupDef.closeKind !== 'anotherExpanded' || lookupDef === payload.lookupDef)
        continue
      await commit('SET_LOOKUP_DEF_VISIBLE', { lookupDef: lookupDef, lookupVisible: false })
    }
    dispatch('addAppWindow', payload)
  },
  addAppWindow: async ({ dispatch, getters, commit }, payload) => {
    let appWindowIdent = payload.appWindowIdent
    let appWindow = getters.getAppWindow(appWindowIdent, payload.path)
    let setActive = payload.setActive
    let lookupDef = payload.lookupDef
    let query = payload.query
    let serverSide = payload.serverSide
    let params = payload.params
    let commands = payload.commands
    if (appWindow)
      dispatch('unlockActions', appWindow)
    if (appWindow === undefined) {
      await dispatch('loadAppWindow', payload)
      appWindow = getters.getAppWindow(appWindowIdent, payload.path)
    }
    if (appWindow) {
      let appWindowUniqIdent = getters.getAppWindowUniqIdentFromAppWindow(
        appWindow,
        query
      )
      if (appWindowUniqIdent !== appWindowIdent) {
        let appWindowNew = getters.getAppWindow(appWindowUniqIdent)
        if (!appWindowNew) {
          appWindowNew = getters.cloneAppWindow(appWindow)
          appWindowNew.appWindowUniqIdent = appWindowUniqIdent
          let mainAppWindowIdent = getters.mainAppWindowIdent
          await commit('ADD_APPWINDOW', {
            appWindow: appWindowNew,
            setActive: setActive,
            lookupDef: lookupDef,
            path: payload.path,
            mainAppWindowIdent: mainAppWindowIdent,
            appWindowIdent: appWindowUniqIdent
          })
        }
      }
      if (setActive && appWindowUniqIdent !== getters.activeWindowIdent)
        await dispatch('setActiveAppWindow', {
          appWindowIdent: appWindowUniqIdent
        })
      appWindow = getters.getAppWindow(appWindowUniqIdent)
      if (!commands) commands = getters.getCommandsFromPath(payload.path)
      if (!params) params = getters.getParamsFromPath(payload.path)
      if (commands) {
        await commit('SET_APPWINDOW_COMMANDS', { appWindow, commands })
        await dispatch('processCommands', { commands })
      }
      await dispatch('fillDataSetsFromQuery', {
        appWindowIdent: appWindowUniqIdent,
        query: query
      })
      if (params && JSON.stringify(params) != JSON.stringify(appWindow.params)) {
        await commit('SET_APPWINDOW_PARAMS', { appWindow, params })
        await dispatch('setDataSetRefReqAll', {
          appWindowIdent: appWindowUniqIdent,
          refreshAggregates: 1
        })
      }
      await dispatch('fillDataSetsFromGetters', {
        appWindowIdent: appWindowUniqIdent,
        dataSetIdent: null
      })
      await dispatch('setAppWindowData', {
        appWindowIdent: appWindowUniqIdent,
        serverSide: serverSide,
        query: query
      })
      await dispatch('refreshDataSetFromSetters', {
        appWindowIdent: appWindowUniqIdent
      })
    }
  },
  loginUsr: async ({ state, getters, dispatch, commit }, payload) => {
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    let action = getters.getDataSetAction(dataSet, 'csLogin')
    let request = {
      sessionId: getters.getSessionId(state),
      csAppNameSpacesG: getters.csAppNameSpacesG,
      connection: getters.getAPIConnectionData,
      route: getters.getAppWindowRoutingData(payload.addRoutingData),
      login: payload.login,
      password: payload.password,
      uPwd: payload.uPwd,
      rPwd: payload.rPwd,
    }
    let url = store.getters['csServerSettings/getAPIDefinitionMethodURL'](
      'login',
      payload.serverSide
    )
    let response = await axios.post(url, request)
    let id = uuid.v1()
    await commit('SET_ERRORS', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: payload.dataSetIdent,
      errors: response.errors,
      action: action,
      row: payload.row,
      id: id
    })
    let data = response.data
    if (data && data.errors) {
      await commit('SET_ERRORS', {
        appWindowIdent: payload.appWindowIdent,
        dataSetIdent: payload.dataSetIdent,
        errors: data.errors,
        action: action,
        row: payload.row,
        id: id
      })
    }
    if (getters.hasError(id)) return
    await dispatch('deleteAppWindowsAll')
    payload.router.push(store.state.route.from.fullPath)
  },
  logoutUsr: async ({ state, getters, dispatch, commit }, payload) => {
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    let action = getters.getDataSetAction(dataSet, 'csLogout')
    let request = {
      sessionId: getters.getSessionId(state),
      csAppNameSpacesG: getters.csAppNameSpacesG,
      connection: getters.getAPIConnectionData,
      route: getters.getAppWindowRoutingData(payload.addRoutingData),
    }
    let url = store.getters['csServerSettings/getAPIDefinitionMethodURL'](
      'logout',
      payload.serverSide
    )
    let response = await axios.post(url, request)
    let data = response.data
    let id = uuid.v1()
    await commit('SET_ERRORS', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: payload.dataSetIdent,
      errors: response.errors,
      action: action,
      row: payload.row,
      id: id
    })
    if (data && data.errors) {
      await commit('SET_ERRORS', {
        appWindowIdent: payload.appWindowIdent,
        dataSetIdent: payload.dataSetIdent,
        errors: data.errors,
        action: action,
        row: payload.row,
        id: id
      })
    }
    if (getters.hasError(id)) return
    await dispatch('deleteAppWindowsAll')
    payload.router.go()
  },
  gotoLocation: ({ commit }, payload) => {
    let router = payload.router
    let location = payload.location
    commit('GOTO_LOCATION', { router: router, location: location })
  },
  unlockActions: ({ commit }, appWindow) => {
    if (appWindow.dataSets)
      for (var dataSet in appWindow.dataSets) {
        if (dataSet.actions)
          dataSet.actions.forEach(action => {
            commit('SET_DATASET_ACTION_STATE', { action: action, state: 1 })
          })
      }
  },
  loadAppWindow: async ({ commit, state, getters }, payload) => {
    let refreshParamsJSON = getters.getRefreshParams()
    let request = {
      serverSide: payload.serverSide,
      csAppNameSpacesG: getters.csAppNameSpacesG,
      appWindowIdent: payload.appWindowIdent,
      sessionId: getters.getSessionId(state),
      viewHTMLFromFile: getters.viewHTMLFromFile,
      connection: refreshParamsJSON ? getters.getAPIConnectionData : undefined,
      route: getters.getAppWindowRoutingData(payload.addRoutingData),
      path: payload.path,
      refreshParamsJSON: refreshParamsJSON ? refreshParamsJSON : undefined
    }
    let url = store.getters['csServerSettings/getAPIDefinitionMethodURL'](
      'getDefinition',
      payload.serverSide
    )
    let response = await axios.post(url, [request])
    await commit('SET_ERRORS', response.errors)
    if (response.data.errors)
      await commit('SET_ERRORS', [{ messageText: response.data.errors }])
    await commit('SET_SESSIONID', { sessionId: response.data.sessionId })
    if (
      response.data.definition === undefined ||
      response.data.definition === null
    ) {
      commit('ADD_LOG', {
        messageText:
          'Error loading window: ' +
          payload.appWindowIdent +
          ' serverSide: ' +
          payload.serverSide +
          ' url: ' +
          url +
          ' request: ' +
          JSON.stringify(request) +
          ':' +
          JSON.stringify(response.data)
      })
      return
    }
    let appWindow = getters.getAppWindowFromDefinition(
      payload.appWindowIdent,
      response.data.definition,
      payload.lookupDef
    )
    let setActive = payload.setActive
    let lookupDef = payload.lookupDef
    let router = payload.router
    let path = response.data.pathChange != null ? response.data.pathChange : payload.path
    payload.path = path
    let mainAppWindowIdent = getters.mainAppWindowIdent
    let appWindowIdent = appWindow.appWindowIdent
    await commit('ADD_APPWINDOW', {
      appWindow,
      setActive,
      lookupDef,
      path,
      mainAppWindowIdent,
      appWindowIdent
    })
    if (response.data.pathChange != null && router != null && router.currentRoute.path !== path){
      router.replace({ path: path })
    }
  },
  deleteAppWindow: async ({ commit }, payload) => {
    if (payload === null) throw Error('[deleteAppWindow] -  payload is null.')
    if (payload.appWindowIdent === null)
      throw Error('[deleteAppWindow] -  appWindowIdent is null.')
    await commit('DELETE_APPWINDOW', payload)
  },
  reloadAppWindow: async ({ dispatch }, payload) => {
    if (payload === null) throw Error('[reloadAppWindow] -  payload is null.')
    if (payload.appWindowIdent === null)
      throw Error('[reloadAppWindow] -  appWindowIdent is null.')
    await dispatch('deleteAppWindow', {
      appWindowIdent: payload.appWindowIdent
    })
    await dispatch('addAppWindow', {
      appWindowIdent: payload.appWindowIdent,
      setActive: true,
      lookupDef: null,
      addRoutingData: true,
      path: null,
      query: store.state.route.query
    })
  },
  setActiveAppWindow: async ({ commit }, payload) => {
    if (payload === null)
      throw Error('[setActiveAppWindow] -  payload is null.')
    if (payload.appWindowIdent === null)
      throw Error('[setActiveAppWindow] -  appWindowIdent is null.')
    await commit('SETACTIVE_APPWINDOW', payload)
  },
  dataSetPageChange: ({ dispatch }, payload) => {
    dispatch('refreshDataSet', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: payload.dataSetIdent,
      refreshAggregates: 0
    })
  },
  setDataSetPageNo: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let pagesCount = getters.getDataSetPagesCount(dataSet)
    let pageNo = payload.pageNo
    commit('SET_DATASET_PAGENO', { dataSet, pagesCount, pageNo })
    dispatch('dataSetPageChange', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: dataSet.dataSetIdent
    })
  },
  setDataSetPivotColsPageNo: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let pagesCount = getters.getDataSetPivotColsPagesCount(dataSet)
    let pageNo = payload.pageNo
    let layout = getters.getDataSetLayout(
      dataSet,
      getters.getDataSetLayoutIdent(dataSet)
    )
    commit('SET_DATASET_PIVOT_COLS_PAGENO', {
      dataSet,
      layout,
      pagesCount,
      pageNo
    })
    dispatch('dataSetPageChange', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: dataSet.dataSetIdent
    })
  },
  setDataSetPivotRowsPageNo: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let pagesCount = getters.getDataSetPivotRowsPagesCount(dataSet)
    let pageNo = payload.pageNo
    let layout = getters.getDataSetLayout(
      dataSet,
      getters.getDataSetLayoutIdent(dataSet)
    )
    commit('SET_DATASET_PIVOT_ROWS_PAGENO', {
      dataSet,
      layout,
      pagesCount,
      pageNo
    })
    dispatch('dataSetPageChange', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: dataSet.dataSetIdent
    })
  },
  setDataSetPageNoFirst: ({ commit, dispatch }, payload) => {
    let dataSet = payload.dataSet
    commit('SET_DATASET_PAGENOFIRST', { dataSet })
    dispatch('dataSetPageChange', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: dataSet.dataSetIdent
    })
  },
  setDataSetPivotColsPageNoFirst: (
    { commit, getters, dispatch },
    payload
  ) => {
    let dataSet = payload.dataSet
    let layout = getters.getDataSetLayout(
      dataSet,
      getters.getDataSetLayoutIdent(dataSet)
    )
    commit('SET_DATASET_PIVOT_COLS_PAGENOFIRST', { dataSet, layout })
    dispatch('dataSetPageChange', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: dataSet.dataSetIdent
    })
  },
  setDataSetPivotRowsPageNoFirst: (
    { commit, getters, dispatch },
    payload
  ) => {
    let dataSet = payload.dataSet
    let layout = getters.getDataSetLayout(
      dataSet,
      getters.getDataSetLayoutIdent(dataSet)
    )
    commit('SET_DATASET_PIVOT_ROWS_PAGENOFIRST', { dataSet, layout })
    dispatch('dataSetPageChange', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: dataSet.dataSetIdent
    })
  },
  setDataSetPageNoLast: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let pagesCount = getters.getDataSetPagesCount(dataSet)
    commit('SET_DATASET_PAGENOLAST', { dataSet, pagesCount })
    dispatch('dataSetPageChange', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: dataSet.dataSetIdent
    })
  },
  setDataSetPivotColsPageNoLast: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let pagesCount = getters.getDataSetPivotColsPagesCount(dataSet)
    let layout = getters.getDataSetLayout(
      dataSet,
      getters.getDataSetLayoutIdent(dataSet)
    )
    commit('SET_DATASET_PIVOT_COLS_PAGENOLAST', {
      dataSet,
      layout,
      pagesCount
    })
    dispatch('dataSetPageChange', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: dataSet.dataSetIdent
    })
  },
  setDataSetPivotRowsPageNoLast: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let pagesCount = getters.getDataSetPivotRowsPagesCount(dataSet)
    let layout = getters.getDataSetLayout(
      dataSet,
      getters.getDataSetLayoutIdent(dataSet)
    )
    commit('SET_DATASET_PIVOT_ROWS_PAGENOLAST', {
      dataSet,
      layout,
      pagesCount
    })
    dispatch('dataSetPageChange', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: dataSet.dataSetIdent
    })
  },
  setDataSetPageNoNext: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let pagesCount = getters.getDataSetPagesCount(dataSet)
    commit('SET_DATASET_PAGENONEXT', { dataSet, pagesCount })
    dispatch('dataSetPageChange', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: dataSet.dataSetIdent
    })
  },
  setDataSetPivotColsPageNoNext: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let pagesCount = getters.getDataSetPivotColsPagesCount(dataSet)
    let layout = getters.getDataSetLayout(
      dataSet,
      getters.getDataSetLayoutIdent(dataSet)
    )
    commit('SET_DATASET_PIVOT_COLS_PAGENONEXT', {
      dataSet,
      layout,
      pagesCount
    })
    commit('SET_DATASET_SCROLL_DIRECTION', {
      dataSet: dataSet,
      scrollDirection: dataSetUtils.scrollDirection.right
    })
    dispatch('dataSetPageChange', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: dataSet.dataSetIdent
    })
  },
  setDataSetPivotRowsPageNoNext: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let pagesCount = getters.getDataSetPivotRowsPagesCount(dataSet)
    let layout = getters.getDataSetLayout(
      dataSet,
      getters.getDataSetLayoutIdent(dataSet)
    )
    commit('SET_DATASET_PIVOT_ROWS_PAGENONEXT', {
      dataSet,
      layout,
      pagesCount
    })
    commit('SET_DATASET_SCROLL_DIRECTION', {
      dataSet: dataSet,
      scrollDirection: dataSetUtils.scrollDirection.bottom
    })
    dispatch('dataSetPageChange', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: dataSet.dataSetIdent
    })
  },
  setDataSetPageNoPrev: ({ commit, dispatch }, payload) => {
    let dataSet = payload.dataSet
    commit('SET_DATASET_PAGENOPREV', { dataSet })
    dispatch('dataSetPageChange', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: dataSet.dataSetIdent
    })
  },
  setDataSetPivotColsPageNoPrev: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let layout = getters.getDataSetLayout(
      dataSet,
      getters.getDataSetLayoutIdent(dataSet)
    )
    commit('SET_DATASET_PIVOT_COLS_PAGENOPREV', { dataSet, layout })
    commit('SET_DATASET_SCROLL_DIRECTION', {
      dataSet: dataSet,
      scrollDirection: dataSetUtils.scrollDirection.left
    })
    dispatch('dataSetPageChange', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: dataSet.dataSetIdent
    })
  },
  setDataSetPivotRowsPageNoPrev: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let layout = getters.getDataSetLayout(
      dataSet,
      getters.getDataSetLayoutIdent(dataSet)
    )
    commit('SET_DATASET_PIVOT_ROWS_PAGENOPREV', { dataSet, layout })
    commit('SET_DATASET_SCROLL_DIRECTION', {
      dataSet: dataSet,
      scrollDirection: dataSetUtils.scrollDirection.top
    })
    dispatch('dataSetPageChange', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: dataSet.dataSetIdent
    })
  },
  setDataSetLayoutIdent: ({ commit }, payload) => {
    commit('SET_LAYOUT_IDENT', payload)
  },
  setDataSetSortIdent: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let sortIdent = payload.sortIdent
    let layout = getters.getDataSetLayout(
      dataSet,
      getters.getDataSetLayoutIdent(dataSet)
    )
    commit('SET_LAYOUT_SORTIDENT', { layout, sortIdent })
    dispatch('setDataSetPageNoFirst', {
      appWindowIdent: payload.appWindowIdent,
      dataSet: payload.dataSet
    })
  },
  setDataSetPageSizesIdent: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let pageSizesIdent = payload.pageSizesIdent
    let pageSizes = getters.getDataSetPageSizes(dataSet, pageSizesIdent)
    let pageSize
    if (pageSizes !== null && pageSizes !== undefined) {
      pageSize = pageSizes.pageSize
    }
    commit('SET_DATASET_PAGESIZESIDENT', {
      dataSet,
      pageSizesIdent,
      pageSize
    })
    dispatch('setDataSetPageNoFirst', {
      appWindowIdent: payload.appWindowIdent,
      dataSet: payload.dataSet
    })
  },
  clearDataSet: ({ commit, getters }, payload) => {
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    let layout = getters.getDataSetLayout(
      dataSet,
      getters.getDataSetLayoutIdent(dataSet)
    )
    commit('CLEAR_DATASET', { dataSet, layout })
  },
  incDataSetRefCount: ({ commit, getters }, payload) => {
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    commit('INC_DATASET_REFCOUNT', { dataSet })
  },
  deleteDataSetWhereListsItem: ({ commit, getters }, payload) => {
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    let dataFieldIdent = payload.dataFieldIdent
    commit('DELETE_DATASET_WHERE_LISTS', { dataSet, dataFieldIdent })
  },
  deleteDataSetWhereListItem: async ({ commit, getters, dispatch }, payload) => {
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    let dataFieldIdent = payload.dataFieldIdent
    let dataFieldValue = payload.dataFieldValue
    await commit('DELETE_DATASET_WHERE_LIST_ITEM', {
      dataSet,
      dataFieldIdent,
      dataFieldValue
    })
    let lookupDef = getters.getDataSetLookupDef(
      payload.appWindowIdent,
      payload.dataSetIdent,
      dataFieldIdent
    )
    if (lookupDef && lookupDef.isMultiSelect && payload._keyFieldsValues) {
      let lookupSettersRefresh = lookupDef.lookupSettersRefresh || []
      await lookupSettersRefresh.forEach(item => {
        dispatch('deleteSelectedRow', {
          appWindowIdent: item.appWindowIdentFrom,
          dataSetIdent: item.dataSetIdentFrom,
          row: payload._keyFieldsValues
        })
      })
    }
  },
  setDataSetBusy: ({ commit, getters }, payload) => {
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    commit('SET_DATASET_BUSY', { appWindowIdent: payload.appWindowIdent, dataSet: dataSet })
  },
  setAppWindowData: async ({ dispatch, commit, getters }, payload) => {
    let ord = 0
    let appWindowIdent = payload.appWindowIdent
    let query = payload.query
    let maxOrd = getters.getAppWindowDataSetsMaxOrd(appWindowIdent)
    let dataSetList = null
    let dataSetIdent = null
    let dataToPost = null
    let response = null
    let data = null
    let serverSide = payload.serverSide
    while (ord < maxOrd) {
      ord++
      dataSetList = getters.getDataSetsToRefresh(appWindowIdent, ord)
      if (dataSetList == null || dataSetList.length == 0) {
        continue
      }
      for (let i = 0; i < dataSetList.length; i++) {
        dataSetIdent = null
        dataSetIdent = dataSetList[i].dataSetIdent
        await dispatch('setDataSetBusy', {
          appWindowIdent: appWindowIdent,
          dataSetIdent: dataSetIdent
        })
        await dispatch('fillDataSetWhere', {
          appWindowIdent: appWindowIdent,
          dataSetIdent: dataSetIdent
        })
      }
      for (let i = 0; i < dataSetList.length; i++) {
        await dispatch('incDataSetRefCount', {
          appWindowIdent: appWindowIdent,
          dataSetIdent: dataSetIdent
        })
      }
      response = null
      dataToPost = null
      dataToPost = await getters.getAPIDataRequest(appWindowIdent, dataSetList, serverSide)
      response = await axios.post(
        store.getters['csServerSettings/getAPIDataMethodURL'](
          'getData',
          serverSide
        ),
        dataToPost
      )
      await commit('SET_ERRORS', {
        appWindowIdent: appWindowIdent,
        dataSetIdent: dataSetIdent,
        errors: response.errors
      })
      data = null
      data = response.data
      if (data !== null) {
        let wasErrors = await commit('SET_ERRORS', {
          appWindowIdent: appWindowIdent,
          dataSetIdent: dataSetIdent,
          errors: data.errors
        })
        if (!wasErrors) {
          await commit('SET_APPWINDOWDATA', {
            appWindowIdent,
            dataSetList,
            data,
            query
          })
        }
      }
      for (let i = 0; i < dataSetList.length; i++) {
        if (dataSetList[i].crLocData === 1) {
          await dispatch('fillDataSetsFromGetters', {
            appWindowIdent: appWindowIdent,
            dataSetIdent: dataSetList[i].dataSetIdent
          })
        }
        if (!getters.getDataSetPivotIsEmpty(dataSetList[i])) {
          let pivotCurrentRowIndex = 0
          let pivotCurrentColIndex = 0
          let pivotCurrentDataFieldIdent = getters.getDataSetAggrFields(
            dataSetList[i]
          )[0].dataFieldIdent
          switch (dataSetList[i].scrollDirection) {
          case dataSetUtils.scrollDirection.right:
            pivotCurrentRowIndex =
              dataSetList[i].pivotPrevRowIndex <
                dataSetList[i].pivotRows.length
                ? dataSetList[i].pivotPrevRowIndex
                : 0
            pivotCurrentDataFieldIdent =
              dataSetList[i].pivotPrevDataFieldIdent
            break
          case dataSetUtils.scrollDirection.left:
            pivotCurrentRowIndex =
              dataSetList[i].pivotPrevRowIndex <
                dataSetList[i].pivotRows.length
                ? dataSetList[i].pivotPrevRowIndex
                : 0
            pivotCurrentDataFieldIdent =
              dataSetList[i].pivotPrevDataFieldIdent
            break
          case dataSetUtils.scrollDirection.bottom:
            pivotCurrentColIndex =
              dataSetList[i].pivotPrevColIndex <
                dataSetList[i].pivotCols.length
                ? dataSetList[i].pivotPrevColIndex
                : 0
            break
          case dataSetUtils.scrollDirection.top:
            pivotCurrentColIndex =
              dataSetList[i].pivotPrevColIndex <
                dataSetList[i].pivotCols.length
                ? dataSetList[i].pivotPrevColIndex
                : 0
            break
          }
          await dispatch('setDataSetCurrentPivotIndex', {
            appWindowIdent: appWindowIdent,
            dataSetIdent: dataSetList[i].dataSetIdent,
            pivotCurrentRowIndex: pivotCurrentRowIndex,
            pivotCurrentColIndex: pivotCurrentColIndex,
            pivotCurrentDataFieldIdent: pivotCurrentDataFieldIdent
          })
        }
      }
    }
  },
  invokeAction: async ({ dispatch, commit, getters, state }, payload) => {
    if (payload.actionIdent == null) return
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    let rowIndex = payload.rowIndex
    let row = payload.row
    let action = getters.getDataSetAction(dataSet, payload.actionIdent)
    if (!action) return
    let actionState = getters.getDataSetActionState(dataSet, payload.actionIdent, row)
    if (actionState === 0) return
    if (action.addNewRow && payload.execute !== 1) {
      await dispatch('addRow', {
        dataSet: dataSet,
        fieldsIdents: action.fieldsIdents,
        row: payload.row
      })
      rowIndex = dataSet.rows.length - 1
      row = dataSet.rows[rowIndex]
    }
    if (action.showView === 1 && payload.execute !== 1) {
      let activeAppWindow = getters.getAppWindow(getters.activeWindowIdent)
      await commit('ADD_MODAL_WINDOW', {
        appWindow: activeAppWindow,
        data: {
          appWindowIdent: payload.appWindowIdent,
          dataSetIdent: payload.dataSetIdent,
          actionIdent: payload.actionIdent,
          onCFDataFieldIdent: payload.onCFDataFieldIdent,
          row: row,
          rowIndex: rowIndex,
          addNewRow: action.addNewRow
        }
      })
      return
    }
    await commit('SET_DATASET_ACTION_STATE', { action: action, row: row, state: 0 })
    await commit('CLEAR_ERRORFIELDS', {
      dataSet: dataSet
    })
    if (action.uploadFiles === 1) {
      await dispatch('putAllFiles', { dataSet })
      if (!getters.isFilesUploaded(dataSet)) {
        await commit('SET_DATASET_ACTION_STATE', { action: action, row: row, state: -1 })
        return
      }
    }
    if (payload.actionIdent === 'csLogin') {
      let loginPayload = {
        appWindowIdent: payload.appWindowIdent,
        dataSetIdent: payload.dataSetIdent
      }
      loginPayload.login = row ? row.login : null
      loginPayload.password = row ? row.password : null
      loginPayload.uPwd = row ? row.uPwd : null
      loginPayload.uPwd = row ? row.rPwd : null
      loginPayload.router = payload.router
      loginPayload.row = payload.row
      await dispatch('loginUsr', loginPayload)
    } else if (payload.actionIdent === 'csLogout') {
      await dispatch('logoutUsr', payload)
    } else if (action && (action.kind === 'exportXLSX' || action.kind === 'exportCSV' || action.kind === 'exportTXT')) {
      await dispatch('exportData', payload)
    } else {
      let where = dataSet ? dataSet.where : null
      let selectedRows = dataSet ? dataSet.selectedRows : null
      let sources = getters.getDataSetActionSourcesValues(action)
      let refreshParamsJSON = getters.getRefreshParams()
      let dataToPost = {
        appWindowIdent: getters.getAppWindowIdent(payload.appWindowIdent),
        dataSetIdent: payload.dataSetIdent,
        actionIdent: payload.actionIdent,
        sessionId: getters.getSessionId(state),
        connection: refreshParamsJSON ? getters.getAPIConnectionData : undefined,
        csAppNameSpacesG: getters.csAppNameSpacesG,
        where: getters.undefinedWhenObjNull(getters.getDataSetActionWhere(action, where), true),
        selectedRows: getters.undefinedWhenArrayEmpty(getters.getDataSetActionSelectedRows(action, selectedRows)),
        row: getters.undefinedWhenObjNull(getters.getDataSetActionRow(action, payload.row), true),
        sources: getters.undefinedWhenObjNull(sources, true),
        onCFDataFieldIdent: payload.onCFDataFieldIdent ? payload.onCFDataFieldIdent : undefined,
        refreshParamsJSON: refreshParamsJSON ? refreshParamsJSON : undefined,
        files: dataSet.files
      }
      let response = await axios.post(
        store.getters['csServerSettings/getAPIDataMethodURL'](
          'invokeAction',
          payload.serverSide
        ),
        dataToPost
      )
      await commit('SET_ERRORS', {
        appWindowIdent: payload.appWindowIdent,
        dataSetIdent: payload.dataSetIdent,
        row: payload.row,
        errors: response.errors,
        action: action
      })
      let data = response.data
      if (data !== null) {
        await commit('SET_ERRORS', {
          appWindowIdent: payload.appWindowIdent,
          dataSetIdent: payload.dataSetIdent,
          row: payload.row,
          errors: data.errors,
          action: action
        })
        await dispatch('processCommands', {
          appWindowIdent: payload.appWindowIdent,
          dataSetIdent: payload.dataSetIdent,
          commands: data.commands,
          row: payload.row,
          where: where,
          router: payload.router,
          window: payload.window
        })
      }
    }
    actionState = getters.getDataSetActionState(dataSet, payload.actionIdent, row)
    if (actionState !== -1) {
      await commit('SET_DATASET_ACTION_STATE', { action: action, row: payload.row, state: 1 })
      if (action.removeFiles === 1)
        await commit('DELETE_ALL_FILES', { dataSet })
      if (payload.execute === 1 && payload.modalWindow)
        await dispatch('deleteModalWindow', payload.modalWindow)
      if (action.clearSelectedRows === 1)
        await commit('DELETE_ALL_SELECTED_ROW', { dataSet })
    }
  },
  exportData: async ({ getters, commit }, payload) => {
    if (!payload.appWindowIdent || !payload.dataSetIdent)
      return
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    let action = getters.getDataSetAction(dataSet, payload.actionIdent)
    let request = getters.getAPIExportDataRequest(payload.appWindowIdent, payload.dataSetIdent, action.kind)
    let response = await axios.post(
      store.getters['csServerSettings/getAPIDataMethodURL']('exportData', payload.serverSide),
      request
    )
    await commit('SET_ERRORS', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: payload.dataSetIdent,
      errors: response.errors,
      action: action,
      row: payload.row
    })
    let data = response.data
    if (!data) return
    if (data.errors) {
      await commit('SET_ERRORS', {
        appWindowIdent: payload.appWindowIdent,
        dataSetIdent: payload.dataSetIdent,
        errors: data.errors,
        action: action,
        row: payload.row
      })
    }
    if (action.state !== -1 && payload.window && data.fileUrl)
      payload.window.location.href = store.getters['csServerSettings/getAPIDataMethodURL']('content/download', payload.serverSide) + data.fileUrl
  },
  downloadFile: async (empty, payload) =>{
    if (!payload.window || payload.remoteFileName == null)
      return
    let localFileName = payload.localFileName == null ? payload.remoteFileName : payload.localFileName
    payload.window.location.href = store.getters['csServerSettings/getAPIDataMethodURL']('content/download', payload.serverSide) + '/' + payload.remoteFileName + '/' + localFileName
  },
  addError: async ({ commit }, payload) => {
    commit('SET_ERRORS', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: payload.dataSetIdent,
      row: payload.row,
      errors: payload.errors
    })
  },
  addMessage: async ({ dispatch, commit }, payload) => {
    commit('SET_MESSAGES', payload.messages)
    await payload.messages.forEach(message => {
      dispatch('processCommands', {
        commands: message.commands
      })
    })
  },
  processCommands: async ({ dispatch }, payload) => {
    let row = payload.row
    let where = payload.where
    let router = payload.router
    let window = payload.window
    if (payload.commands) {
      await payload.commands.forEach(item => {
        let command = item.command
        let payload = item.payload
        payload = { ...payload, row: row, where: where, router: router, window: window}
        if (command) dispatch(command, payload)
      })
    }
  },
  removeError: ({ commit }, payload) => {
    commit('DEL_ERROR', payload)
  },
  clearErrors: ({ state, dispatch }) => {
    while(state.errors.length > 0) {
      dispatch('removeError', {error: state.errors[0]})
    }
  },
  removeMessage: ({ commit }, message) => {
    commit('DEL_MESSAGE', message)
  },
  clearMessages: ({ state, dispatch }) => {
    while(state.messages.length > 0) {
      dispatch('removeMessage', {message: state.messages[0]})
    }
  },
  setDataSetRefReqAll: ({ commit, getters }, payload) => {
    let appWindow = getters.getAppWindow(
      payload.appWindowIdent
    )
    let refreshAggregates = payload.refreshAggregates
    commit('SET_DATASET_REFREQ_ALL', { appWindow, refreshAggregates })
  },
  setDataSetRefReq: ({ commit, getters }, payload) => {
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    let refreshAggregates = payload.refreshAggregates
    commit('SET_DATASET_REFREQ', { dataSet, refreshAggregates })
  },
  setDataSetCurrentRowIndex: ({ dispatch, commit }, payload) => {
    let dataSet = payload.dataSet
    let currentRowIndex = payload.currentRowIndex
    commit('SET_DATASET_CURRENT_ROW_INDEX', { dataSet, currentRowIndex })
    dispatch('refreshDataSetDependence', {
      appWindowIdent: payload.appWindowIdent,
      parentDataSetIdent: dataSet.dataSetIdent,
      refreshAggregates: 1
    })
  },
  setDataSetCurrentRow: ({ dispatch, commit }, payload) => {
    let dataSet = payload.dataSet
    let row = payload.row
    let currentRowIndex = -1
    if (dataSet !== null && dataSet.rows !== null) {
      currentRowIndex = dataSet.rows.indexOf(row)
    }
    commit('SET_DATASET_CURRENT_ROW_INDEX', { dataSet, currentRowIndex })
    dispatch('refreshDataSetDependence', {
      appWindowIdent: payload.appWindowIdent,
      parentDataSetIdent: dataSet.dataSetIdent,
      refreshAggregates: 1
    })
  },
  setDataSetCurrentRowFromFilter: ({getters, commit, dispatch}, payload) => {
    let dataSet = getters.getDataSet(payload.appWindowIdent, payload.dataSetIdent)
    if (!dataSet || !payload.filter)
      return
    if (dataSet.state === dataSetUtils.state.added || dataSet.state === dataSetUtils.state.progress)
      commit('SET_DATASET_CURRENT_ROW_FILTER', { dataSet: dataSet, filter: payload.filter})
    else {
      let row = getters.appWindowDataSetFindRow(payload.appWindowIdent, payload.dataSetIdent, payload.filter)
      if (row)
        dispatch('setDataSetCurrentRow', {dataSet, row})
    }
  },
  setDataSetCurrentPivotIndex: async ({ commit, dispatch, getters }, payload) => {
    let dataSet = getters.getDataSet(
      payload.appWindowIdent,
      payload.dataSetIdent
    )
    let pivotCurrentRowIndex = payload.pivotCurrentRowIndex
    let pivotCurrentColIndex = payload.pivotCurrentColIndex
    let pivotCurrentDataFieldIdent = payload.pivotCurrentDataFieldIdent
    if (dataSet && dataSet.pivotCurrentRowIndex === pivotCurrentRowIndex && 
      dataSet.pivotCurrentColIndex === pivotCurrentColIndex && dataSet.pivotCurrentDataFieldIdent === pivotCurrentDataFieldIdent)
      return
    await commit('SET_DATASET_CURRENT_PIVOT_INDEX', {
      dataSet,
      pivotCurrentRowIndex,
      pivotCurrentColIndex,
      pivotCurrentDataFieldIdent
    })
    await dispatch('refreshDataSetDependence', {
      appWindowIdent: payload.appWindowIdent,
      parentDataSetIdent: payload.dataSetIdent,
      refreshAggregates: 1
    })
  },
  setDataSetColFieldAttr: async ({ getters, commit }, payload) => {
    let dataSet = payload.dataSet
    let colFieldIndex = payload.colFieldIndex
    let colFields = getters.getDataSetColFields(dataSet)
    let colField = colFields[colFieldIndex]
    let attr = payload.attr
    commit('SET_DATASET_COL_FIELD_ATTR', { dataSet, colField, attr })
  },
  setDataSetVisibleColFieldAttr: async ({ getters, commit }, payload) => {
    let dataSet = payload.dataSet
    let colFieldIndex = payload.colFieldIndex
    let colFields = getters.getDataSetVisibleColFields(dataSet)
    let colField = colFields[colFieldIndex]
    let attr = payload.attr
    commit('SET_DATASET_COL_FIELD_ATTR', { dataSet, colField, attr })
  },
  setDataSetVisibleColFieldSortedAttr: async (
    { getters, commit },
    payload
  ) => {
    let dataSet = payload.dataSet
    let colFieldIndex = payload.colFieldIndex
    let colFields = getters.getDataSetVisibleColFieldsSorted(dataSet)
    let colField = colFields[colFieldIndex]
    let attr = payload.attr
    commit('SET_DATASET_COL_FIELD_ATTR', { dataSet, colField, attr })
  },
  setDataSetFirstRow: ({ commit }, dataSet) => {
    if (dataSet != null && dataSet.rows.length > 1) {
      let currentRowIndex = 0
      commit('SET_DATASET_CURRENT_ROW_INDEX', { dataSet, currentRowIndex })
    }
  },
  setDataSetPrevRow: ({ commit }, dataSet) => {
    let currentRowIndex = dataSet.currentRowIndex
    if (currentRowIndex - 1 >= 0) {
      currentRowIndex--
      commit('SET_DATASET_CURRENT_ROW_INDEX', { dataSet, currentRowIndex })
    }
  },
  setDataSetPrevRowByStep: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let currentRowIndex = dataSet.currentRowIndex
    let pageNo = dataSet.pageNo
    let step = payload.step || 1
    let pagesCount = getters.getDataSetPagesCount(dataSet)
    if (currentRowIndex - 1 >= 0) {
      currentRowIndex--
      commit('SET_DATASET_CURRENT_ROW_INDEX', { dataSet, currentRowIndex })
    } else if (currentRowIndex - 1 < 0 && pageNo > 1) {
      pageNo--
      commit('SET_DATASET_PAGENO', { dataSet, pagesCount, pageNo })
      dispatch('dataSetPageChange', {
        appWindowIdent: payload.appWindowIdent,
        dataSetIdent: dataSet.dataSetIdent
      })
      currentRowIndex = dataSet.rows.length - step
      commit('SET_DATASET_CURRENT_ROW_INDEX', { dataSet, currentRowIndex })
    } else if (pageNo === 1 && pagesCount > 1) {
      pageNo = pagesCount
      commit('SET_DATASET_PAGENO', { dataSet, pagesCount, pageNo })
      dispatch('dataSetPageChange', {
        appWindowIdent: payload.appWindowIdent,
        dataSetIdent: dataSet.dataSetIdent
      })
      currentRowIndex = dataSet.rows.length - step
      commit('SET_DATASET_CURRENT_ROW_INDEX', { dataSet, currentRowIndex })
    } else if (pageNo === 1) {
      currentRowIndex = dataSet.rows.length - step
      commit('SET_DATASET_CURRENT_ROW_INDEX', { dataSet, currentRowIndex })
    }
  },
  setDataSetNextRow: ({ commit }, dataSet) => {
    let currentRowIndex = dataSet.currentRowIndex
    if (currentRowIndex + 1 < dataSet.rows.length) {
      currentRowIndex++
      commit('SET_DATASET_CURRENT_ROW_INDEX', { dataSet, currentRowIndex })
    }
  },
  setDataSetNextRowByStep: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let currentRowIndex = dataSet.currentRowIndex
    let pageNo = dataSet.pageNo
    let step = payload.step || 1
    let pagesCount = getters.getDataSetPagesCount(dataSet)
    if (currentRowIndex + step < dataSet.rows.length) {
      currentRowIndex++
      commit('SET_DATASET_CURRENT_ROW_INDEX', { dataSet, currentRowIndex })
    } else if (
      currentRowIndex + step >= dataSet.rows.length &&
      pageNo < pagesCount
    ) {
      pageNo++
      commit('SET_DATASET_PAGENO', { dataSet, pagesCount, pageNo })
      dispatch('dataSetPageChange', {
        appWindowIdent: payload.appWindowIdent,
        dataSetIdent: dataSet.dataSetIdent
      })
    } else if (pageNo === pagesCount && pagesCount === 1) {
      currentRowIndex = 0
      commit('SET_DATASET_CURRENT_ROW_INDEX', { dataSet, currentRowIndex })
    } else if (pageNo === pagesCount)
      dispatch('setDataSetPageNoFirst', payload)
  },
  setDataSetFieldValue: async ({ dispatch }, payload) => {
    if (payload.dataFieldIdent === null) return null
    let action = 'setDataSetRowsFieldValue'
    switch (payload.sourceKind) {
    case 'aggregates':
      action = 'setDataSetAggregatesFieldValue'
      break
    case 'where':
      action = 'setDataSetWhereFieldValue'
      break
    case 'pivotValues':
      action = 'setDataSetPivotValuesFieldValue'
      break
    }
    await dispatch(action, payload)
  },
  setDataSetRowStatus: async ({ commit }, payload) => {
    commit('SET_DATASET_ROW_STATUS', {
      row: payload.row,
      status: payload.status
    })
  },
  setDataSetRowsFieldValue: async ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let row = payload.row || getters.getDataSetCurrentRow(dataSet)
    if (!row)
      return
    let dataFieldValue = payload.dataFieldValue
    if (dataFieldValue === '') dataFieldValue = null
    let dataFieldIdent = payload.dataFieldIdent
    await commit('SET_DATASET_ROWS_FIELD_VALUE', {
      row,
      dataFieldIdent,
      dataFieldValue
    })
    await dispatch('setDataSetRowStatus', {
      row: row,
      status: dataSetUtils.rowState.modified
    })
    let onCFActionIdent = getters.getFieldsOnCFActionIdentsOnCFActionIdent(
      dataSet,
      dataFieldIdent
    )
    if (onCFActionIdent && payload.onCFLock !== 1 && payload.oncfTimeout) {
      let action = getters.getDataSetAction(dataSet, onCFActionIdent)
      let timer = setTimeout( () => {
        dispatch('invokeAction', {
          appWindowIdent: payload.appWindowIdent,
          dataSetIdent: dataSet.dataSetIdent,
          actionIdent: onCFActionIdent,
          onCFDataFieldIdent: dataFieldIdent,
          row: row
        })
      }, payload.oncfTimeout)
      await commit('SET_DATASET_ACTION_TIMER', {      
        row,
        action,
        timer
      })
    }
    else if (onCFActionIdent && payload.onCFLock !== 1){
      await dispatch('invokeAction', {
        appWindowIdent: payload.appWindowIdent,
        dataSetIdent: dataSet.dataSetIdent,
        actionIdent: onCFActionIdent,
        onCFDataFieldIdent: dataFieldIdent,
        row: row
      })
    }
  },
  setDataSetAggregatesFieldValue: ({ commit }, payload) => {
    let dataSet = payload.dataSet
    let dataFieldValue = payload.dataFieldValue
    let dataFieldIdent = payload.dataFieldIdent
    commit('SET_DATASET_AGGREGATES_FIELD_VALUE', {
      dataSet,
      dataFieldIdent,
      dataFieldValue
    })
  },
  setDataSetPivotValuesFieldValue: async (
    { dispatch, commit, getters },
    payload
  ) => {
    let dataSet = payload.dataSet
    let dataFieldValue = payload.dataFieldValue
    let dataFieldIdent = payload.dataFieldIdent
    let pivotRow = payload.pivotRow
    let pivotCol = payload.pivotCol
    let pivotRowKey = payload.pivotRowKey
    let row =
      payload.dataSet.pivotValues[pivotRowKey] ||
      getters.getPivotEmptyRow(pivotCol, pivotRow)
    let colFields = getters.getDataSetColFields(dataSet)
    let rowFields = getters.getDataSetRowFields(dataSet)
    let rowTransformed = {}
    colFields.forEach((item, index) => {
      rowTransformed[item.dataFieldIdent] =
        payload.dataSet.pivotCols[row[2]['c']][index][0]
    })
    rowFields.forEach((item, index) => {
      rowTransformed[item.dataFieldIdent] =
        payload.dataSet.pivotRows[row[2]['r']][index][0]
    })
    rowTransformed[payload.dataFieldIdent] = payload.dataFieldValue
    commit('SET_DATASET_PIVOT_VALUES_FIELD_VALUE', {
      dataSet,
      row,
      pivotRowKey,
      dataFieldIdent,
      dataFieldValue
    })
    await dispatch('invokeAction', {
      appWindowIdent: payload.appWindowIdent,
      dataSetIdent: payload.dataSet.dataSetIdent,
      actionIdent: payload.dataSet.pivotUpdateActionIdent,
      row: rowTransformed
    })
  },
  setDataSetWhereFieldValue: async (
    { dispatch, commit, getters },
    payload
  ) => {
    let dataSet = payload.dataSet
    let dataFieldValue = payload.dataFieldValue
    let dataFieldIdent = payload.dataFieldIdent
    commit('SET_DATASET_WHERE_FIELD_VALUE', {
      dataSet,
      dataFieldValue,
      dataFieldIdent
    })
    let onCFActionIdent = getters.getDataSetWhereOnCFActionIdentsOnCFActionIdent(
      dataSet,
      dataFieldIdent
    )
    if (onCFActionIdent && payload.onCFLock !== 1 && payload.oncfTimeout) {
      let action = getters.getDataSetAction(dataSet, onCFActionIdent)
      let timer = setTimeout( async () => {
        await dispatch('invokeAction', {
          appWindowIdent: payload.appWindowIdent,
          dataSetIdent: dataSet.dataSetIdent,
          actionIdent: onCFActionIdent,
          onCFDataFieldIdent: dataFieldIdent
        })
        if (payload.refreshLock !== 1){
          let whereFieldsIdent = getters.getDataSetWhereFieldsIdentsDataField(dataSet, dataFieldIdent)
          if (!whereFieldsIdent || whereFieldsIdent.refreshDependency !== 1)
            return
    
          await dispatch('refreshDataSet', {
            appWindowIdent: payload.appWindowIdent,
            dataSetIdent: dataSet.dataSetIdent,
            refreshAggregates: 1
          })
        }
      }, payload.oncfTimeout)
      await commit('SET_DATASET_ACTION_TIMER', {      
        action,
        timer
      })
    }
    else if (onCFActionIdent && payload.onCFLock !== 1) {
      await dispatch('invokeAction', {
        appWindowIdent: payload.appWindowIdent,
        dataSetIdent: dataSet.dataSetIdent,
        actionIdent: onCFActionIdent,
        onCFDataFieldIdent: dataFieldIdent
      })
      if (payload.refreshLock !== 1){
        let whereFieldsIdent = getters.getDataSetWhereFieldsIdentsDataField(dataSet, dataFieldIdent)
        if (!whereFieldsIdent || whereFieldsIdent.refreshDependency !== 1)
          return
  
        await dispatch('refreshDataSet', {
          appWindowIdent: payload.appWindowIdent,
          dataSetIdent: dataSet.dataSetIdent,
          refreshAggregates: 1
        })
      }
    }
  },
  setDataSetWhereListsFieldValue: ({ commit }, payload) => {
    let dataSet = payload.dataSet
    let lookupDataFieldIdent = payload.lookupDataFieldIdent
    let whereListValue = payload.whereListValue
    commit('SET_DATASET_WHERE_LISTS_FIELD_VALUE', {
      dataSet,
      lookupDataFieldIdent,
      whereListValue
    })
  },
  pushRegisterSubscription: async ({ commit, getters, state }, payload) => {
    let dataToPost = {
      sessionId: getters.getSessionId(state),
      subscription: payload.subscription
    }
    let response = await axios.post(
      store.getters['csServerSettings/getAPIDataMethodURL'](
        'pushRegisterSubscription',
        payload.serverSide
      ),
      dataToPost
    )
    await commit('SET_ERRORS', {
      errors: response.errors
    })
  },
  pushSendTestMessage: async ({ commit, getters, state }, payload) => {
    let dataToPost = {
      sessionId: getters.getSessionId(state),
      subscription: payload.subscription,
      title: payload.title,
      url: payload.url,
      body: payload.body
    }
    let response = await axios.post(
      store.getters['csServerSettings/getAPIDataMethodURL'](
        'pushSendNotify',
        payload.serverSide
      ),
      dataToPost
    )
    await commit('SET_ERRORS', {
      errors: response.errors
    })
  },
  putFile: async ({ commit }, payload) => {
    let file = payload.file
    let dataToPost = new FormData()
    dataToPost.append(payload.file.__uuid, file.file)
    let config = {
      onUploadProgress: function (progressEvent) {
        let progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        commit('SET_FILE_PROGRESS', { file, progress })
      },
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
    await commit('SET_FILE_STATUS', { file: file, status: dataSetUtils.fileState.uploading })
    let url = store.getters['csServerSettings/getAPIDefinitionMethodURL'](
      'putFiles',
      payload.serverSide
    )
    let response = await axios.put(
      url,
      dataToPost,
      config
    )
    await commit('SET_ERRORS', {
      errors: response.errors
    })
    if (response.data)
      await commit('SET_ERRORS', {
        errors: response.data.errors
      })
    if (response.errors || (response.data && response.data.errors))
      await commit('SET_FILE_STATUS', { file: file, status: dataSetUtils.fileState.error })
    else if (response.data) {
      await commit('SET_FILE_STATUS', { file: file, status: dataSetUtils.fileState.uploaded })
      await commit('SET_FILE_DATA', { file: file, data: response.data.data ? response.data.data[0] : undefined })
    }
  },
  putAllFiles: async ({ dispatch }, payload) => {
    if (!payload.dataSet)
      return
    let files = payload.dataSet.files
    await Promise.all(
      files.map(async file => {
        if (file._status !== dataSetUtils.fileState.uploaded)
          await dispatch('putFile', { file })
      })
    )
  },
  deleteAllFiles: async ({ commit }, payload) => {
    if (!payload.dataSet)
      return
    await commit('DELETE_ALL_FILES', payload)
  },
  setScrollDirection: ({ commit }, payload) => {
    let dataSet = payload.dataSet
    let scrollDirection = payload.scrollDirection
    commit('SET_DATASET_SCROLL_DIRECTION', { dataSet, scrollDirection })
  },
  setColFieldOrd: ({ commit, getters }, payload) => {
    let dataSet = payload.dataSet
    let ord = payload.ord
    let ordOld = payload.colField.ord
    let colFields = getters.getDataSetColFields(dataSet)
    if (ord < 1) ord = 1
    if (ord > colFields.length) ord = colFields.length
    if (ord === ordOld) return
    if (colFields) {
      colFields.forEach(el => {
        if (el.ord === ordOld)
          commit('SET_COL_FIELD_ORD', { colField: el, ord: ord })
        else if (ordOld > ord && el.ord < ordOld && el.ord >= ord)
          commit('SET_COL_FIELD_ORD', { colField: el, ord: el.ord + 1 })
        else if (ordOld < ord && el.ord > ordOld && el.ord <= ord)
          commit('SET_COL_FIELD_ORD', { colField: el, ord: el.ord - 1 })
      })
    }
  },
  setSortColFieldOrd: ({ commit, getters }, payload) => {
    let dataSet = payload.dataSet
    let ord = payload.ord
    let ordOld = payload.sortColField.ord
    let sortColFields = getters.getDataSetSortColFields(dataSet)
    if (ord < 1) ord = 1
    if (ord > sortColFields.length) ord = sortColFields.length
    if (ord === ordOld) return
    if (sortColFields) {
      sortColFields.forEach(el => {
        if (el.ord === ordOld)
          commit('SET_SORT_COL_FIELD_ORD', { sortColField: el, ord: ord })
        else if (ordOld > ord && el.ord < ordOld && el.ord >= ord)
          commit('SET_SORT_COL_FIELD_ORD', {
            sortColField: el,
            ord: el.ord + 1
          })
        else if (ordOld < ord && el.ord > ordOld && el.ord <= ord)
          commit('SET_SORT_COL_FIELD_ORD', {
            sortColField: el,
            ord: el.ord - 1
          })
      })
    }
  },
  setColFieldVisibility: ({ commit }, payload) => {
    let colField = payload.colField
    let isVisible = payload.isVisible
    commit('SET_COL_FIELD_VISIBILITY', { colField, isVisible })
  },
  setLayoutSortIdentToUsrDefinedWithCopy: ({ commit, getters }, payload) => {
    let dataSet = payload.dataSet
    let layout = getters.getDataSetLayout(
      dataSet,
      getters.getDataSetLayoutIdent(dataSet)
    )
    let sortIdents = getters.getDataSetSortIdents(dataSet)
    let currentSortIdent = getters.getDataSetSort(
      dataSet,
      getters.getDataSetSortIdent(dataSet)
    )
    if (layout === null || sortIdents === null) return
    let sortIdent = sortIdents.find(item => {
      return item.isUsrDefined === 1
    })
    if (sortIdent) {
      if (currentSortIdent)
        commit('SET_SORT_IDENT_SORT_COL_FIELDS', {
          sortIdent: sortIdent,
          sortColFields: currentSortIdent.sortColFields.concat()
        })
      commit('SET_LAYOUT_SORTIDENT', {
        layout: layout,
        sortIdent: sortIdent.sortIdent
      })
    }
  },
  setSortIdentSortColFields: ({ commit }, payload) => {
    commit('SET_SORT_IDENT_SORT_COL_FIELDS', { payload })
  },
  setLayoutSortIdentToUsrDefined: ({ commit, getters }, payload) => {
    let dataSet = payload.dataSet
    let layout = getters.getDataSetLayout(
      dataSet,
      getters.getDataSetLayoutIdent(dataSet)
    )
    let sortIdents = getters.getDataSetSortIdents(dataSet)
    if (layout === null || sortIdents === null) return
    let sortIdent = sortIdents.find(item => {
      return item.isUsrDefined === 1
    })
    if (sortIdent) {
      commit('SET_LAYOUT_SORTIDENT', {
        layout: layout,
        sortIdent: sortIdent.sortIdent
      })
    }
  },
  addSortColFieldToSortIdent: ({ commit, getters }, payload) => {
    let dataSet = payload.dataSet
    let sortIdent = getters.getDataSetSort(
      dataSet,
      getters.getDataSetSortIdent(dataSet)
    )
    let colField = payload.colField
    if (colField && sortIdent) {
      let sortColFields = getters.getDataSetSortColFields(dataSet)
      let currentSortColFieldIndex = sortColFields.length
      let ord = 1
      if (sortColFields && sortColFields.length > 0)
        ord = sortColFields[sortColFields.length - 1].ord + 1
      let sortColField = {
        dataFieldIdent: colField.dataFieldIdent,
        dataFieldColTranslatedDesc: colField.dataFieldColTranslatedDesc,
        isDesc: 0,
        sortType: 0,
        ord: ord
      }
      commit('ADD_SORT_IDENT_SORT_COL_FIELD', { sortIdent, sortColField })
      commit('SET_CURRENT_SORT_COL_FIELD_INDEX', {
        sort: sortIdent,
        currentSortColFieldIndex: currentSortColFieldIndex
      })
    }
  },
  deleteSortColField: ({ commit, getters, dispatch }, payload) => {
    let dataSet = payload.dataSet
    let ord = getters.getDataSetSortColFields(dataSet).length
    let sortIdent = getters.getDataSetSort(
      dataSet,
      getters.getDataSetSortIdent(dataSet)
    )
    dispatch('setSortColFieldOrd', {
      dataSet: dataSet,
      sortColField: payload.sortColField,
      ord: ord
    })
    commit('DELETE_SORT_IDENT_SORT_COL_FIELD', {
      sortIdent: sortIdent,
      sortColField: payload.sortColField
    })
    let currentSortColFieldIndex = getters.getCurrentSortColFieldIndex(
      dataSet
    )
    currentSortColFieldIndex =
      currentSortColFieldIndex >= ord - 1
        ? currentSortColFieldIndex === 0
          ? 0
          : currentSortColFieldIndex - 1
        : currentSortColFieldIndex
    commit('SET_CURRENT_SORT_COL_FIELD_INDEX', {
      sort: sortIdent,
      currentSortColFieldIndex: currentSortColFieldIndex
    })
  },
  deleteAllSortColFields: ({ commit, getters }, payload) => {
    let dataSet = payload.dataSet
    let sortIdent = getters.getDataSetSort(
      dataSet,
      getters.getDataSetSortIdent(dataSet)
    )
    commit('DELETE_ALL_SORT_IDENT_SORT_COL_FIELDS', { sortIdent })
  },
  setSortColFieldsIsDesc: ({ commit }, payload) => {
    commit('SET_SORT_COL_FIELD_IS_DESC', payload)
  },
  setCurrentColField: ({ commit, getters }, payload) => {
    let dataSet = payload.dataSet
    if (dataSet == null) return
    let colField = payload.colField
    let currentColFieldIndex = -1
    let layout = getters.getDataSetLayout(
      dataSet,
      getters.getDataSetLayoutIdent(dataSet)
    )
    if (layout !== null && layout.colFields !== null) {
      currentColFieldIndex = layout.colFields.indexOf(colField)
    }
    if (currentColFieldIndex > -1)
      commit('SET_CURRENT_COL_FIELD_INDEX', { layout, currentColFieldIndex })
  },
  setCurrentSortColField: ({ commit, getters }, payload) => {
    let dataSet = payload.dataSet
    if (dataSet == null) return
    let sortColField = payload.sortColField
    let currentSortColFieldIndex = -1
    let sort = getters.getDataSetSort(
      dataSet,
      getters.getDataSetSortIdent(dataSet)
    )
    if (sort !== null && sort.sortColFields !== null) {
      currentSortColFieldIndex = sort.sortColFields.indexOf(sortColField)
    }
    if (currentSortColFieldIndex > -1)
      commit('SET_CURRENT_SORT_COL_FIELD_INDEX', {
        sort,
        currentSortColFieldIndex
      })
  },
  setRefreshParams: ({ commit }, payload) => {
    commit('SET_REFRESH_PARAMS', payload)
  },
  deleteAppWindowsAll: async ({ state, getters, dispatch, commit }) => {
    await commit('SETACTIVE_APPWINDOW', { appWindowIdent: null })
    await commit('CLEAR_PATHS')
    dispatch('clearErrors', {state: state, dispatch: dispatch})
    dispatch('clearMessages', {state: state, dispatch: dispatch})
    for (let key in getters.csAppWindows) {
      await commit('DELETE_APPWINDOW', { appWindowIdent: key })
    }
  },
  deleteModalWindow: async ({ commit, getters }, payload) => {
    let modalWindows = getters.getAppWindowModalWindows(payload.appWindowIdent)
    let modalWindow = modalWindows && payload.modalWindowIndex ? modalWindows[payload.modalWindowIndex] : null
    if (!modalWindow) return
    if (modalWindow.addNewRow) {
      await commit('DELETE_ROW', {
        dataSet: getters.getDataSet(modalWindow.appWindowIdent, modalWindow.dataSetIdent),
        row: modalWindow.row
      })
    }
    await commit('DELETE_MODAL_WINDOW', {
      modalWindows: modalWindows,
      modalWindowIndex: payload.modalWindowIndex
    })
  },
  setDataSetAggrFieldCalc4Cols: ({ commit }, payload) => {
    commit('SET_DATASET_AGGRFIELD_CALC4COLS', payload)
  },
  setDataSetAggrFieldsCalc4Cols: ({ dispatch, getters }, payload) => {
    if (!payload.dataSet)
      return
    let aggrFields = getters.getDataSetAggrFields(payload.dataSet)
    aggrFields.forEach(aggrField => {
      dispatch('setDataSetAggrFieldCalc4Cols', {
        aggrField: aggrField,
        calc4Cols: payload.calc4Cols
      })
    })
  },
  setDataSetAggrFieldCalc4Rows: ({ commit }, payload) => {
    commit('SET_DATASET_AGGRFIELD_CALC4ROWS', payload)
  },
  setDataSetAggrFieldsCalc4Rows: ({ dispatch, getters }, payload) => {
    if (!payload.dataSet)
      return
    let aggrFields = getters.getDataSetAggrFields(payload.dataSet)
    aggrFields.forEach(aggrField => {
      dispatch('setDataSetAggrFieldCalc4Rows', {
        aggrField: aggrField,
        calc4Rows: payload.calc4Rows
      })
    })
  }
}
