import React, { useCallback, useState } from 'react'
import styles from './index.module.scss'
import { baseURL } from '@/utils/http'
import imgLoding from '@/assets/img/loading.gif'
import imgErr from '@/assets/img/IMGerror.png'
import { EyeOutlined } from '@ant-design/icons'
import store from '@/store'
import { Image } from 'antd-mobile'
import { Image as ImagePc } from 'antd'

type Props = {
  width?: number | string
  height?: number | string
  imgList: any
  noLook?: boolean
  offline?: boolean
}

function ImageLazy({
  width = 100,
  height = 100,
  imgList,
  noLook,
  offline = false
}: Props) {
  const PreviewGroup = ImagePc.PreviewGroup

  // 默认不能预览图片，加载成功之后能预览
  const [lookImg, setLookImg] = useState(false)

  // 图片加载完成
  const onLoad = useCallback(() => {
    setLookImg(true)
  }, [])

  // 点击预览图片
  const lookBigImg = useCallback(
    (src?: string, srcBig?: string) => {
      store.dispatch({
        type: 'layout/lookBigImg',
        payload: {
          url: (offline ? src : srcBig ? baseURL + srcBig : baseURL + src) as string,
          show: true
        }
      })
    },
    [offline]
  )

  return (
    <div className={styles.ImageLazy} style={{ width: width, height: height }}>
      <div className='lazyBox'>
        {imgList.map((item: any, index: number) => {
          return (
            <PreviewGroup key={index}>
              <Image
                lazy
                onLoad={onLoad}
                src={item.thumb ? (offline ? item.thumb : baseURL + item.thumb) : ''}
                placeholder={<img src={imgLoding} alt='' />}
                fallback={<img src={imgErr} alt='' />}
                fit='cover'
              />
              {/* 图片预览 */}
              {noLook || !lookImg ? null : (
                <div
                  className='lookImg'
                  onClick={() => lookBigImg(item.thumb, item.filePath)}
                >
                  <EyeOutlined />
                  &nbsp;
                  <div>预览</div>
                </div>
              )}
            </PreviewGroup>
          )
        })}
      </div>
    </div>
  )
}

const MemoImageLazy = React.memo(ImageLazy)

export default MemoImageLazy
