import React from 'react'
import PropTypes from 'prop-types'
import { Upload , Icon ,Button} from 'antd'
import style  from './index.less'
import { getQiniuToken } from '../../services/common'

let  data = {}

function toqiniu (file,fileList) {
    return getQiniuToken().then(res=>{
        // console.log(res)
        if(res.success){
            data.token = res.upToken
            data.key = (+new Date()) + '_' + file.name.replace(/\-/g,'')
            return Promise.resolve(data)
        }else{
            return Promise.reject()
        }
    })
}

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img)
}


class MyUpLoad extends React.Component {
    constructor (props) {
        super(props)
        this.state = {
            result:props.imgUrl || props.vdoUrl || '',
            uploading:false
        }
    }
    
    componentWillReceiveProps (nextProps) {
        // // console.log(nextProps)
        // if(nextProps.type === 'img'){
        //     this.setState({
        //         result:nextProps.imgUrl
        //     })
        // }
    }


    handleChange = (info) => {
        this.setState({uploading:true})
        // console.log(info)
        if (info.file.status === 'done') {
            this.setState({uploading:false})
      // Get this url from response in real world.
            if(this.props.type === 'img'){
                getBase64(info.file.originFileObj, result => this.setState({ result }));
            }
            if(this.props.type === 'video'){
                this.setState({
                    result:info.file.response.key
                })
                // result = info.response.key
            }
            // console.log(info)
            this.props.upload("http://livefile.yxj.org.cn/"+info.file.response.key)
        }
    }

    child = (type,result) => {
        let size = this.props.size || null
        if(type && type === 'img'){
            return (result !=='' ?<img src={result} style={{width:size.w+'px',height:size.h+'px'}} className={style.avatar} /> :<Icon type="plus" style={{width:size.w+'px',height:size.h+'px'}} className={style.avatartrigger} />)
        }else{
            return (<Button  size="large" icon={result === ''?'plus':''} loading={this.state.uploading}> {result === ''?( this.state.uploading?'正在上传':'点击上传'):'上传成功' }</Button>)
        }
    }

    render () {
        let result = this.state.result;
        let type = this.props.type
        let accept = this.props.type === 'img'?'image/png,image/jpg':'video/*'
        return (
             <Upload accept={accept}  showUploadList={false} onChange={this.handleChange} beforeUpload={toqiniu} name="file" data={data} action="http://upload.qiniu.com/">
                {
                    this.child(type,result)
                }
            </Upload>
        )
    }
} 

export default MyUpLoad