import { formatImgUrl, formatRemoveHashTag } from '@/common/fotmat'
import Preview from '@/pages/details/components/preview'
import { Image, View } from '@tarojs/components'
import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import LabAndImgShow from '../LabAndImgShow'

//该组件宽高为100%需调整外层元素宽高
type 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
}
export default memo(({ 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) {
      let 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)
  }

  return (
    <>
      <View className={styles.labAndImg_main} onClick={() => onShowLabAndImg()}>
        {imgs?.length > 0 && <Image mode='aspectFill' src={imgs[0]} className={styles.labAndImg_image}></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} />
    </>
  )
})
