import { CustomWrapper, Text, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import Big from 'big.js'
import ColorCheckbox from '../colorCheckbox'
import RecommendProduct from '../recommendProduct'
import styles from './index.module.scss'
import LabAndImg from '@/components/LabAndImg'
import Counter from '@/components/counter'
import type { ColorType } from '@/context/ContextShop'
import { useCurrenShop } from '@/context/ContextShop'
import { formatPriceDiv } from '@/common/fotmat'
import { DelShoppingCartApi, GetShoppingCartApi, UpdateShoppingCartApi } from '@/api/shopCart'
import { debounce } from '@/common/util'
import { SALE_MODE_SETTING } from '@/common/enum'

interface ColorItemType {
  colorItem: ColorType
}

type IndexItemType = {
  onSelect?: (val: boolean) => void
  onChangeNum?: (val: { id: number; length: number; roll: number }) => void
  onSubmitSuccess?: () => void
}&ColorItemType

export default memo((props: ColorItemType) => {
  const { fetchData: updateShoppingCartFetchData } = UpdateShoppingCartApi()
  const { fetchData: getShoppingCartFetchData } = GetShoppingCartApi()
  const { fetchData: delShopFetchData } = DelShoppingCartApi()
  const { colorItem } = props
  const { state, dispatch } = useCurrenShop()
  const indexs = colorItem.index_str.split(',')
  const colorItemNew: ColorType = state.list[indexs[0]].color_list[indexs[1]]
  const onChangeNum = useCallback(async(val) => {
    if (val.roll == 0 && val.length == 0) {
      Taro.showModal({
        content: '确定删除该商品？',
        confirmText: '删除',
        async success(res) {
          if (res.confirm) {
            const res = await delShopFetchData({ id: [colorItemNew.id] })
            if (res.success) {
              dispatch({ type: 'setDelCommendId', data: { list: state.list, delCommendId: colorItemNew.id } })
            }
          }
          else if (res.cancel) {
            state.list[indexs[0]].color_list[indexs[1]] = { ...state.list[indexs[0]].color_list[indexs[1]] }
            dispatch({ type: 'updateProduct', data: { list: state.list } })
          }
        },
      })
    }
    else {
      await updateShoppingCartFetchData(val)
      const res = await getShoppingCartFetchData({ id: colorItem.id })
      if (res.success) {
        state.list[indexs[0]].color_list[indexs[1]] = { ...state.list[indexs[0]].color_list[indexs[1]], ...res.data.color_list[0] }
        dispatch({ type: 'updateProduct', data: { list: state.list } })
      }
    }
  }, [colorItemNew])

  const onSubmitSuccess = useCallback(() => {
    dispatch({ type: 'setRecommendId', data: { list: state.list, recommendId: colorItemNew.id } })
  }, [colorItemNew])
  return <Index colorItem={state.list[indexs[0]].color_list[indexs[1]]} onChangeNum={onChangeNum} onSubmitSuccess={onSubmitSuccess} />
})

const Index = memo((props: IndexItemType) => {
  const { colorItem, onChangeNum, onSubmitSuccess } = props
  const rga = useMemo(() => {
    return { lab: colorItem.lab, rgb: colorItem.rgb, texture_url: colorItem.texture_url, title: colorItem.product_color_code }
  }, [colorItem])
  const [count, setCount] = useState(0)
  useEffect(() => {
    setCount(() => colorItem.sale_mode === 0 ? colorItem.roll : colorItem.length / 100)
  }, [colorItem])
  const getCount = debounce(async(num) => {
    setCount(num)
    const data = { id: colorItem.id, length: 0, roll: 0 }
    if (colorItem.sale_mode === 0) {
      data.roll = num
    }
    else {
      data.length = Big(num).times(100).toNumber()
    }
    onChangeNum?.(data)
  }, 300)
  const selectList = SALE_MODE_SETTING
  const saleSetting = useMemo(() => {
    return selectList[colorItem.sale_mode]
  }, [colorItem])
  console.log('colorItem::', colorItem)

  const checkBoxRef = useRef<any>(null)
  return <>
    <View className={styles.shop_product_item_con}>
      <View className={styles.shop_product_item}>
        <ColorCheckbox colorItem={colorItem} ref={checkBoxRef} />
        <View className={styles.item_con} onClick={() => checkBoxRef.current.onSelect()}>
          <View className={styles.img}>
            <LabAndImg value={rga}></LabAndImg>
          </View>
          <View className={styles.item_name_price_count}>
            <View className={styles.name_price}>
              <Text>{colorItem.product_color_code + colorItem.product_color_name}</Text>
              <View className={styles.price}>
                <Text>{colorItem.standard_price > colorItem.sale_price && `¥${formatPriceDiv(colorItem.standard_price)}`}</Text>
                <Text>¥{formatPriceDiv(colorItem.sale_price)}/kg</Text>
              </View>
            </View>
            <View className={styles.count_con}>
              <View className={styles.recommend_title}>
                {colorItem.is_screw_recommend
                && <>
                  <Text>推荐</Text>
                  <Text>配套螺纹</Text>
                </>
                }
              </View>
              <View className={styles.count}>
                <CustomWrapper>
                  <Counter
                    onClickBtn={getCount}
                    minNum={saleSetting.minNum}
                    maxNum={saleSetting.maxNum}
                    onBlue={getCount}
                    defaultNum={count}
                    unit={colorItem.sale_mode === 0 ? '条' : '米'}
                    digits={saleSetting.digits}
                    returnZero
                  />
                </CustomWrapper>
              </View>
            </View>

          </View>
        </View>
      </View>
      {colorItem.has_screw_recommend && <RecommendProduct onClick={onSubmitSuccess} />}
    </View>
  </>
})
