import React, { useState, useEffect } from 'react';

import { Upload, Modal, message } from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';

import { randomString } from '@/utils/string';

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

import { getUrlPicName } from '../../utils/string';
const PictureOptionsRow = (props: any) => {
  const { value, onChange, limitNums } = props;
  const [fileList, setFileList] = useState([] as any);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [limitNum, setLimitNum] = useState(5);
  const handleCancel = () => setPreviewVisible(false);
  const [imgLoad, setimgLoad] = useState(false); //图片上传 load状态

  useEffect(() => {
    if (limitNums != null) {
      setLimitNum(limitNums);
    }
  }, [limitNums]);

  useEffect(() => {
    if (value != null) {
      var tmp = value;
      var result = new Array();
      var resultToInside = new Array();
      if (value.length == 0) {
        setFileList([]);
      } else if (tmp.length > 0 && typeof tmp[0] != 'string') {
        //输入输出
        tmp.map((item: any) => {
          if (item.name == null) {
            item.name = getUrlPicName(item.url);
            item.uid = randomString(8);
            item.status = 'done';
          }
          result.push(item);
          resultToInside.push(item.name);
        });
        setFileList(result);
        onChange && onChange(resultToInside);
      }
    }
  }, [value]);

  // 加载logo
  const uploadButton = (
    <div>
      {imgLoad ? <LoadingOutlined /> : <PlusOutlined />}
      <div className="ant-upload-text">Upload</div>
    </div>
  );

  const handlePreview = async (file: any) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewVisible(true);
  };

  const handleChange = ({ file, fileList }: any) => {
    // 给传递的附加名字
    // props.data.fileName = fileList[0].name;

    file.status === 'uploading' ? setimgLoad(true) : setimgLoad(false);

    if (file.status == 'done') {
      let tmp = fileList.filter((file: any) => {
        return file.status == 'done';
      });
      setFileList(tmp);
      var result = new Array();
      tmp.map((item: { name: string }, index: number) => {
        result.push(item.name);
      });
      onChange && onChange(result);
    }
  };

  // 移除
  const onRemove = (file: any) => {
    let list = fileList;
    for (let i in list) {
      if (list[i].uid == file.uid) {
        list.splice(i, 1);
      }
    }
    setFileList([...list]);
    onChange && onChange([...list]);
  };

  // 提交前限制
  function beforeUpload(file: any) {
    // 文件类型判断
    const isJpgOrPng =
      file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG/Jpeg file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must be less than or equal to 2MB!');
    }
    return isJpgOrPng && isLt2M;
  }
  console.log(props);
  return (
    <div>
      <Upload
        accept=".png,.jpg,.jpeg"
        action={props.action != null ? props.action : '/tos/image/upload'}
        listType="picture-card"
        data={props.data}
        fileList={fileList}
        onPreview={handlePreview} // 预览
        onRemove={onRemove} // 删除
        beforeUpload={beforeUpload}
        onChange={handleChange} // 点击上传
        disabled={props.over}
      >
        {fileList.length >= limitNum ? null : props.disabled ? null : uploadButton}
      </Upload>
      <Modal
        title="Preview"
        width={640}
        footer={null}
        visible={previewVisible}
        onOk={handleCancel}
        onCancel={handleCancel}
      >
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </div>
  );
};

export default PictureOptionsRow;
