import { 
  createSlice,
  PayloadAction,
  createAsyncThunk
} from '@reduxjs/toolkit'
import { StoreState } from '.'
import axios from '../http'

export const enum SceneType {
  KANKAN = '4dkk',
  LASER = 'laser',
  GIS = 'gis'
}

export interface Scene {
  id: string,
  title: string,
  cover: string,
  time: string,
  type: SceneType,
  m?: string
}
export type EditableScene = Omit<Scene, 'id' | 'time'>

export type Scenes = Scene[]

export const addScene = createAsyncThunk('scenes/addScene', async (scene: EditableScene, { dispatch }) => {
  await axios.post('/cms/scene/save', {
    name: scene.title,
    sceneCode: scene.m,
    thumb: scene.cover,
    type: scene.type
  })
  dispatch(fetchScenes())
})
export const updateScene = createAsyncThunk('scenes/updateScene', async (scene: Scene) => {
  await axios.post('/cms/scene/save', {
    id: scene.id,
    name: scene.title,
    sceneCode: scene.m,
    thumb: scene.cover,
    type: scene.type
  })
  return scene
})
export const deleteScene = createAsyncThunk('scenes/delScene', async (sceneId: Scene['id']) => {
  await axios.get(`/cms/scene/remove/${sceneId}`)
  return sceneId
})
export const fetchScenes = createAsyncThunk('scenes/fetchScene', async () => {
  const res = await axios.post('/cms/scene/list', null, { 
    params: { pageNum: 1, pageSize: 100000 },
    headers: { 'Content-type': 'application/json' },
    data: {}
  })
  return res.data.data.records.map(item => ({
    id: item.id,
    title: item.name,
    cover: item.thumb,
    time: item.createTime,
    type: item.type,
    m: item.sceneCode
  })) as Scene[]
})


const initialValue: Scenes = []

const sceneSlice = createSlice({
  initialState: {
    value: initialValue
  },
  name: 'scenes',
  reducers: {
  },
  extraReducers(builder) {
    builder
      .addCase(fetchScenes.fulfilled, (state, action: PayloadAction<Scene[]>) => {
        state.value = action.payload
      })
      // .addCase(addScene.fulfilled, (state, action: PayloadAction<Scene>) => {
      //   state.value.push(action.payload)
      // })
      .addCase(updateScene.fulfilled, (state, action: PayloadAction<Scene>) => {
        const updateScene = state.value.find(post => post.id === action.payload.id)
        Object.assign(updateScene, action.payload)
      })
      .addCase(deleteScene.fulfilled, (state, action: PayloadAction<Scene['id']>) => {
        const index = state.value.findIndex(scene => scene.id === action.payload)
        if (~index) {
          state.value.splice(index, 1)
        }
      })
  }
})

export const sceneReducer = sceneSlice.reducer

export const scenesSelector = (state: StoreState) => state.scenes.value
export const sceneSelector = (state: StoreState, id: Scene['id']) => 
  state.scenes.value.find(scene => scene.id === id)