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

export type 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不限制
}
export default ({ value, show = false, onClose, showNumber = 1 }: colorParams) => {
  useEffect(() => {
    if (show && rgbStyle) setLabShow(() => true)
    if (show && value?.texture_url) onShowImage()
    if (!show) setLabShow(() => false)
  }, [show])

  //显示颜色
  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)
      })
    }
    let n_res = showNumber == 0 ? res : res?.splice(0, showNumber)
    Taro.previewImage({
      current: n_res[0],
      urls: n_res,
    })
  }

  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>
      )}
    </>
  )
}
