import React, { useState, useEffect } from 'react';
import styles from './index.less';

import { Upload, Modal,Row,Col,Input,message} from 'antd';
import { PlusOutlined,PictureFilled } from '@ant-design/icons';
import { OmitProps } from 'antd/lib/transfer/ListBody';

function getBase64(file:any) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
const Picture = (props:any) => {

  const [previewVisible, setPreviewVisible] = useState(false)
  const [previewImage, setPreviewImage] = useState('')
  const [previewTitle, setPreviewTitle] = useState('')
  const [fileList, setFileList] = useState([])
  
  useEffect(() => {
    var tmp = props.defaultValue
    var checkFlag=false
    if (tmp != null) {    
      tmp.map((item, index) => {
        if (item.name == null||item.pic==null) {
          checkFlag=true
        }
      })
      if (!checkFlag) {
        setFileList(tmp)
       }
      
    }
  },[props.defaultValue])
  const handleCancel = () => {
    setPreviewVisible(false)
  }
  
  const handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview)
    setPreviewVisible(true)
    setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1))
  };

  const handleChange = ({ file,fileList }) => {
    let tmp=fileList
    setFileList(tmp.filter(file => !!file.status))
    // console.log(fileList)
    if (file.status === 'done') {
      // console.log("success upload picture")
      props.onSubmit(file.name)
    } 
  }
  const handleRemove = (file: any) => {
    // props.onSubmit(file.name)
    props.onDelete(file.name)
  }
  const beforeUpload=( file:any) => {
    if (file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg') {
      return true
    } else {
      message.error(`${file.name} is not a png/jpeg/jpg file`);
      return false
    }
  }
    
  const uploadButton = (
    <div>
      <PictureFilled style={{ fontSize: '28px' }}/>
      <div className="ant-upload-text">Upload</div>
    </div>
  );
  const uploadpic = (
    <Upload
      accept=".png,.jpg,.jpeg"
      action="/tos/image/upload"
      listType="picture-card"
      data={props.data} 

      fileList={fileList}
      onPreview={handlePreview}
      onChange={handleChange}
      onRemove={handleRemove}
      disabled={props.disabled}
      beforeUpload={beforeUpload}> 
      {fileList.length >= 1 ? null : uploadButton}
    </Upload>  
  )
  return (
    <div>
      {uploadpic}
      
      <Modal  visible={previewVisible}  title={previewTitle} footer={null} onCancel={handleCancel} onOk={handleCancel}>
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>  
    </div>
  );
};

export default Picture;



