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

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

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);
  });
}

const uploadButton = (
  <div>
    <PlusOutlined />
    <div className="ant-upload-text">Upload</div>
  </div>
);
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);

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

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

  useEffect(() => {
    // if (props.disabled) {
    if (props.defaultValue != null) {
      var tmp = props.defaultValue;
      var result = new Array();
      var resultToInside = new Array();

      tmp.map((item: any, index: any) => {
        if (item.name == null) {
          item.name = getUrlPicName(item.url);
          item.uid = index;
        }
        result.push(item);
        resultToInside.push(item.name);
      });
      setFileList(result);
    }
    //   }
  }, [props.defaultValue]);

  // useEffect(() => {
  //   if (props.disabled) {
  //     if (value != null) {
  //       var tmp = value
  //       var result = new Array()
  //       var resultToInside = new Array()
  //       console.log("图片集使用表单组件");
  //       console.log(tmp)
  //       if (tmp.url != null) {
  //         tmp.map((item: any, index: any) => {
  //           if (item.name == null) {
  //             item.name = getUrlPicName(item.url)
  //             item.uid = index
  //           }
  //           result.push(item)
  //           resultToInside.push(item.name)
  //         })
  //         setFileList(result)
  //       }
  //     }
  //   }
  // }, [value])

  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;
    let tmp = fileList;
    setFileList(tmp.filter((file: any) => !!file.status || file.status == null));
    var result = new Array();
    fileList.map((item: { name: string }, index: number) => {
      result.push(item.name);
    });
    onChange(result);
  };
  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 file!');
    }
    // 文件大小判断
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  }

  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}
        beforeUpload={beforeUpload}
        onChange={handleChange}
        disabled={props.over}
      >
        {fileList.length >= limitNum ? null : props.disabled ? null : uploadButton}
      </Upload>
      <Modal
        title="Preview"
        footer={null}
        visible={previewVisible}
        onOk={handleCancel}
        onCancel={handleCancel}
      >
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </div>
  );
};

export default PictureOptionsRow;
