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 Preview from '@/pages/details/components/preview'
import { formatImgUrl, formatRemoveHashTag } from '@/common/fotmat'

// 该组件宽高为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
  }
  customImageStyle?: React.CSSProperties
  showStatus?: true | false
  onClick?: (val: Param['value']) => void
  round?: boolean
  name?: string
}
const LabAndImg = ({ value, onClick, showStatus = false, round = false, name = '', customImageStyle = {} }: 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 imgs = value.texture_url.split(',').map((item) => {
        return formatImgUrl(item)
      })
      setImgs(() => imgs[0])
    }
  }, [value])

  const [labAndImgShow, setLabAndImgShow] = useState(false)
  const closeLabAndImgShow = useCallback(() => {
    setLabAndImgShow(false)
  }, [])

  const onShowLabAndImg = (e) => {
    onClick?.(value)
    if (!showStatus) { return false }
    setLabAndImgShow(true)
  }

  const checkLoad = (val) => {
    setImgs(() => formatImgUrl(''))
  }

  return (
    <>
      <View className={styles.labAndImg_main} style={{ borderRadius: round ? '50%' : '' }} onClick={onShowLabAndImg}>
        {value.texture_url && (
          <Image
            lazyLoad
            mode="aspectFill"
            src={imgs}
            onError={e => checkLoad(e)}
            className={styles.labAndImg_image}
            style={{ borderRadius: round ? '50%' : '', ...customImageStyle }}
          ></Image>
        )}
        {!value.texture_url && rgbStyle && <View className={styles.boxColor} style={{ ...rgbStyle, borderRadius: round ? '50%' : '', ...customImageStyle }}></View>}
        {!value.texture_url && !rgbStyle && (
          <Image mode="aspectFill" src={formatImgUrl('')} className={styles.labAndImg_image} style={{ borderRadius: round ? '50%' : '', ...customImageStyle }} lazyLoad></Image>
        )}
        {name && <View className={styles.labAndImg_name}>{name}</View>}
      </View>
      <LabAndImgShow value={value} show={labAndImgShow} onClose={closeLabAndImgShow} />
    </>
  )
}
export default memo(LabAndImg)
