import React from 'react';
import { Upload, Icon, Modal, message } from 'antd';
import PropTypes from 'prop-types';

import { uploadUrl } from '../../services/api';
import Immutable, { Map, is } from 'immutable';
import './less/style.less';

/**w
 *
 * @desc    把 antd 组件的图片上传组件封装在一起，
 *          只需要关心初始化的值 init 以及 onchang 方法。支持多个图片
 * @param   {Array} init 初始化的地址
 * @param   {func} onResult(data)  返回图片上传结果。
 * @param   {Int} num  设置图片上传个数。
 * @param   {Int} disabled  设置图片是否禁止上传。
 * @param   {types} 限制上传图片的格式。
 * @param   {size} 限制上传图片的大小。 单位MB  2019-09-23
 * @return
 */

class PUpLodadImg extends React.Component {
    state = {
        previewVisible: false,
        previewImage: '',
        fileList: [],
        ifInit: false //是否加载完成初始化
    };

    static propTypes = {
        init: PropTypes.array,
        onResult: PropTypes.func,
        num: PropTypes.number,
        disabled: PropTypes.bool
    };

    componentWillMount = () => {
        if (this.props.init) {
            if (Object.prototype.toString.call(this.props.init) == '[object Array]') {
                this.updataList(this.props.init);
            }
        }
    };

    componentWillReceiveProps = nextProps => {
        const nextInit = nextProps.init;
        const thisInit = this.props.init;
        // if (this.state.ifInit) {
        //     return;
        // }

        if (JSON.stringify(nextInit) !== JSON.stringify(thisInit)) {
            if (nextInit && nextInit.length !== 0) {
                this.updataList(nextInit);
            }
        }
    };

    shouldComponentUpdate = (nextProps = {}, nextState = {}) => {
        const thisProps = this.props || {},
            thisState = this.state || {};

        if (
            Object.keys(thisProps).length !== Object.keys(nextProps).length ||
            Object.keys(thisState).length !== Object.keys(nextState).length
        ) {
            return true;
        }
        for (const key in nextProps) {
            if (
                thisProps[key] !== nextProps[key] ||
                !is(thisProps[key], nextProps[key])
            ) {
                return true;
            }
        }
        for (const key in nextState) {
            if (
                thisState[key] !== nextState[key] ||
                !is(thisState[key], nextState[key])
            ) {
                return true;
            }
        }
        return false;
    };

    //刷新
    updataList = arr => {
        const newArr = arr.filter(val => val.trim() !== '');
        if (newArr.length !== 0) {
            let fileList = [];
            newArr.map((val, key) => {
                fileList.push({
                    uid: key,
                    url: val
                });
            });
            this.setState({ fileList, ifInit: true });
        }
    };

    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = file => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true
        });
    };

    handleChange = info => {
        let result = true;
        const { status } = info.file;

        const disabled = this.props.disabled ? this.props.disabled : false;
        if (disabled) {
            return;
        }

        //除了移除状态，上传过程中，判断是否符合上传规则
        if (status !== 'removed') {
            result = this.beforeUpload(info.file);
        }
        if (!result) {
            return;
        }

        let fileList = [...this.state.fileList];
        fileList = info.fileList;
        this.setState({ fileList });

        if (status !== 'uploading') {
        }
        if (status === 'done') {
            if (info.file.response.retType !== '0') {
                /// 本地上传成功，但服务器返回上传错误
                this.state.fileList.map((item, index) => {
                    if (item.uid === info.file.uid) {
                        const removeErrFileList = [...this.state.fileList];
                        removeErrFileList.splice(index, 1);
                        this.setState({
                            fileList: removeErrFileList
                        });
                        // this.state.fileList[index].status = "error";
                    }
                });
                message.error(info.file.response.msg);
                return;
            }
            // this.props.result("done", info.file.response.data.filegroupid);
            message.success(`${info.file.name} 文件上传成功。`);

            if (this.props.onResult) {
                if (info.fileList.length === 0) {
                    return;
                }
                const result = info.fileList.reduce((acc, elem) => {
                    if (elem.response && elem.response.data) {
                        acc.push(elem.response.data);
                        return acc;
                    }
                    if (elem.url) {
                        acc.push(elem.url);
                        return acc;
                    }
                }, []);
                this.props.onResult(result);
            }
        } else if (status === 'error') {
            message.error(`${info.file.name} 文件上传失败。`);
        }
        if (info.file.status == 'removed') {
            let result;
            //如果全部删除
            if (info.fileList.length === 0) {
                this.props.onResult([]);
                return;
            } else {
                //如果部分删除
                result = info.fileList.reduce((acc, elem) => {
                    if (elem.url) {
                        acc.push(elem.url);
                        return acc;
                    }
                }, []);
            }
            this.props.onResult(result);
        }
    };

    beforeUpload = file => {
        /**
         * 新增文件类型格式的判断 2019-08-14 Lyq
         * 
         */
        const types = this.props.types || ['image/png', 'image/jpeg', 'image/jpg'];
        const imgType = file.name.split('.')[file.name.split('.').length - 1];
        const has = types.some(item => item.indexOf(imgType) != -1);
        if (!has) {
            // 拼接
            const tip = types.reduce((str, item) => {
                const type = item.split('/')[1];
                return str + (type ? type : '') + (type ? ',' : '');
            }, '');
            message.error(`只能上传${tip.slice(0, -1)}类型的文件!`);
            // message.error('只能上传png,jpeg,jpg类型的图片!');
            return false;
        }
        // file.size = file.size / 1024;  //字节大小转成KB
        let result = true;
        if (Object.prototype.toString.call(this.props.size).slice(8, -1) == 'Array') {
            const sizes = this.props.size.sort((a, b) => a - b);
            if (sizes[0] * 1024 * 1024 > file.size) {
                if (this.props.sizeErrMsg) {
                    message.error(this.props.sizeErrMsg);
                } else {
                    let unit = size[0]*1024 > 1024 ? `${size[0]}M!` : `${size[0]*1024}kb!`;
                    message.error(`图片应大于${unit}`);
                }
                result = false;
            }
            if (sizes[1] * 1024 * 1024 < file.size) {
                if (this.props.sizeErrMsg) {
                    message.error(this.props.sizeErrMsg);
                } else {
                    let unit = size[0]*1024 > 1024 ? `${size[0]}M!` : `${size[0]*1024}kb!`;
                    message.error(`图片应小于${unit}`);
                }
                result = false;
            }
        } else {
            const size = this.props.size ? this.props.size*1024* 1024 : 8 * 1024*1024;

            if (file.size > size) {
                if (this.props.sizeErrMsg) {
                    message.error(this.props.sizeErrMsg);
                } else {
                    let unit = size > 1? `${size/1024/1024}M!` : `${size*1024}kb!`;
                    message.error(`图片应小于${unit}`);
                }
                result = false;
            }
        }
        return result;
    };

    render() {
        const { previewVisible, previewImage, fileList } = this.state;
        const uploadButton = (
            <div >
                <Icon type="plus"/>
                <div className="ant-upload-text" > 上传 </div>
            </div>
        );
        const num = this.props.num ? this.props.num : 1;
        const disabled = this.props.disabled ? this.props.disabled : false;
        return (<div className="clearfix" >
            <Upload action={uploadUrl}
                name="xfile"
                listType="picture-card"
                fileList={fileList}
                onPreview={this.handlePreview}
                onChange={this.handleChange}
                disabled={disabled}
                className={disabled ? "deleteIcon" : null}
            // beforeUpload={this.beforeUpload}
            >
                {fileList.length >= num ? null : uploadButton} 
            </Upload>
            <Modal visible={previewVisible}
                footer={null}
                onCancel={this.handleCancel}
                className="preview-modal"
                width="90%"
                height="90%"
                centered bodyStyle={
                    {
                        textAlign: 'center',
                        verticalAlign: 'middle',
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        padding: '50px 24px'
                    }
                } >
                <div className="preview-img-wrap" >
                    <img alt="example"
                        style={
                            { maxWidth: '100%' }
                        }
                        src={previewImage}
                    /> </div> 
                </Modal> 
            </div>
        );
    }
}

export default PUpLodadImg;