import produce from 'immer'
import type { Dispatch } from 'react'
import React, { useContext } from 'react'
import type { ShoppingStore } from './shoppingStore'
import type { EnumSaleMode } from '@/common/Enumerate'

/**
 * 456: {
 *  purchaserId: 456,
 *  colorKind: {
 *    4562: {
 *      id: 4562,
 *      ...
 *    }
 *  },
 *  multipleSelection: {
 *    4562: {
 *      id: 4562,
 *      ...
 *    }
 *  }
 * },
 * 457: {
 *  purchaserId: 457,
 *  colorKind: {
 *    4562: {
 *      id: 4562,
 *      ...
 *    }
 *  }
 * }
 */
export type ColorStore = Record<GoodsMeta['purchaserId'], GoodsMeta>

export interface Goods {
  id: number
  product_code: number // 面料编号
  product_color_code: number // 颜色编号
  estimate_amount: number // 预估金额
  count: number // 已选的条数或米数
  sale_mode: EnumSaleMode
  roll?: number
  length?: number
}
// 分组
export interface GoodsMeta {
  purchaserId: number
  goodsKind?: Record<Goods['id'], Goods>
  multipleSelection?: GoodsMeta['goodsKind']
}

export interface ShoppingStateContextValue {
  isManageStatus: boolean // 管理按钮的状态
  isMultipleSelection: boolean // 全选按钮的状态
  currentCheckedPurchaserId: number // 当前高亮的客户ID
  currentCheckedSaleMode: EnumSaleMode
  colorStore: ColorStore
  selectedAmount: number
  Observer: ShoppingStore
}

export enum ShoppingDispatchType {
  UPDATE_MANAGE_STATUS = 'UPDATE_MANAGE_STATUS',
  UPDATE_MULTIPLE_SELECTION_STATUS = 'UPDATE_MULTIPLE_SELECTION_STATUS',
  UPDATE_CURRENT_CHECKED_PURCHASERID = 'UPDATE_CURRENT_CHECKED_PURCHASERID',
  UPDATE_CURRENT_CHECKED_SALEMODE = 'UPDATE_CURRENT_CHECKED_SALEMODE',
  UPDATE_COLOR_STORE = 'UPDATE_COLOR_STORE',
  UPDATE_SELECTED_AMOUNT = 'UPDATE_SELECTED_AMOUNT',
  UPDATE_CHANGED_CHECKBOX = 'UPDATE_CHANGED_CHECKBOX',
}

export interface ShoppingDispatchContextValue {
  [ShoppingDispatchType.UPDATE_MANAGE_STATUS]: (isManageStatus: ShoppingStateContextValue['isManageStatus']) => void
  [ShoppingDispatchType.UPDATE_MULTIPLE_SELECTION_STATUS]: (isMultipleSelection: ShoppingStateContextValue['isMultipleSelection']) => void
  [ShoppingDispatchType.UPDATE_CURRENT_CHECKED_PURCHASERID]: (purchaserId: ShoppingStateContextValue['currentCheckedPurchaserId']) => void
  [ShoppingDispatchType.UPDATE_CURRENT_CHECKED_SALEMODE]: (saleMode: ShoppingStateContextValue['currentCheckedSaleMode']) => void
  [ShoppingDispatchType.UPDATE_COLOR_STORE]: (colorStore: React.SetStateAction<ColorStore>) => void
  [ShoppingDispatchType.UPDATE_SELECTED_AMOUNT]: (amount: React.SetStateAction<ShoppingStateContextValue['selectedAmount']>) => void
  [ShoppingDispatchType.UPDATE_CHANGED_CHECKBOX]: (amount: React.SetStateAction<ShoppingStateContextValue['selectedAmount']>) => void
}

export interface ShoppingAction {
  type: ShoppingDispatchType
  data?: any
}

export const shoppingReducer = produce((draft: ShoppingStateContextValue, action: ShoppingAction) => {
  const { type, data } = action
  switch (type) {
    case ShoppingDispatchType.UPDATE_MANAGE_STATUS: {
      draft.isManageStatus = data
      break
    }
    case ShoppingDispatchType.UPDATE_MULTIPLE_SELECTION_STATUS: {
      draft.isMultipleSelection = data
      break
    }
    case ShoppingDispatchType.UPDATE_CURRENT_CHECKED_PURCHASERID: {
      draft.currentCheckedPurchaserId = data
      break
    }
    case ShoppingDispatchType.UPDATE_CURRENT_CHECKED_SALEMODE: {
      draft.currentCheckedSaleMode = data
      break
    }
    case ShoppingDispatchType.UPDATE_COLOR_STORE: {
      draft.colorStore = data
      break
    }
    case ShoppingDispatchType.UPDATE_SELECTED_AMOUNT: {
      draft.selectedAmount = data
      break
    }
    case ShoppingDispatchType.UPDATE_CHANGED_CHECKBOX: {
      if (!draft.colorStore[data.purchaserId]) {
        draft.colorStore[data.purchaserId] = {
          purchaserId: data.purchaserId,
          goodsKind: data.goodsKind,
          multipleSelection: data.multipleSelection,
        }
      }
      else {
        draft.colorStore[data.purchaserId] = produce(draft.colorStore[data.purchaserId], (purchaserDraft) => {
          purchaserDraft.purchaserId = data.purchaserId
          purchaserDraft.goodsKind = { ...purchaserDraft.goodsKind, ...data.goodsKind }
          purchaserDraft.multipleSelection = data.multipleSelection ? data.multipleSelection : purchaserDraft?.multipleSelection
        })
      }
      break
    }
    default:
      throwError()
  }
})

export const ShoppingStateContext = React.createContext<ShoppingStateContextValue | null>(null)

export const ShoppingDispatchContext = React.createContext<Dispatch<ShoppingAction> | null>(null)

export function useShoppingState() {
  const ctx = useContext(ShoppingStateContext)
  if (!ctx) {
    throw new Error('没有获取到shopping context')
  }
  return ctx
}

export function useShoppingDispatch() {
  const ctx = useContext(ShoppingDispatchContext)
  if (!ctx) {
    throw new Error('没有获取到shopping dispatch')
  }
  return ctx
}

export function useWatch(purchaserId: GoodsMeta['purchaserId'], id: number) {
  const { colorStore } = useShoppingState()
  return id ? colorStore[purchaserId].goodsKind![id] : colorStore[purchaserId].goodsKind
}

export interface ShoppingCartAction {
  setManageStatus: (manageStatus: boolean) => void
  getManageStatus: () => boolean
}

export interface InternalShoppingCartAction extends ShoppingCartAction {
  __INTERNAL__: React.MutableRefObject<ShoppingCartAction | null>
}

export function throwError(): never {
  throw new Error('没有这个action.type')
}
