import { Text, View } from '@tarojs/components'
import type { FC } from 'react'
import React, { memo, useEffect, useRef, useState, useTransition } from 'react'
import classnames from 'classnames'
import dayjs from 'dayjs'
import styles from './index.module.scss'
import { formatHashTag } from '@/common/format'
import { alert } from '@/common/common'
import type { BluetoothStateType } from '@/use/contextBlueTooth'
import { toRgb } from '@/common/bluetooth/color/colorSpace'

interface PropsType {
  currentTakeColorIndex?: number | null
  item?: Record<string, any>
  index?: number
  onPreviewRgb?: Function
  onTakeColor?: Function
  measureAndGetLab: Function
  bluetoothState: BluetoothStateType
}

const ColorCard: FC<PropsType> = (params) => {
  const { item = {}, index, onTakeColor, onPreviewRgb, currentTakeColorIndex, measureAndGetLab, bluetoothState } = params
  console.log('item===>', item)
  const truncation = (ev) => {
    if (ev) {
      ev += ''
      const index = ev.lastIndexOf('.')
      let suffix = ev.substr(index + 1)
      if (suffix.length > 2) {
        suffix = suffix.substr(0, 1)
        ev = `${ev.substr(0, index)}.${suffix}`
      }
      return ev
    }
    else {
      return 0
    }
  }
  const [moveBorder, setMoveBorder] = useState<number>(0)
  const [color, setColor] = useState({
    currnetRgb: item.rgb,
    currentLab: item.lab,
  })

  useEffect(() => {
    console.log('lastTakeColorIndex,index', currentTakeColorIndex, index)
    if (currentTakeColorIndex != null && currentTakeColorIndex !== index) {
      setMoveBorder(0)
    }
  }, [currentTakeColorIndex, index])

  const handleTakeColor = async() => {
    if (bluetoothState.connected) {
      onTakeColor?.(index)

      setMoveBorder(1)
      console.log('moveBorder==> start measure', moveBorder)
      const lab = await measureAndGetLab()
      // 转rgb
      const rgb = toRgb([lab.L, lab.a, lab.b])
      setColor({
        currnetRgb: {
          r: rgb[0],
          g: rgb[1],
          b: rgb[2],
        },
        currentLab: {
          l: lab.L,
          a: lab.a,
          b: lab.b,
        },
      })
      setMoveBorder(2)
      console.log('moveBorder==> end measure', moveBorder)
    }
    else {
      alert.none('请连接蓝牙')
    }
  }

  const handlePreviewRgb = () => {
    onPreviewRgb && onPreviewRgb()
  }

  return (
    <View className={classnames(styles['color-list'], { [styles.flash]: moveBorder === 1 })}>
      <View className={classnames(styles.vertical, { [styles['move-vertical']]: moveBorder === 2 })}>
        <View></View>
      </View>
      <View className={classnames(styles.horizontal, { [styles['move-horizontal']]: moveBorder === 2 })}></View>
      <View
        onClick={handlePreviewRgb}
        className={styles['c-image']}
        style={{
          backgroundColor: `rgb(
            ${color.currnetRgb?.r},
            ${color.currnetRgb?.g},
            ${color.currnetRgb?.b}
        )`,
        }}
      >
        {color.currentLab?.l == 0 && color.currentLab?.a == 0 && color.currentLab?.b == 0 && <Text>末取样</Text>}
      </View>
      <View className={styles['c-info']}>
        <View className={styles['c-i-title']}>{formatHashTag(item.product_code, item.product_name)}</View>
        <Text>
          {formatHashTag(item.product_color_code, item.product_color_name)}({moveBorder})
        </Text>
        <View className={styles['c-i-date']}>{item.absorb_lab_time && dayjs(item.absorb_lab_time).format('YYYY-MM-DD HH:mm:ss')}</View>
      </View>
      <View className={styles['c-lab']}>
        <View className={classnames(styles['c-lab-button'], { again: item.sampling })} onClick={handleTakeColor}>
          {item.sampling ? '重新取样' : '取样'}
        </View>
        <View className={styles['c-lab-text']}>
          <View>L*: {truncation(color?.currentLab?.l)}</View>
          <View>a*: {truncation(color?.currentLab?.a)}</View>
          <View>b*: {truncation(color?.currentLab?.b)}</View>
        </View>
      </View>
    </View>
  )
}
export default ColorCard
