import Vue from 'vue'
import store from '@/store'
import constructors from '../../../classes/constructors'
import dataSetUtils from '../../../classes/dataSetUtils'
import stringUtils from '../../../classes/stringUtils'
import { uuid } from 'vue-uuid'

export default {
  ADD_LOG(state, payload) {
    state.log.push({
      date: Date(),
      messageText: payload.messageText
    })
  },
  SET_SESSIONID(state, payload) {
    state.sessionId = payload.sessionId
    state.refreshParams = 1
  },
  LOCK_URL(state){
    state.urlLock = true
  },
  UNLOCK_URL(state){
    state.urlLock = false
  },
  ADD_APPWINDOW(state, payload) {
    if (!state.csAppWindows[payload.appWindowIdent]){
      state.csAppWindows = {
        ...state.csAppWindows,
        [payload.appWindowIdent]: payload.appWindow
      }
    } else {
      state.csAppWindows[payload.appWindowIdent].commands = payload.appWindow.commands
    }
    if (payload.appWindow && payload.setActive) {
      state.activeWindowIdent = payload.appWindowIdent
    }
    if (
      payload.path &&
      payload.appWindow.appWindowIdent !== payload.mainAppWindowIdent
    ) {
      state.paths[payload.path] = {
        appWindowIdent: payload.appWindowIdent,
        params: payload.appWindow.params,
        commands: payload.appWindow.commands
      }
    }
    if (payload.lookupDef)
      state.csAppWindows[payload.appWindowIdent].lookupDef = payload.lookupDef
    state.refreshParams = 0
    state.log.push({
      date: Date(),
      messageText: 'Window added: ' + payload.appWindowIdent
    })
  },
  DELETE_APPWINDOW(state, payload) {
    if (state.activeWindowIdent === payload.appWindowIdent)
      state.activeWindowIdent = null
    Vue.delete(state.csAppWindows, payload.appWindowIdent)
  },
  CLEAR_PATHS(state) {
    for (let key in state.paths) {
      Vue.delete(state.paths, key)
    }
  },
  SETACTIVE_APPWINDOW(state, payload) {
    if (state.activeWindowIdent !== payload.appWindowIdent)
      state.activeWindowIdent = payload.appWindowIdent
  },
  SET_DATASET_PAGENO(state, payload) {
    if (
      payload.dataSet &&
      payload.dataSet.pageNo > 0 &&
      payload.pageNo <= payload.pagesCount
    ) {
      payload.dataSet.pageNo = payload.pageNo
    }
  },
  SET_DATASET_PIVOT_COLS_PAGENO(state, payload) {
    if (
      payload.dataSet &&
      payload.layout &&
      payload.layout.pageNoX > 0 &&
      payload.pageNo <= payload.pagesCount
    ) {
      payload.layout.pageNoX = payload.pageNo
    }
  },
  SET_DATASET_PIVOT_ROWS_PAGENO(state, payload) {
    if (
      payload.dataSet &&
      payload.layout &&
      payload.layout.pageNoY > 0 &&
      payload.pageNo <= payload.pagesCount
    ) {
      payload.layout.pageNoY = payload.pageNo
    }
  },
  SET_DATASET_COL_FIELD_ATTR(state, payload) {
    if (payload.attr.width !== undefined)
      payload.colField['width'] = payload.attr.width
    if (payload.attr.isResizing !== undefined)
      payload.colField['isResizing'] = payload.attr.isResizing
  },
  SET_DATASET_CURRENT_ROW_INDEX(state, payload) {
    let currentRowIndex = payload.currentRowIndex
    if (payload.dataSet !== null && payload.dataSet.rows !== null) {
      if (payload.dataSet.rows.length == 0) {
        currentRowIndex = -1
      } else if (currentRowIndex < 0 && payload.dataSet.rows.length > 0) {
        currentRowIndex = 0
      } else if (currentRowIndex >= payload.dataSet.rows.length) {
        currentRowIndex = payload.dataSet.rows.length - 1
      }
      payload.dataSet.currentRowIndex = currentRowIndex
    }
  },
  SET_DATASET_CURRENT_PIVOT_INDEX(state, payload) {
    if (payload.dataSet) {
      payload.dataSet.pivotCurrentRowIndex = payload.pivotCurrentRowIndex
      payload.dataSet.pivotCurrentColIndex = payload.pivotCurrentColIndex
      payload.dataSet.pivotCurrentDataFieldIdent =
        payload.pivotCurrentDataFieldIdent
    }
  },
  SET_DATASET_PAGENOFIRST(state, payload) {
    if (payload.dataSet) {
      payload.dataSet.pageNo = 1
    }
  },
  SET_DATASET_PIVOT_COLS_PAGENOFIRST(state, payload) {
    if (payload.layout) {
      payload.layout.pageNoX = 1
    }
  },
  SET_DATASET_PIVOT_ROWS_PAGENOFIRST(state, payload) {
    if (payload.layout) {
      payload.layout.pageNoY = 1
    }
  },
  SET_DATASET_PAGENOLAST(state, payload) {
    if (payload.dataSet && payload.pagesCount) {
      payload.dataSet.pageNo = payload.pagesCount
    }
  },
  SET_DATASET_PIVOT_COLS_PAGENOLAST(state, payload) {
    if (payload.layout && payload.pagesCount) {
      payload.layout.pageNoX = payload.pagesCount
    }
  },
  SET_DATASET_PIVOT_ROWS_PAGENOLAST(state, payload) {
    if (payload.layout && payload.pagesCount) {
      payload.layout.pageNoY = payload.pagesCount
    }
  },
  SET_DATASET_PAGENONEXT(state, payload) {
    if (
      payload.dataSet &&
      payload.pagesCount &&
      payload.dataSet.pageNo < payload.pagesCount
    ) {
      payload.dataSet.pageNo++
    }
  },
  SET_DATASET_PIVOT_COLS_PAGENONEXT(state, payload) {
    if (
      payload.layout &&
      payload.pagesCount &&
      payload.layout.pageNoX < payload.pagesCount
    ) {
      payload.layout.pageNoX++
    }
  },
  SET_DATASET_PIVOT_ROWS_PAGENONEXT(state, payload) {
    if (
      payload.layout &&
      payload.pagesCount &&
      payload.layout.pageNoY < payload.pagesCount
    ) {
      payload.layout.pageNoY++
    }
  },
  SET_DATASET_PAGENOPREV(state, payload) {
    if (payload.dataSet && payload.dataSet.pageNo > 1) {
      payload.dataSet.pageNo--
    }
  },
  SET_DATASET_PIVOT_COLS_PAGENOPREV(state, payload) {
    if (payload.layout && payload.layout.pageNoX > 1) {
      payload.layout.pageNoX--
    }
  },
  SET_DATASET_PIVOT_ROWS_PAGENOPREV(state, payload) {
    if (payload.layout && payload.layout.pageNoY > 1) {
      payload.layout.pageNoY--
    }
  },
  SET_DATASET_WHERE(state, payload) {
    if (payload.dataSet) {
      payload.dataSet.where = Object.assign(
        payload.dataSet.where,
        payload.where
      )
    }
  },
  CLEAR_DATASET(state, payload) {
    dataSetUtils.clearDataSet(payload)
  },
  CLEAR_ERRORFIELDS(state, payload) {
    for (let key in payload.dataSet.infoFields) {
      delete payload.dataSet.infoFields[key]
    }
    for (let key in payload.dataSet.warningFields) {
      delete payload.dataSet.warningFields[key]
    }
    for (let key in payload.dataSet.errorFields) {
      delete payload.dataSet.errorFields[key]
    }
  },
  DELETE_DATASET_WHERE_LISTS(state, payload) {
    if (payload.dataSet.whereLists[payload.dataFieldIdent]){
      while (payload.dataSet.whereLists[payload.dataFieldIdent].length > 0)
        payload.dataSet.whereLists[payload.dataFieldIdent].pop()
      delete payload.dataSet.whereLists[payload.dataFieldIdent]
    }
  },
  DELETE_DATASET_WHERE_LIST_ITEM(state, payload) {
    let index = payload.dataSet.whereLists[payload.dataFieldIdent].findIndex(
      item => item[payload.dataFieldIdent] === payload.dataFieldValue
    )
    if (index !== -1)
      payload.dataSet.whereLists[payload.dataFieldIdent].splice(index, 1)
  },
  SET_DATASET_BUSY(state, payload) {
    if (payload.dataSet) {
      payload.dataSet.state = 0
    }
    let appWindow = state.csAppWindows[payload.appWindowIdent]
    if (appWindow)
      appWindow.stateChangeCount += 1
  },
  SET_DATASET_CURRENT_ROW_FILTER(state, payload){
    if (payload.dataSet) 
      payload.dataSet.currentRowFilter = payload.filter
  },
  SET_ERRORS(state, payload) {
    if (!payload) return
    if (!payload.errors) return
    if (!Array.isArray(payload.errors)) {
      if (payload.errors.code && payload.errors.originalError && payload.errors.originalError.info) {
        payload.errors = [
          { messageText: payload.errors.originalError.info.message }
        ]
      } else {
        payload.errors = [{ messageText: payload.errors }]
      }
    }
    let row = payload.row
    payload.errors.forEach(error => {
      error = { ...error, appWindowIdent: payload.appWindowIdent, dataSetIdent: payload.dataSetIdent, row: row, __uuid: payload.id, isVisible: true }
      let autoCloseTimeout = error.autoCloseTimeout
      let showKind = error.showKind === null || error.showKind === undefined ? 0 : error.showKind
      if (
        payload.appWindowIdent &&
        payload.dataSetIdent &&
        error.errorFields
      ) {
        let messageType = error.messageType === null || error.messageType === undefined ? 1 : error.messageType
        error.errorFields.forEach(errorField => {
          let fieldsType
          switch (messageType) {
          case 1:
            fieldsType = 'errorFields'
            break
          case 2:
            fieldsType = 'warningFields'
            break
          case 3:
            fieldsType = 'infoFields'
            break
          }
          let autoCloseTimeoutId
          if (autoCloseTimeout) {
            autoCloseTimeoutId = setTimeout(
              function (
              ) {
                store.dispatch('csAppWindowsUtils/removeError', {
                  error: error
                })
              }, autoCloseTimeout)
          }
          if (row) {
            fieldsType = '_' + fieldsType
            if(row[fieldsType] != null && row[fieldsType][errorField.errorField] != null) {
              let autoCloseTimeoutIdToClear = row[fieldsType][errorField.errorField].autoCloseTimeoutId
              if(autoCloseTimeoutIdToClear) {
                clearTimeout(autoCloseTimeoutIdToClear)
                row[fieldsType][errorField.errorField].autoCloseTimeoutId = null
              }
            }
            row[fieldsType] = {
              ...row[fieldsType],
              [errorField.errorField]: {
                messageText: error.messageText,
                messageType: messageType,
                showKind: showKind,
                autoCloseTimeoutId: autoCloseTimeoutId
              }
            }
          } else {
            if(state.csAppWindows[payload.appWindowIdent].dataSets[payload.dataSetIdent][fieldsType] != null
              && state.csAppWindows[payload.appWindowIdent].dataSets[payload.dataSetIdent][fieldsType][errorField.errorField] != null
            ) {
              let autoCloseTimeoutIdToClear = state.csAppWindows[payload.appWindowIdent].dataSets[payload.dataSetIdent][fieldsType][errorField.errorField].autoCloseTimeoutId
              if(autoCloseTimeoutIdToClear) {
                clearTimeout(autoCloseTimeoutIdToClear)
                state.csAppWindows[payload.appWindowIdent].dataSets[payload.dataSetIdent][fieldsType][errorField.errorField].autoCloseTimeoutId = null
              }
            }
            state.csAppWindows[payload.appWindowIdent].dataSets[
              payload.dataSetIdent
            ][fieldsType] = {
              ...state.csAppWindows[payload.appWindowIdent].dataSets[
                payload.dataSetIdent
              ][fieldsType],
              [errorField.errorField]: {
                messageText: error.messageText,
                messageType: messageType,
                showKind: showKind,
                autoCloseTimeoutId: autoCloseTimeoutId
              }
            }
          }
        })
      }
      if (showKind == 0) state.errors.unshift(error)
    })
    if (row && payload.action && payload.errors.length > 0) {
      let actionIdent = payload.action.actionIdent
      if (row._actionState[actionIdent] === undefined) {
        row._actionState = { ...row._actionState, [actionIdent]: {state: -1, timer: null} }
      } else {
        row._actionState[actionIdent].state = -1
      }
    }
    else if (payload.action && payload.action.state !== -1 && payload.errors.length > 0)
      payload.action.state = -1
  },
  HIDE_ERROR(state, payload) {
    let error = payload.error
    if (error == null) return
    error.isVisible = false
  },
  DEL_ERROR(state, payload) {
    let error = payload.error
    if (error === null) return
    let appWindowIdent = error.appWindowIdent
    let dataSetIdent = error.dataSetIdent
    let row = error.row
    let appWindow = state.csAppWindows[appWindowIdent]
    let dataSet = appWindow && appWindow.dataSets ? appWindow.dataSets[dataSetIdent] : null
    if (dataSet) {
      let infoFields = dataSet.infoFields
      for (let key in infoFields) {
        if(infoFields[key].autoCloseTimeoutId) {
          clearTimeout(infoFields[key].autoCloseTimeoutId)
          infoFields[key].autoCloseTimeoutId = null
        }
        Vue.delete(infoFields, key)
      }
      let warningFields = dataSet.warningFields
      for (let key in warningFields) {
        if(warningFields[key].autoCloseTimeoutId) {
          clearTimeout(warningFields[key].autoCloseTimeoutId)
          warningFields[key].autoCloseTimeoutId = null
        }
        Vue.delete(warningFields, key)
      }
      let errorFields = dataSet.errorFields
      for (let key in errorFields) {
        if(errorFields[key].autoCloseTimeoutId) {
          clearTimeout(errorFields[key].autoCloseTimeoutId)
          errorFields[key].autoCloseTimeoutId = null
        }
        Vue.delete(errorFields, key)
      }
    }
    if (row) {
      let infoFields = row._infoFields
      for (let key in infoFields) {
        if(infoFields[key].autoCloseTimeoutId) {
          clearTimeout(infoFields[key].autoCloseTimeoutId)
          infoFields[key].autoCloseTimeoutId = null
        }
        Vue.delete(infoFields, key)
      }
      let warningFields = row._warningFields
      for (let key in warningFields) {
        if(warningFields[key].autoCloseTimeoutId) {
          clearTimeout(warningFields[key].autoCloseTimeoutId)
          warningFields[key].autoCloseTimeoutId = null
        }
        Vue.delete(warningFields, key)
      }
      let errorFields = row._errorFields
      for (let key in errorFields) {
        if(errorFields[key].autoCloseTimeoutId) {
          clearTimeout(errorFields[key].autoCloseTimeoutId)
          errorFields[key].autoCloseTimeoutId = null
        }
        Vue.delete(errorFields, key)
      }
    }
    let index = state.errors.indexOf(error)
    if (index !== -1) state.errors.splice(index, 1)
  },
  SET_MESSAGES(state, payload) {
    if (payload) {
      payload.forEach(message => {
        state.messages.unshift(message)
      })
    }
  },
  DEL_MESSAGE(state, message) {
    if (message === null) return
    let index = state.messages.indexOf(message)
    if (index !== -1) state.messages.splice(index, 1)
  },
  SET_DATASET_REFREQ(state, payload) {
    if (payload.dataSet) {
      payload.dataSet.refReq = 1
      payload.dataSet.refreshAggregates = payload.refreshAggregates//,
      payload.dataSet.pageNoLock = payload.pageNoLock
    }
  },
  SET_DATASET_REFREQ_ALL(state, payload) {
    if (payload.appWindow && payload.appWindow.dataSets) {
      Object.values(payload.appWindow.dataSets).forEach(dataSet => {
        dataSet.refReq = 1
        dataSet.refreshAggregates = payload.refreshAggregates
      })
    }
  },
  SET_APPWINDOWDATA(state, payload) {
    let dataSetList = payload.dataSetList
    let data = payload.data
    let pivotValues = []
    let dataSetFrom = {}
    let currentRowIndex = 0
    let appWindow = state.csAppWindows[payload.appWindowIdent]
    dataSetList = dataSetList || []
    data = data || []
    dataSetList.forEach(dataSet => {
      dataSetFrom = data[dataSet.dataSetIdent] || {}
      dataSetFrom = constructors.csDataSetFromData(dataSetFrom)
      if (dataSetFrom.refCount !== dataSet.refCount)
        return true
      dataSetUtils.clearDataSet({dataSet})
      if(dataSetUtils.getDataSetFieldsIdentsDataField(dataSet, '_isSelected') != null) {
        dataSetUtils.deleteAllSelectedRows(dataSet)
      }
      dataSetFrom.rows.forEach((row, index) => {
        let newRow = constructors.csRow(row)
        newRow._dataSetIdent = dataSet.dataSetIdent
        newRow._appWindowIdent = payload.appWindowIdent
        dataSet.rows.push(newRow)
        if (dataSet.currentRowFilter) {
          let result = true
          dataSet.currentRowFilter.forEach(filterItem => {
            result = result && row[filterItem.dataFieldIdent] === filterItem.dataFieldValue
          })
          if (result) {
            currentRowIndex = index
            dataSet.currentRowFilter = null
          }
        } else if (row._isCurrent === 1) {
          currentRowIndex = index          
        }
        if(row._isSelected === 1) {
          dataSetUtils.addSelectedRow(dataSet, newRow)
        }
      })
      dataSet.pivotCols = dataSetFrom.pivotCols
      dataSet.pivotRows = dataSetFrom.pivotRows
      pivotValues = dataSetFrom.pivotValues
      pivotValues.forEach(value => {
        dataSet.pivotValues = {
          ...dataSet.pivotValues,
          ['c' + value['c'] + 'r' + value['r']]: {
            '0': value['0'],
            '1': value['1'],
            '2': { c: value['c'], r: value['r'] }
          }
        }
      })
      dataSet.currentRowIndex = dataSet.rows.length > 0 ? currentRowIndex : -1
      if (dataSetFrom.aggregates) dataSet.aggregates = dataSetFrom.aggregates
      if (dataSetFrom.pivotColsAggregates)
        dataSet.pivotColsAggregates = dataSetFrom.pivotColsAggregates
      if (dataSetFrom.pivotRowsAggregates)
        dataSet.pivotRowsAggregates = dataSetFrom.pivotRowsAggregates
      if (dataSet.hasSessionData) {
        (state.languageSuffix = dataSet.rows[0].languageSuffix)
      }
      dataSet.state = 1
      dataSet.refReq = 0
      dataSet.pageNoLock = 0
    })
    state.refreshParams = 0
    appWindow.query = payload.query || store.state.route.query
    appWindow.stateChangeCount += 1
  },
  INC_DATASET_REFCOUNT(state, payload) {
    if (!payload.dataSet) {
      return
    }
    payload.dataSet.refCount++
  },
  SET_REFRESH_PARAMS(state, payload) {
    if (payload.refreshParams == null) {
      return
    }
    state.refreshParams = payload.refreshParams
  },
  SET_APPWINDOW_PARAMS(state, payload) {
    if (!payload.appWindow) {
      return
    }
    payload.appWindow.params = payload.params
  },
  SET_APPWINDOW_COMMANDS(state, payload) {
    if (!payload.appWindow) {
      return
    }
    payload.appWindow.commands = payload.commands
  },
  SET_DATASET_ROWS_FIELD_VALUE(state, payload) {
    if (payload.row == null) return
    if (payload.row[payload.dataFieldIdent] === undefined)
      Vue.set(payload.row, payload.dataFieldIdent, payload.dataFieldValue)
    else
      payload.row[payload.dataFieldIdent] = payload.dataFieldValue

  },
  SET_DATASET_AGGREGATES_FIELD_VALUE(state, payload) {
    payload.dataSet.aggregates[payload.dataFieldIdent] =
      payload.dataFieldValue
  },
  SET_DATASET_PIVOT_VALUES_FIELD_VALUE(state, payload) {
    payload.row['1'][payload.dataFieldIdent] = payload.dataFieldValue
    payload.dataSet.pivotValues = {
      ...payload.dataSet.pivotValues,
      [payload.pivotRowKey]: payload.row
    }
  },
  SET_DATASET_WHERE_FIELD_VALUE(state, payload) {
    if (payload.dataSet.where[payload.dataFieldIdent] !== payload.dataFieldValue) {
      payload.dataSet.refReq = 1
      payload.dataSet.pageNo = payload.dataSet.pageNoLock === 1 ? payload.dataSet.pageNo : 1
      payload.dataSet.refreshAggregates = payload.dataSet.pageNoLock === 1 ? payload.dataSet.refreshAggregates : 1
    }
    payload.dataSet.where[payload.dataFieldIdent] = payload.dataFieldValue
  },
  SET_DATASET_WHERE_LISTS_FIELD_VALUE(state, payload) {
    if (!payload.dataSet.whereLists[payload.lookupDataFieldIdent] && payload.whereListValue) {
      payload.dataSet.whereLists = {
        ...payload.dataSet.whereLists,
        [payload.lookupDataFieldIdent]: [payload.whereListValue]
      }
    } else if (
      payload.whereListValue &&
      !payload.dataSet.whereLists[payload.lookupDataFieldIdent].find(
        item =>
          JSON.stringify(item._keyFieldsValues) === JSON.stringify(payload.whereListValue._keyFieldsValues)
      )
    ) {
      payload.dataSet.whereLists[payload.lookupDataFieldIdent].push(
        payload.whereListValue
      )
    } else if (
      !payload.whereListValue &&
      payload.dataSet.whereLists[payload.lookupDataFieldIdent]
    ) {
      while (payload.dataSet.whereLists[payload.lookupDataFieldIdent].length > 0)
        payload.dataSet.whereLists[payload.lookupDataFieldIdent].pop()
      delete payload.dataSet.whereLists[payload.lookupDataFieldIdent]
    }
  },
  SET_DATASET_ROW_STATUS(state, payload) {
    if (payload.row._status === undefined) {
      payload.row = { ...payload.row, _status: payload.status }
    } else {
      payload.row._status = payload.status
    }
  },
  SET_DATASET_SORTIDENT(state, payload) {
    if (payload.dataSet) {
      payload.dataSet.sortIdent = payload.sortIdent
    }
  },
  SET_LAYOUT_SORTIDENT(state, payload) {
    if (payload.layout) {
      payload.layout.sortIdent = payload.sortIdent
    }
  },
  SET_LAYOUT_IDENT(state, payload) {
    if (payload.dataSet && payload.layoutIdent)
      payload.dataSet.layoutIdent = payload.layoutIdent
  },
  SET_DATASET_PAGESIZESIDENT(state, payload) {
    if (payload.dataSet) {
      payload.dataSet.pageSizesIdent = payload.pageSizesIdent
      if (payload.pageSize > 0) {
        payload.dataSet.pageSize = payload.pageSize
      }
    }
  },
  SET_DATASET_PAGESIZE(state, payload) {
    if (payload.dataSet && payload.pageSize > 0) {
      payload.dataSet.pageSize = payload.pageSize
    }
  },
  SET_LOOKUP_DEF_VISIBLE(state, payload) {
    if (payload.lookupDef){
      payload.lookupDef.lookupVisible = payload.lookupVisible
      if (payload.appWindowUniqIdent)
        payload.lookupDef.appWindowUniqIdent = payload.appWindowUniqIdent
    }
    if (payload.dataSet)
      payload.dataSet.rows.forEach(row => {
        row._lookupVisible = { ...row._lookupVisible, [payload.lookupDef.appWindowIdentLookup]: false}
      })
    if (payload.row)
      payload.row._lookupVisible = { ...payload.row._lookupVisible, [payload.lookupDef.appWindowIdentLookup]: payload.lookupVisible}
  },
  SET_APPWINDOW_LOOKUP_DEF(state, payload) {
    if (!payload.appWindow)
      return
    payload.appWindow.lookupDef = payload.lookupDef
  },
  ADD_ROW(state, payload) {
    let fieldsIdents = payload.fieldsIdents
    let row = payload.row || {}
    let newRow = constructors.csRow()
    newRow._appWindowIdent = payload.appWindowIdent
    newRow._dataSetIdent = payload.dataSetIdent
    if (fieldsIdents) {
      fieldsIdents.forEach(fieldIdent => {
        let dataFieldIdent = fieldIdent.dataFieldIdent
        let value = row[dataFieldIdent]
        newRow = { ...newRow, [dataFieldIdent]: value === undefined ? null : value }
      })
    } else {
      for (let key in row) {
        if (newRow[key] === undefined)
          newRow = { ...newRow, [key]: null }
      }
    }
    newRow = { ...newRow, _status: dataSetUtils.rowState.added }
    payload.dataSet.rows.push(newRow)
    payload.dataSet.currentRowIndex = payload.dataSet.rows.length - 1
  },
  DELETE_ROW(state, payload) {
    let index = payload.dataSet.rows.findIndex(row => {
      return JSON.stringify(payload.row) === JSON.stringify(row)
    })
    if (index >= 0) payload.dataSet.rows.splice(index, 1)
  },
  ADD_FILE(state, payload) {
    let file = {
      __uuid: uuid.v1(),
      _status: dataSetUtils.fileState.added,
      _progress: 0,
      orginalFileName: payload.file.name,
      ext: stringUtils.getFileExtension(payload.file.name),
      size: payload.file.size,
      file: payload.file
    }
    payload.dataSet.files.push(file)
  },
  SET_FILE_STATUS(state, payload) {
    payload.file._status = payload.status
  },
  SET_FILE_PROGRESS(state, payload) {
    payload.file._progress = payload.progress
  },
  SET_FILE_DATA(state, payload) {
    payload.file.remoteFileName = payload.data.filename
    payload.file.fileSize = payload.data.size
  },
  DELETE_FILE(state, payload) {
    let index = payload.dataSet.files.findIndex(file => {
      return JSON.stringify(payload.file) === JSON.stringify(file)
    })
    if (index >= 0) payload.dataSet.files.splice(index, 1)
  },
  DELETE_ALL_FILES(state, payload) {
    payload.dataSet.files.splice(0, payload.dataSet.files.length)
  },
  ADD_SELECTED_ROW(state, payload) {
    dataSetUtils.addSelectedRow(payload.dataSet, payload.row)
  },
  DELETE_SELECTED_ROW(state, payload) {
    dataSetUtils.deleteSelectedRow(payload.dataSet, payload.row)
  },
  DELETE_ALL_SELECTED_ROW(state, payload) {
    dataSetUtils.deleteAllSelectedRows(payload.dataSet)
  },
  SET_DATASET_SCROLL_DIRECTION(state, payload) {
    if (payload.dataSet)
      payload.dataSet.scrollDirection = payload.scrollDirection
  },
  SET_COL_FIELD_ORD(state, payload) {
    if (payload.colField) payload.colField.ord = payload.ord
  },
  SET_SORT_COL_FIELD_ORD(state, payload) {
    if (payload.sortColField) payload.sortColField.ord = payload.ord
  },
  SET_COL_FIELD_VISIBILITY(state, payload) {
    if (payload.colField) payload.colField.isVisible = payload.isVisible
  },
  SET_SORT_IDENT_SORT_COL_FIELDS(state, payload) {
    if (payload.sortIdent)
      payload.sortIdent.sortColFields = payload.sortColFields
  },
  ADD_SORT_IDENT_SORT_COL_FIELD(state, payload) {
    if (payload.sortIdent)
      payload.sortIdent.sortColFields.push(payload.sortColField)
  },
  DELETE_SORT_IDENT_SORT_COL_FIELD(state, payload) {
    if (payload.sortIdent) {
      let index = payload.sortIdent.sortColFields.indexOf(
        payload.sortColField
      )
      if (index > -1) payload.sortIdent.sortColFields.splice(index, 1)
    }
  },
  SET_SORT_COL_FIELD_IS_DESC(state, payload) {
    if (payload.sortColField) payload.sortColField.isDesc = payload.isDesc
  },
  SET_CURRENT_COL_FIELD_INDEX(state, payload) {
    if (payload.layout)
      payload.layout.currentColFieldIndex = payload.currentColFieldIndex
  },
  SET_CURRENT_SORT_COL_FIELD_INDEX(state, payload) {
    if (payload.sort)
      payload.sort.currentSortColFieldIndex = payload.currentSortColFieldIndex
  },
  SET_DATASET_ACTION_STATE(state, payload) {
    if (payload.row && payload.action && payload.action.actionIdent) {
      let actionIdent = payload.action.actionIdent
      if (payload.row._actionState[actionIdent] === undefined) {
        payload.row._actionState = { ...payload.row._actionState, [actionIdent]: {state: payload.state, timer: null} }
      } else {
        payload.row._actionState[actionIdent].state = payload.state
      }
    } else if (payload.action) {
      payload.action.state = payload.state
    }
  },
  SET_DATASET_ACTION_TIMER(state, payload) {
    if (payload.row && payload.action && payload.action.actionIdent) {
      let actionIdent = payload.action.actionIdent
      if (payload.row._actionState[actionIdent] === undefined) {
        payload.row._actionState = { ...payload.row._actionState, [actionIdent]: {state: 1, timer: payload.timer} }
      } else {
        clearTimeout(payload.row._actionState[actionIdent].timer)
        payload.row._actionState[actionIdent].timer = payload.timer
      }
    } else if (payload.action) {
      clearTimeout(payload.action.timer)
      payload.action.timer = payload.timer
    }
  },
  ADD_MODAL_WINDOW(state, payload) {
    if (payload.appWindow && payload.data) {
      let data = payload.data
      let key = data.appWindowIdent + '_' + data.dataSetIdent + '_' + data.actionIdent
      payload.appWindow.modalWindows = { ...payload.appWindow.modalWindows, [key]: data }
    }
  },
  DELETE_MODAL_WINDOW(state, payload) {
    if (payload.modalWindows && payload.modalWindowIndex) {
      Vue.delete(payload.modalWindows, payload.modalWindowIndex)
    }
  },
  DELETE_ALL_SORT_IDENT_SORT_COL_FIELDS(state, payload) {
    if (payload.sortIdent && payload.sortIdent.sortColFields) {
      while (payload.sortIdent.sortColFields.length > 0)
        payload.sortIdent.sortColFields.pop()
    }
  },
  SET_DATASET_AGGRFIELD_CALC4COLS(state, payload) {
    if (!payload.aggrField) {
      return
    }
    payload.aggrField.calc4Cols = payload.calc4Cols
  },
  SET_DATASET_AGGRFIELD_CALC4ROWS(state, payload) {
    if (!payload.aggrField) {
      return
    }
    payload.aggrField.calc4Rows = payload.calc4Rows
  }
}
