import { Image, View } from '@tarojs/components'
import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import LabAndImgShow from '../LabAndImgShow'
import styles from './index.module.scss'
import { formatImgUrl } from '@/common/format'

// 该组件宽高为100%需调整外层元素宽高
interface Param {
  value?: {
    texture_url?: string // 纹理图路径
    lab?: { l: number; a: number; b: number } // lab
    rgb?: { r: number; g: number; b: number } // rgb
    title?: string
  }
  showStatus?: true | false
  onClick?: (val: Param['value']) => void
}
const LabAndImg = ({ value, onClick, showStatus = false }: Param) => {
  const [imgs, setImgs] = useState<string[]>([])

  // lab是否都是0
  const rgbStyle = useMemo(() => {
    if (value?.lab && (value.lab.l || value.lab.a || value.lab.b)) {
      return { backgroundColor: `rgb(${value.rgb?.r} ${value.rgb?.g} ${value.rgb?.b})` }
    }
    else {
      return null
    }
  }, [value])

  useEffect(() => {
    if (value?.texture_url) {
      const res = value.texture_url.split(',').map((item) => {
        return formatImgUrl(item)
      })
      setImgs(() => res)
    }
  }, [value])

  const [labAndImgShow, setLabAndImgShow] = useState(false)
  const closeLabAndImgShow = useCallback(() => {
    setLabAndImgShow(false)
  }, [])
  const onShowLabAndImg = () => {
    onClick?.(value)
    if (!showStatus) { return false }
    setLabAndImgShow(true)
  }

  const handleImageError = () => {
    setImgs([])
  }

  return (
    <>
      <View className={styles.labAndImg_main} onClick={() => onShowLabAndImg()}>
        {imgs?.length > 0 && <Image mode="aspectFill" src={imgs[0]} className={styles.labAndImg_image} onError={handleImageError}></Image>}
        {!imgs?.length && rgbStyle && <View className={styles.boxColor} style={{ ...rgbStyle }}></View>}
        {!imgs?.length && !rgbStyle && <Image mode="aspectFill" src={formatImgUrl('')} className={styles.labAndImg_image}></Image>}
      </View>
      <LabAndImgShow value={value} show={labAndImgShow} onClose={closeLabAndImgShow} />
    </>
  )
}
export default memo(LabAndImg)
