import { View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { formatImgUrl } from '@/common/format'

export interface colorParams {
  value?: {
    texture_url?: string // 纹理图路径
    lab?: { l: number; a: number; b: number } // lab
    rgb?: { r: number; g: number; b: number } // rgb
    title?: string // 标题
  }
  show?: false | true
  onClose?: () => void
  showNumber?: number // 图片显示张数，0不限制
}
const LabAndImgShow = ({ value, show = false, onClose, showNumber = 1 }: colorParams) => {
  // 显示颜色
  const [labShow, setLabShow] = useState(false)
  // 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])

  // 显示图片
  const onShowImage = () => {
    onClose?.()
    let res: string[] = []
    if (value?.texture_url) {
      res = value?.texture_url?.split(',').map((item) => {
        return formatImgUrl(item)
      })
    }
    const n_res = showNumber == 0 ? res : res?.splice(0, showNumber)
    Taro.previewImage({
      current: n_res[0],
      urls: n_res,
    })
  }
  useEffect(() => {
    if (show && rgbStyle) { setLabShow(() => true) }
    if (show && value?.texture_url) { onShowImage() }
    if (!show) { setLabShow(() => false) }
  }, [show])
  return (
    <>
      {labShow && (
        <View className={styles.main} catch-move="true" onClick={() => onClose?.()}>
          <View className={styles.con}>
            <View className={styles.rgb} style={rgbStyle!}></View>
            <View className={styles.name}>{value?.title}</View>
          </View>
        </View>
      )}
    </>
  )
}

export default LabAndImgShow
