import React from 'react';
import { message } from 'kts-xui';
import { Upload } from 'kts-components-antd-x4'
// import { DigitalAssetVerification as agent } from '../../../';
import agent from '../../Server';
/** Props接口 */
interface IProps {
    children?: any;
    onChange?: any;
    tokenUrl?: string;
    fileUrl?: string;
    showUploadList?: boolean; // 是否展示文件列表
    fileName?: any;
    formKey?: string;
    size?: number; // 限制上传大小 MB
    limitNum?: number; // 限制上传文件个数
    fileTypeList?: any[]; // 支持的类型
    value?: any;
    isUpload?: boolean;
    accept?: string;
}
/**
 * 由于采用自定义上传并且支持多图上传，这里的fileList在更新时可能出现前后不一致
 */
export default class UploadComponent extends React.Component<IProps, any> {
    index = 90001;
    list: any = [];
    constructor(props: IProps) {
        super(props);
        this.state = {
            uploadFileList: [],
            isUpload: this.props.isUpload || true, // 是否可以上传，true可以上传，false 不可以上传
            uploadFileUrl: {},
            token: null,
            keyPrefix: null,
            uploadUrl: null,
            value: this.props.value || []
        };
    }
    componentDidMount() {
        const { value } = this.state;
        if (value.length > 0) {
            const list = value.map((item) => {
                return {
                    name: item.fileOriginalName,
                    uid: this.index++,
                    status: "done",
                    response: {
                        key: item.fileUploadName
                    }
                };
            });
            this.setState({
                uploadFileList: list
            });
        }
    }
    beforeUploadHandler = async (file) => {
        let isType: boolean = true;
        if (this.props.fileTypeList && this.props.fileTypeList.length) {
            isType = ((this.props.fileTypeList as any).includes(file.type));
            if (!isType) {
                message.error(`当前类型${file.type}，只支持${this.props.fileTypeList.join('、')}`);
                this.setState({
                    isUpload: false
                });
                return false;
            }
        }
        const isLtSize = (file.size / 1024 / 1024) < (this.props.size || 1);
        if (!isLtSize) {
            this.setState({
                isUpload: false
            });
            message.error(`大小不能超过 ${this.props.size || 1}MB!`);
            return false;
        }
        // let suffix = file.type.split('/').pop();
        //重复的名字会覆盖 所以需要加时间戳
        let fileTrim = file.name.replace(/\s+/g, "");
        let fileName = new Date().getTime() + fileTrim;
        return new Promise((resolve, reject) => {
            this.getToken(fileName).then((res) => {
                if (res) {
                    resolve(file);
                } else {
                    reject();
                }
            });
        });
    }
    getToken = async (fileName: string) => {
        const { tokenUrl = '/web/verifiedTask/getFileUploadInfo' } = this.props;
        const response = await agent.post(tokenUrl, {
            fileName: fileName,
            type: 1
        }, null);
        const res = response.res;
        if (!res.er) {
            this.setState({
                token: res.uploadToken,
                uploadUrl: res.uploadUrl,
                keyPrefix: res.uploadFileName,
                isUpload: true
            });
            return true;
        } else {
            this.setState({
                isUpload: false
            });
            return false
        }
        // return isType && isLtSize;
    }
    handleChange = async info => {
        let fileList = info.fileList
        let file = info.file;
        let { value } = this.state;
        // console.log(this.state.isUpload);
        // if (!this.state.isUpload) {
        //     return false;
        // }
        // if (this.props.limitNum && fileList.length > this.props.limitNum) {
        //     message.warning(`上传文件限制${this.props.limitNum}个`);
        //     return false;
        // }
        console.log(fileList)
        this.setState({
            uploadFileList: fileList
        });
        if (file.status === 'done') {

            let fileObj: any = {
                fileOriginalName: file.name,
                fileUploadName: file.response.key,
            }
            this.setState({
                value: [...value, fileObj],
            }, () => {
                this.props.onChange(this.state.value);
            })
            // const { fileUrl = '/web/verifiedTask/getFileDownloadUrl' } = this.props;
            // const response = await agent.post(fileUrl, { fileNameList: [file.response.key] }, null);

            // const res = response.res[0];
            // const href = `${res}`;
            // const uid = file.uid;
            // const index = fileList.findIndex(item => item.uid === uid);
            // fileList[index].url = href;
            // this.list.push(fileList[index]);
            // this.setState({
            //     uploadFileList: this.list
            // });

        } else if (file.status === 'error') {
            message.error(`${info.file.name}上传失败`);
            // this.setState({
            //     uploadFileList: fileList
            // });
            return false;
        } else if (file.status === 'removed') {
            // this.setState({
            //     uploadFileList:  fileList
            // });
        } else if (file.status === 'uploading') {
            // this.setState({
            //     uploadFileList: fileList
            // });
        }

        //受控组件 必须执行以下代码
        // console.log(fileList);
        

    }
    onRemoveHandler = (file) => {
        // console.log(this.state.value,file);
        const targetName = file.response.key;
        const restFiles = this.state.uploadFileList.filter(item => item.response.key !== targetName);

        const restValue = this.state.value.filter(item => {
            return item.fileUploadName !== targetName;
        });

        this.list = restFiles;
        // if (restValue.length > 0) {
        this.setState({
            uploadFileList: restFiles,
            value: restValue
        }, () => {
            this.props.onChange(restValue);
        });
        // }
        return true;
    }
    normFile = e => {
        let fileList: any[] = [];
        if (Array.isArray(e)) {
            fileList = [...e];
        } else if (e && e.fileList) {
            fileList = [...e.fileList];
        }
        return fileList.filter((file) => {
            return file.status === 'done';
        });
    }
    onPreview = async (data) => {
        console.log(data);
        const { fileUrl = '/web/verifiedTask/getFileDownloadUrl' } = this.props;
        const response = await agent.post(fileUrl, { fileNameList: [data.response.key] }, this);
        const res = response.res[0];
        const href = `${res}`;
        let a = window.document.createElement('a');
        a.setAttribute('href', href);
        a.setAttribute('target', '_blank');
        a.click();
        // a = null;
    }
    render() {
        const propsUpload = {
            action: `${this.state.uploadUrl}`,
            beforeUpload: this.beforeUploadHandler,
            onChange: this.handleChange,
            onRemove: this.onRemoveHandler,
            data: { key: `${this.state.keyPrefix}`, token: this.state.token },
            multiple: true,
            onPreview:this.onPreview
        };
        return (
            <div style={{ flex: 1 }}>
                <Upload
                    {...propsUpload as any}
                    accept={this.props.accept}
                    fileList={this.state.uploadFileList}
                    showUploadList={this.props.showUploadList}
                    maxCount={this.props.limitNum}
                // itemRender={(originNode, file) => {
                //     return (
                //         <a onClick={() => { this.onPreview(file.response); }}>{originNode}</a>
                //     )
                // }}
                >
                    <div>
                        {
                            this.props.children
                        }
                    </div>
                </Upload>
            </div>
        );
    }
}
