import { A1tbType } from '@/types'
import { A1_APIsort } from '@/store/action/A1banner'

// 初始化状态
const initState = {
  // 列表数据
  tableInfo: {
    list: [] as A1tbType[],
    total: 0
  }
}

// 定义 action 类型
type Props = {
  type: 'A1/getList'
  payload: { list: A1tbType[]; total: number }
}

type sortProps = {
  type: 'A1/moveUp' | 'A1/moveDown'
  payload: number
}

// reducer
export default function Reducer(state = initState, action: Props | sortProps) {
  switch (action.type) {
    // 获取列表数据
    case 'A1/getList':
      return { ...state, tableInfo: action.payload }

    // 上移
    case 'A1/moveUp':
      const indexSort = action.payload
      if (indexSort <= 0) return state // 已经在顶部，不能再上移
      const indexDown = state.tableInfo.list[indexSort].sort
      const indexUp = state.tableInfo.list[indexSort - 1].sort
      const upId = state.tableInfo.list[indexSort - 1].carouselId
      const downId = state.tableInfo.list[indexSort].carouselId
      const obj = {
        list: [
          {
            carouselId: upId,
            sort: indexDown
          },
          {
            carouselId: downId,
            sort: indexUp
          }
        ]
      }
      A1_APIsort(obj)
      const newList = swapItems(state.tableInfo.list, indexSort, indexSort - 1)
      newList[indexSort].sort = indexDown
      newList[indexSort - 1].sort = indexUp
      return {
        ...state,
        tableInfo: {
          ...state.tableInfo,
          list: newList
        }
      }
    // 下移
    case 'A1/moveDown':
      const indexSort2 = action.payload
      if (indexSort2 >= state.tableInfo.list.length - 1) return state // 已经在底部，不能再下移
      const indexUp2 = state.tableInfo.list[indexSort2].sort
      const indexDown2 = state.tableInfo.list[indexSort2 + 1].sort
      const downId2 = state.tableInfo.list[indexSort2 + 1].carouselId
      const upId2 = state.tableInfo.list[indexSort2].carouselId
      const obj2 = {
        list: [
          {
            carouselId: upId2,
            sort: indexDown2
          },
          {
            carouselId: downId2,
            sort: indexUp2
          }
        ]
      }
      A1_APIsort(obj2)
      const newList2 = swapItems(state.tableInfo.list, indexSort2, indexSort2 + 1)
      newList2[indexSort2].sort = indexUp2
      newList2[indexSort2 + 1].sort = indexDown2
      return {
        ...state,
        tableInfo: {
          ...state.tableInfo,
          list: newList2
        }
      }
    default:
      return state
  }
}

const swapItems = (array: any[], index1: number, index2: number) => {
  const newArray = [...array]
  ;[newArray[index1], newArray[index2]] = [newArray[index2], newArray[index1]]
  return newArray
}
