import { CustomWrapper, View } from '@tarojs/components'
import { useContext, useEffect, useState } from 'react'
import Counter from '../counter'
import styles from './index.module.scss'
import { debounce } from '@/common/util'
import type { saleModeType } from '@/common/enum'

export type Mode = 'weight'|'weight_error'|'sale_price'
export type NumberParam = (num: number, type: Mode) => void
interface Props {
  onNumber?: NumberParam
  sale_mode: saleModeType
  defaultValue?: {
    weight: number
    weight_error: number
    sale_price: number
  }
}
export default (props: Props) => {
  const { onNumber, defaultValue, sale_mode } = props
  const [defaultNum, setDefaultNum] = useState({
    weight: 0,
    weight_error: 0,
    sale_price: 0,
  })
  useEffect(() => {
    defaultValue && setDefaultNum(() => defaultValue)
  }, [defaultValue])
  const getNumber: NumberParam = debounce((num, type) => {
    onNumber?.(num, type)
    if (type === 'weight') {
      defaultNum.weight = num
    }
    else if (type === 'sale_price') {
      defaultNum.sale_price = num
    }
    else {
      defaultNum.weight_error = num
    }
    setDefaultNum(() => ({ ...defaultNum }))
  }, 300)
  return <View className={styles.change_count}>
    <View className={styles.change_count__item}>
      <View className={styles['change_count__item--title']}>重量</View>
      <CustomWrapper>
        <Counter defaultNum={defaultNum.weight} minNum={-1000} digits={2} onChange={num => getNumber(num, 'weight')} onBlue={num => getNumber(num, 'weight')} />
      </CustomWrapper>
    </View>
    {sale_mode === 0 && <View className={styles.change_count__item}>
      <View className={styles['change_count__item--title']}>空差</View>
      <CustomWrapper>
        <Counter defaultNum={defaultNum.weight_error} minNum={-1000} digits={2} onChange={num => getNumber(num, 'weight_error')} onBlue={num => getNumber(num, 'weight_error')} />
      </CustomWrapper>
    </View>}
    <View className={styles.change_count__item}>
      <View className={styles['change_count__item--title']}>单价</View>
      <CustomWrapper>
        <Counter defaultNum={defaultNum.sale_price} minNum={-1000} digits={2} onChange={num => getNumber(num, 'sale_price')} onBlue={num => getNumber(num, 'sale_price')} />
      </CustomWrapper>
    </View>
  </View>
}
