import {toRaw} from 'vue'
import {pageSettings, packStruct, packsNames, data} from './StaticData'
import {fetchColumn} from '@organisms/PackColumns';
import {loadingPagination, setPagination} from './helpers';
import {isEmpty, uniq} from 'ramda'
import moment from'moment'

const initState = {
  
  isLoading: false,
  searchValue: null,
  packsSettings: pageSettings,

  selectedPacksGroup: null,
  selectedPack: null,
  selectedColumnsSelect: null,
  
  lastPacks: [],
  freePacks: {},
  packsGroupDefault: [],
  packsGroup: null,
  tableData: [],
  machinesData: [],
  columnsSelect: [],

};

const state = {
  ...initState
};

const getters = {
  isLoading: (state) => state.isLoading,
  searchValue: (state) => state.searchValue,
  packsSettings: (state) => state.packsSettings,

  selectedPacksGroup: (state) => state.selectedPacksGroup,
  selectedPack: (state) => state.selectedPack,
  selectedColumnsSelect: (state) => state.selectedColumnsSelect,

  lastPacks: (state) => state.lastPacks,
  freePacks: (state) => state.freePacks,
  packsGroup: (state) => state.packsGroup,
  tableData: (state) => state.tableData,
  machinesData: (state) => state.machinesData,
  columnsSelect: (state) => state.columnsSelect,
};

const mutations = {
  setIsLoading: (state, updval) =>  state.isLoading = updval,
  setSearchValue: (state, updval) =>  state.searchValue = updval,
  setPacksSettings: (state, updval) =>  state.packsSettings = updval,

  setSelectedPack: (state, updval) =>  state.selectedPack = updval,
  setSelectedPacksGroup: (state, updval) =>  state.selectedPacksGroup = updval,
  setSelectedColumnsSelect: (state, updval) =>  state.selectedColumnsSelect = updval,

  saveLastPacks: (state, updval) =>  state.lastPacks = updval,
  saveFreePacks: (state, updval) => state.freePacks = updval,
  setpacksGroupDefault: (state, updval) =>  state.packsGroupDefault = updval,
  setpacksGroup: (state, updval) =>  state.packsGroup = updval,
  setTableData: (state, updval) =>  state.tableData = updval,
  setMachinesData: (state, updval) =>  state.machinesData = updval,
  setColumnSelect: (state, updval) =>  state.columnsSelect = updval,
  
  resetStore: (state) => {
    Object.entries(initState).forEach(([k,v]) => {
      state[k] = v
    })
  },
};

const actions = {
  uploadData: async ({commit, getters}, params) => {
    try{

      /*

      Получаем все имена группы пакетов
      Также необходимо передать название группы пакетов либо при клике по ссылке из Поиск по пакетам(finder packs), либо при получении имен пакетов внутри группы и 
      дополнительно название самой группы

        pack_names =
      LiveMonitor.Packages.list_pack_struct(:preload, pack_group: params.pack_group)
      |> Enum.filter(& Map.get(&1, :is_prod))
      |> to_list()
      |> Enum.map(&Map.get(&1, :name))
      |> sort_pack_names()
      
      */

      /*
      
      Получаем данные по выбранному пакету

      defp get_packs_with_additions(packNum, imei, dt_start, dt_finish, options) do
        %{
          pack_number: String.to_integer(packNum),
          imei: String.to_integer(imei),
          dt_start: dt_start,
          dt_finish: dt_finish,
          options: options
        }
        |> Communicator.PackFetcher.get_handled_packs()
        |> LiveMonitorWeb.PacksController.repack_it(packNum)
        |> LiveMonitorWeb.PacksController.round_values()
      end
      
      */

      /*
        Получаем структуру пакета по выбранному пакету

        LiveMonitor.Packages.get_pack_struct(like_name: page_settings.selected_pack)

      */

      // imei 864004043403283

      console.log('params', toRaw(params))
      console.log('getters.isLoading', toRaw(getters.isLoading))

      const packsSettings = toRaw(getters.packsSettings)
      const packGroup = packsSettings.selectedPacksGroup // Переход из меню в пакеты
      const packGroupIdx = params.path?.lastIndexOf('/')
      const currentPackGroup = packGroup ? packGroup : params.path?.slice(packGroupIdx + 1)
      console.log('packGroupIdx', packGroupIdx)
      console.log('packGroup', packGroup)
      console.log('currentPackGroup', currentPackGroup)

      if (currentPackGroup) {

        const selectedPacksGroup = !isEmpty(packsNames) ? packsNames.map((name) => ({name: name})) : [] // use params.packGroup, for getting packsNames from server
        const currentPacksSettings = {...packsSettings, selectedPackGroup: selectedPacksGroup, selectedPack: selectedPacksGroup[0]}

        commit('setPacksSettings', currentPacksSettings)

        if (params.query && params.query.pack && params.query.date && params.query.imei) {

          const packStructure = !isEmpty(packStruct) ? packStruct : []
          const dataPack = !isEmpty(data) ? data : []
    
          const currentColumns = fetchColumn(packStructure, dataPack)
    
          const dataWithPagination = loadingPagination(dataPack.askr_logs, packsSettings.pagination)

          const dtStart = moment(params.query.date).subtract(1, "day").startOf('day').startOf('minute').format("YYYY-MM-DDTHH:mm:ss")
          const dtFinish = moment(params.query.date).endOf('day').startOf('minute').format("YYYY-MM-DDTHH:mm:ss")

          const dates = {dtStart, dtFinish, selectedDate: params.query.date}
          const tableColumns = {...packsSettings.tableColumns,  default: currentColumns}

          const currentPacksSettings = {...packsSettings, selectedPackGroup: selectedPacksGroup, tableColumns, selectedPack: {name: params.query.pack}, dates: dates, imei: params.query.imei, pagination: dataWithPagination.pagination}

          const columnsSelect = currentColumns.map((column) => ({name: column.title, key: column.field}))
    
          const currentTableData = {dataSource: dataWithPagination.machines, pagination: dataWithPagination.pagination, columns: currentColumns, height: "550px"}
    
          console.log('currentColumns', currentColumns)
          console.log('dtStart', dtStart)
          console.log('dtFinish', dtFinish)
          
          commit('setColumnSelect', columnsSelect)
          commit('setSelectedColumnsSelect', columnsSelect)
          commit('setTableData', currentTableData)
          commit('setPacksSettings', currentPacksSettings)
          commit('setMachinesData', dataPack.askr_logs)
          
        }

      }

      commit('setIsLoading', false)
      
    } catch (err) {
      console.error(err)
    }
  },
  setLastPacks: async ({commit}, packs) => {
    try {
      commit('saveLastPacks', packs)
    } catch (err) {
      console.error(err)
    }
  },
  setFreePacks: async ({commit}, packs) => {
    try {
      commit('saveFreePacks', packs)
    } catch (err) {
      console.error(err)
    }
  },
  updatePagination: async ({commit, getters, state}, updatedData) => {
    try {

      const tableData = toRaw(getters.tableData)
      const packsSettings = toRaw(getters.packsSettings)
      const machinesData = toRaw(state.machinesData)
      const newData = setPagination(machinesData, packsSettings.pagination, updatedData)
      const currentPacksSettings = {...packsSettings, pagination: newData.updatedPagination}
      console.log('currentTableData', newData.currentTableData)
      const currentTableData = {...tableData, dataSource: newData.currentTableData, pagination: newData.updatedPagination}
      commit('setTableData', currentTableData)
      commit('setPacksSettings', currentPacksSettings)
    } catch (err) {
      console.error(err)
    }
  },
  updatePackSettings: async ({commit, getters}, updatedData) => {
    try {
      console.log('updatedData', updatedData)
      const packsSettings = toRaw(getters.packsSettings)
      const key = Object.keys(updatedData)[0]
      const currentPacksSettings = {...packsSettings, [key]: updatedData[key]}
      console.log('currentPacksSettings', currentPacksSettings)
      commit('setPacksSettings', currentPacksSettings)
    } catch (err) {
      console.error(err)
    }
  },
  updateSelects: async ({commit, getters}, updatedSelect) => {
    try {

      const dataSource = toRaw(getters.tableData).dataSource
      const packsSettings = toRaw(getters.packsSettings)
      const allSelects = toRaw(getters.columnsSelect)
      const selectedSelects = toRaw(getters.selectedColumnsSelect)
      const defaultColumns = toRaw(packsSettings.tableColumns.default)
      const selectedColumns = toRaw(packsSettings.tableColumns.selected)

      let currentColumns = !isEmpty(selectedColumns) ? selectedColumns : defaultColumns
      const pagination = packsSettings.pagination
      const curSelectKey = updatedSelect.select.key

      let updatedSelects = []
      let updatedColumns = []
      for (let i = 0; i < allSelects.length; i++) {
        const curSelect = allSelects[i]
        const newSelected = curSelect.key === curSelectKey ? curSelect : null
        if (updatedSelect.key === 'added' && newSelected) {
          updatedSelects = [...selectedSelects, newSelected]
          const newColumn = defaultColumns.find((el) => el.field === newSelected.key)
          currentColumns = selectedSelects.length === 0 ? [] : currentColumns
          updatedColumns = uniq([...currentColumns, newColumn])
          break
        }
        if (updatedSelect.key === 'removed' && newSelected && selectedSelects.length === 1) {
          updatedSelects = []
          updatedColumns = defaultColumns.filter((el) => el.field === 'pack_dt')
          break
        } 
        if (updatedSelect.key === 'removed' && newSelected && selectedSelects.length > 1) {
          updatedSelects = selectedSelects.filter((el) => el.key !== newSelected.key)
          updatedColumns = currentColumns.filter((el) => el.field !== newSelected.key)
          break
        }
      }

      const tableColumns = {...packsSettings.tableColumns, selected: updatedColumns}
      const currentPacksSettings = {...packsSettings, tableColumns}
      const currentTableData = {dataSource, pagination, columns: updatedColumns, height: "550px"}

      // console.log('updatedSelects', updatedSelects)
      // console.log('currentTableData', currentTableData)

      commit('setSelectedColumnsSelect', updatedSelects)
      commit('setTableData', currentTableData)
      commit('setPacksSettings', currentPacksSettings)
    } catch (err) {
      console.error(err)
    }
  },
  resetStore: ({commit}) => {
    commit('resetStore')
  }
};

export const store = {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};
