import { Image, Text, View } from '@tarojs/components'
import type { FC } from 'react'
import { forwardRef, memo, useCallback, useEffect, useState } from 'react'
import classnames from 'classnames'
import { selectList } from '../../config'
import type { ShoppingStateContextValue } from '../../context'
import { Goods, ShoppingDispatchType, useShoppingDispatch, useShoppingState } from '../../context'
import type { ShoppingStore } from '../../context/shoppingStore'
import { events } from '../../context/shoppingStore'
import styles from './index.module.scss'
import MCheckbox from '@/components/checkbox'
import Counter from '@/components/counter'
import { debounce } from '@/common/util'
import { formatImgUrl, formatMeterDiv, formatMeterMul, formatPriceDiv } from '@/common/format'
import { EnumSaleMode } from '@/common/Enumerate'
import { AdjestShoppingCartApi } from '@/api/shopping/index'
import LabAndImg from '@/components/LabAndImg'
import { usePropsValue } from '@/use/useCommon'

interface PropsType {
  state?: {
    Observer: ShoppingStore
  }
  purchaserId: number
  itemData: Record<string, any> & object
  checked?: boolean
  onChange?: (isChecked: boolean, goodsId: number) => void
}

const ColorKindItem: FC<PropsType> = (props) => {
  console.log('rerender component ColorKindItem', props)
  const { state, purchaserId, itemData, checked = false } = props
  const [isChecked, setCheck] = usePropsValue({
    value: checked,
    defaultValue: checked,
    onChange: (value) => {
      props.onChange?.(value, itemData.id)
    },
  })

  // 格式化数量
  const formatCount = (itemData) => {
    return itemData.sale_mode == EnumSaleMode.Bulk ? itemData.roll : formatMeterDiv(itemData.length)
  }

  const [count, setCount] = useState(formatCount(itemData))

  // 格式化金额
  const formatPrice = (price: number) => {
    return Number(formatPriceDiv(price))
  }

  const handleCountChange = (nextValue: number) => {
    setCount(nextValue)
  }

  // 格式化单位
  const formatUnit = (itemData) => {
    return itemData.sale_mode == EnumSaleMode.Bulk ? '条' : '米'
  }
  // 选中
  const handleSelect = () => {
    const payload = {
      id: itemData?.id,
      estimate_amount: itemData.estimate_amount,
      product_code: itemData.product_code,
      product_color_code: itemData.product_color_code,
      sale_mode: itemData.sale_mode,
      count: itemData.sale_mode === EnumSaleMode.Bulk ? itemData.roll : Number(formatMeterDiv(itemData.length)),
    }
    events.trigger('updatePurchaserMultipleSelection', purchaserId, payload, 'add', itemData?.id)
    setCheck(true)
  }
  // 未选中
  const handleClose = () => {
    events.trigger('updatePurchaserMultipleSelection', purchaserId, null, 'delete', itemData.id)
    setCheck(false)
  }
  const { fetchData } = AdjestShoppingCartApi()

  // 调整条数/米数的接口  并在调整完成后重新请求整个购物车页面
  const getInputValue = useCallback(debounce(async(num) => {
    console.log('num===>', num)
    const targetColor: Record<string, any> = {
      roll: 0,
      length: 0,
    }
    if (itemData.sale_mode === EnumSaleMode.Bulk) {
      itemData.roll = num
      targetColor.roll = num
    }
    else {
      itemData.length = formatMeterMul(num)
      targetColor.length = formatMeterMul(num)
    }
    const res = await fetchData({
      id: itemData.id,
      roll: targetColor.roll,
      length: targetColor.length,
    })
    if (res.success) {
      state?.Observer?.notify(purchaserId)
    }
  }, 460), [itemData])

  const labAndImgObj = useCallback((item) => {
    return { lab: item.lab, rgb: item.rgb, texture_url: item.product_color_texture_url }
  }, [])
  useEffect(() => {
    console.log('itemData==>', itemData)
    setCount(formatCount(itemData))
  }, [itemData.roll, itemData.length])
  return (
    <MCheckbox
      status={isChecked}
      onSelect={handleSelect}
      onClose={handleClose}
      customClassName={classnames(styles.checkbox, isChecked ? styles.selected : '')}
      customTextClass={styles.colorKindItem}
    >
      <View className={styles.colorKindItem__left}>
        <LabAndImg value={labAndImgObj(itemData)} />
      </View>
      <View className={styles.colorKindItem__center}>
        <Text className={styles['colorKindItem__center--title']}>
          {itemData.product_code}# {itemData.product_name}
        </Text>
        <View className={styles['colorKindItem__center--detail']}>
          <Text className={styles['colorKindItem__center--ID']}>{itemData.product_color_code}</Text>
          <Text className={styles['colorKindItem__center--description']}>{itemData.product_color_name}</Text>
        </View>
      </View>
      <View className={styles.colorKindItem__right}>
        <View className={styles['colorKindItem__right--price']}>￥ {formatPrice(itemData.sale_price)}/{itemData.sale_mode == EnumSaleMode.Plate ? '米' : 'kg'}</View>
        <View className={styles['colorKindItem__right--counter']}>
          <Counter
            onBlue={getInputValue}
            defaultNum={count}
            onChange={handleCountChange}
            step={itemData.step}
            digits={itemData.digits}
            onClickBtn={getInputValue}
            unit={formatUnit(itemData)}
            minNum={itemData.sale_mode == EnumSaleMode.Bulk ? itemData.min_num : formatMeterDiv(itemData.min_num)}
            maxNum={itemData.sale_mode == EnumSaleMode.Bulk ? itemData.max_num : formatMeterDiv(itemData.max_num)}
          />
        </View>
      </View>
    </MCheckbox>
  )
}
// State 分割组件 思路就是把 context 直接通过 props 的形式传给组件，这样的话就解决了 context 强制刷新 memo 的问题了
// 那么当 context 内的 value 被更新的时候，react 只会强制渲染 Wrapper
const withStateSlice = (comp, slice) => {
  const MemoComp = memo(comp, (prevProps, nextProps) => {
    let needMemo = true
    if (prevProps.itemData !== nextProps.itemData) {
      console.log('itemData 有变化')
      needMemo = false
    }
    if (prevProps.state.Observer !== nextProps.state.Observer) {
      console.log('Observer 有变化')
      needMemo = false
    }
    if (prevProps.checked !== nextProps.checked) {
      console.log('checked 有变化', prevProps.checked, nextProps.checked)
      needMemo = false
    }
    if (prevProps.purchaserId !== nextProps.purchaserId) {
      console.log('purchaserId 有变化')
      needMemo = false
    }
    return needMemo
  })
  const Wrapper = (props, ref) => {
    const state = useShoppingState()
    return <MemoComp ref={ref} state={slice(state, props)} {...props} />
  }
  return memo(forwardRef(Wrapper))
}

const ColorKindItemWithStateSlice = withStateSlice(ColorKindItem, (state: ShoppingStateContextValue, props: PropsType) => {
  return {
    Observer: state.Observer,
  }
})

export default ColorKindItemWithStateSlice
