import React, { useRef } from 'react';
import { Wrapper, Img, Span, OverLay, HiddenFileInput, UploadIcon, Spin } from './style';
import useDataApi from 'utils/useDataApi';
import { getDescendantProp, buildNestedObj, getImgDimension } from 'utils';
import validate from './validateImg';
import { IAvatar } from './types';
const Avatar = function({
    accept = 'image/*',
    additionalData = {},
    actionUrl = 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    width = 110,
    propertyPath = '.url',
    heightLimit = [-Infinity, Infinity],
    name = 'file',
    ratioLimit = [-Infinity, Infinity],
    sizeLimit = Infinity,
    widthLimit = [-Infinity, Infinity],
    ...rest
}: IAvatar) {
    const [state, doUpload] = useDataApi(actionUrl, buildNestedObj({}, propertyPath, ''));
    const fileInput: any = useRef();
    const paths = propertyPath.split('.').filter(Boolean);
    paths.unshift('data');
    const url = getDescendantProp(state, paths.join('.'));

    return (
        <Wrapper onClick={() => (fileInput.current as HTMLInputElement).click()} width={width} {...rest}>
            {url && <Img src={url} />}
            {url && (
                <OverLay className="overlay">
                    <UploadIcon className="uploadIcon" />
                    <Span>重新上传</Span>
                </OverLay>
            )}
            {state.isLoading && <Spin color="white" strokeWidth={4} />}
            {!url && !state.isLoading && <UploadIcon className="uploadIcon" />}
            <HiddenFileInput
                ref={fileInput}
                accept={accept}
                onChange={async ({ target: { files } }: any) => {
                    if (!files.length) {
                        return;
                    }
                    const img: any = await getImgDimension(files[0]);
                    const passed = validate(img, sizeLimit, ratioLimit, widthLimit, heightLimit);
                    if (!passed) {
                        return;
                    }
                    const data = new FormData();
                    Object.entries(additionalData).forEach(([key, value]) => data.append(key, value as any));
                    data.append(name, files[0]);
                    doUpload({
                        data,
                    });
                }}
            />
        </Wrapper>
    );
};

export default Avatar;
