import React from 'react'

import type { BorderProps, LayoutProps, SpaceProps } from '@lx-react-materiel/shared'
import { commonStyleFn } from '@lx-react-materiel/shared'

import type { ImageProps } from '@tarojs/components'
import { Image } from '@tarojs/components'
import Taro from '@tarojs/taro'

import './index.less'

interface ILxImageBasic {
  urls?: string[]
}

type ILxImageProps = ImageProps
& BorderProps
& LayoutProps
& SpaceProps
& ILxImageBasic

/**
 * 视图组件 支持 JPG、PNG、SVG、WEBP、GIF 等格式以及云文件ID。
 *
 * 1、基本用法参考 https://docs.taro.zone/docs/components/media/image
 * 2、更多用法请查看 lxImage.stories
 *
 * @param props
 * @example
 * 普通支持用法：
 * <LxImage src='' mode='aspectFill' borderRadius={50} onClick={() => void 0} width={100} height={100}></LxImage>
 *
 * 支持预览的用法：
 * <LxImage src='' urls=[]></LxImage>
 */
export function LxImage (props: ILxImageProps) {
  const {
    style = commonStyleFn(props),
    className = null,
    src,
    onClick,
    urls = [src],
    ...rest
  } = props

  const handleClick: Pick<ImageProps, 'onClick'>['onClick'] = (e) => {
    if (onClick) {
      onClick(e)
      return
    }
    if (urls.length > 1) {
      Taro.previewImage?.({
        current: src,
        urls: [...urls]
      }).catch((e) => {
        console.log(e)
      })
    }
  }

  const mergeProps = {
    ...rest,
    src,
    className: `lx-image ${className ?? ''}`,
    style,
    onClick: handleClick
  }

  return (
    <Image { ...mergeProps } />
  )
}
