import React, { Component } from 'react'
import { Avatar } from 'antd'
import { isEqual } from 'lodash'
import { PreviewFileBase64 } from 'util/file'

const getSrc = async id => {
    if (id) {
        const base64 = await PreviewFileBase64(id)
        return base64
    }
    return ''
}

export default class Image extends Component {
    state = {
        src: '',
    }

    id = ''

    constructor(props) {
        super(props)

        this.setSrc()
    }

    shouldComponentUpdate(props, state) {
        // props变更或state.src变更时进行渲染
        return !isEqual(this.props, props) || this.state.src !== state.src
    }

    componentDidUpdate() {
        if (this.id !== this.props.id && this.props.id) {
            this.setSrc()
        }
    }

    setSrc = async () => {
        if (this.props.id) {
            this.id = this.props.id
            const src = await getSrc(this.id)
            this.setState({ src })
        }
    }

    render() {
        if (this.props.type === 'avatar') {
            return <Avatar src={this.state.src} {...this.props} />
        } else {
            return <img src={this.state.src} {...this.props} alt="" />
        }
    }
}
