import { View } from '@tarojs/components'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import Big from 'big.js'
import ProductItem from '../../productItem'
import type { NumberParam } from '../../settingNumber'
import SettingNumber from '../../settingNumber'
import styles from './index.module.scss'
import { useCurrenCode } from '@/context/ContextCodeSetting'

interface Param {
  colorInfo: any
}
type IndexParam = {
  onChangeNumber: NumberParam
} & Param

export default memo((props: Param) => {
  const { dispatch, productData } = useCurrenCode()
  const { colorInfo } = props

  const index = colorInfo.index_str.split('_')
  const changeNumber: NumberParam = useCallback((num, type) => {
    // 更新整体数据
    const updateData = {
      price: colorInfo?.price_admin,
      weight: colorInfo?.weight_admin,
      weight_error: colorInfo?.weight_error_admin,
    }
    if (type === 'weight') {
      updateData.weight = num * 1000
    }
    else if (type === 'sale_price') {
      updateData.price = num * 100
    }
    else {
      updateData.weight_error = num * 1000
    }

    if (colorInfo.sale_mode === 0) {
      colorInfo.weight_setting = Big(updateData.weight).times(colorInfo.roll).add(colorInfo.weight).toNumber()
      colorInfo.weight_error_setting = Big(updateData.weight_error).times(colorInfo.roll).add(colorInfo.weight_error).toNumber()
    }
    else {
      colorInfo.weight_setting = Big(updateData.weight).add(colorInfo.weight).toNumber()
      colorInfo.weight_error_setting = Big(updateData.weight_error).add(colorInfo.weight_error).toNumber()
    }
    colorInfo.price_setting = Big(updateData.price).add(colorInfo.price).toNumber()

    colorInfo.weight_admin = updateData.weight
    colorInfo.price_admin = updateData.price
    colorInfo.weight_error_admin = updateData.weight_error
    productData.color_item_data.product_color_details[index[1]] = { ...colorInfo }
    productData.color_item_data = { ...productData.color_item_data }

    dispatch({ type: 'updateColorData', data: { ...productData.color_item_data }, update_status: 1 })
  }, [colorInfo])

  return <Index colorInfo={colorInfo} onChangeNumber={changeNumber} />
})

const Index = memo((props: IndexParam) => {
  const { colorInfo } = props
  const getNumber: NumberParam = (num, type) => {
    props.onChangeNumber?.(num, type)
  }
  console.log('colorInfo777:::', colorInfo)
  const defaultNum = useMemo(() => {
    return {
      weight: Big(colorInfo.weight_admin || 0).div(Big(1000)).toNumber(),
      sale_price: Big(colorInfo.price_admin || 0).div(Big(100)).toNumber(),
      weight_error: Big(colorInfo.weight_error_admin || 0).div(Big(1000)).toNumber(),
    }
  }, [colorInfo])
  return <View className={styles['product_list__item--con']}>
    <ProductItem codeItem={colorInfo} settingColorStatus />
    <SettingNumber sale_mode={colorInfo.sale_mode} onNumber={getNumber} defaultValue={defaultNum} />
  </View>
})
