import React from 'react';
import { connect } from 'dva';
import { message, Upload, Button, Icon, Modal } from 'antd';
import {
    initFilter, getOnlyPropertyData, getDataFieldValue, empty, extendRule, extendInclude, initFilterGroup, extendGroupRule, extendFilterGroup, guid, getParseValue
} from "../../utils/common";
import config from "../../config";
import debounce from 'lodash/debounce';
import storage from '../../utils/storage'
import { serializeRequestParams } from '../../utils/request'
import { isEqual } from 'lodash'
let reload = true;
const removeFiles = [];
class Attachment extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            updateLoadFileList: [],
            removeFileList: [],
            record: this.props.record,
            previewVisible: false,
            previewImage: '',
        }
    }

    componentDidMount() {
        this.getValue()

    }
    static getDerivedStateFromProps(nextprops, preprops) {
        if (!isEqual(nextprops.record, preprops.record)) {
            return {
                record: nextprops.record
            }
        }
        return null
    }
    componentDidUpdate(prevProps, prevState) {
        // const navShowFieldArray = this.props.colConfig.field.split('.');
        // const saveField = navShowFieldArray[0];
        if (reload && (prevState.record?.ID !== this.props.record?.ID
            || !isEqual(prevState.record[this.props.colConfig.field], this.props.record[this.props.colConfig.field]))) {
            this.getValue()
        }
    }
    handleCancel = () => {
        this.setState({ previewVisible: false });
        return false;
    }
    getValue = () => {
        const record = this.props.record;
        let updateLoadFileList = [];
        if (record) {
            const navShowFieldArray = this.props.colConfig.field.split('.');
            if (navShowFieldArray != null && navShowFieldArray.length > 1) {
                var saveFieldData = record[navShowFieldArray[0]]
                for (var x = 1; x < navShowFieldArray.length - 1; x++) {
                    saveFieldData = saveFieldData[navShowFieldArray[x]]
                }
                saveFieldData && saveFieldData[navShowFieldArray[navShowFieldArray.length - 1]].map(item => {
                    if (item.IS_DELETED)
                        return;
                    updateLoadFileList.push({
                        ID: item.ID,
                        IMG_FILE_ID: item.IMG_FILE_ID,
                        uid: item.ID,
                        name: item.name ? item.name : (item.Nav_ImgFile ? item.Nav_ImgFile.FILE_NAME : '未知文件'),
                        status: item.status ? item.status : 'done',
                        response: { Data: { imgFileID: item.IMG_FILE_ID }, file: item },
                        url: item.Nav_ImgFile ? (config.picServerHost + item.Nav_ImgFile.Nav_File.FILE_PATH) : '',
                        thumbUrl: item.Nav_ImgFile ? (config.picServerHost + item.Nav_ImgFile.Nav_File.FILE_PATH) : '',
                    });
                })
            } else {
                var saveField = navShowFieldArray[0];
                record[saveField] && record[saveField].map(item => {
                    if (item.IS_DELETED)
                        return;
                    updateLoadFileList.push({
                        ID: item.ID,
                        IMG_FILE_ID: item.IMG_FILE_ID,
                        uid: item.ID,
                        name: item.name ? item.name : (item.Nav_ImgFile ? item.Nav_ImgFile.FILE_NAME : '未知文件'),
                        status: item.status ? item.status : 'done',
                        response: { Data: { imgFileID: item.IMG_FILE_ID }, file: item },
                        url: item.Nav_ImgFile ? (config.picServerHost + item.Nav_ImgFile.Nav_File.FILE_PATH) : '',
                        thumbUrl: item.Nav_ImgFile ? (config.picServerHost + item.Nav_ImgFile.Nav_File.FILE_PATH) : '',
                    });
                })
            }

        }
        this.setState({ updateLoadFileList: updateLoadFileList })
    }

    handleChange = (uid, url) => {
        const record = this.props.record;
        const { updateLoadFileList } = this.state
        const { INPUT_ID_FIELD } = this.props.colConfig.column;
        if (uid) {
            updateLoadFileList.forEach(element => {
                if (element.uid == uid) {
                    element["url"] = config.picServerHost + url;
                }
            });
        }
        if (typeof this.props.onChange === 'function') {
            {
                reload = false;
                let re = updateLoadFileList.filter(it => it.status == 'done').map(it => {
                    var retJson = {
                        ID: it.ID || guid(),
                        IMG_FILE_ID: it.response?.Data?.imgFileID,
                        ORG_ID: this.props.login.OrgId,
                    }
                    if (INPUT_ID_FIELD) {
                        retJson[INPUT_ID_FIELD] = record.ID
                    }
                    return retJson;
                })
                removeFiles.forEach(it => {
                    var removeJson = {
                        ID: it.ID || guid(),
                        IMG_FILE_ID: it.response?.Data?.imgFileID,
                        ORG_ID: this.props.login.OrgId,
                    }
                    if (INPUT_ID_FIELD) {
                        removeJson[INPUT_ID_FIELD] = record.ID
                    }
                    removeJson.IS_DELETED = true;
                    re.push(removeJson);
                });
                this.props.onChange({ value: re });
            }
        }
        this.setState({
            updateLoadFileList: updateLoadFileList
        }, () => { reload = true; })
    };
    removeFileHandle = (file) => {
        removeFiles.push(file);
    };
    render() {
        const Tenant = storage('lacal').getItem('Tenant').val
        const props = {
            name: 'file',
            disabled: this.props.colConfig.disabled,
            action: config.serviceHost('api/PF/File/UploadFile'),
            data: { OrgId: this.props.login.OrgId },
            fileList: this.state.updateLoadFileList,
            listType: 'picture',
            headers: {
                Tenant: Tenant,
            },
            // onPreview: (file) => {
            //     if (file.type === "image/jpeg" || file.type === "image/png") {
            //         this.setState({
            //             previewImage: file.thumbUrl,
            //             previewVisible: true,
            //         });
            //     }
            //     return false;
            // },
            // onPreview: (file) =>{
            //     var urls = config.serviceHost + 'PF/File/GetFile?id=' + file.response.Data;
            //     fetch(urls).then(res => res.blob()).then(blob => {
            //         const a = document.createElement('a');
            //         document.body.appendChild(a)
            //         a.style.display = 'none'
            //         const url = window.URL.createObjectURL(blob);
            //         a.href = url;
            //         a.download = file.name;
            //         a.click();
            //         document.body.removeChild(a)
            //         window.URL.revokeObjectURL(url);
            //     }, () => {

            //     });
            // },
            onRemove: (file) => {
                this.removeFileHandle(file);
                return !this.props.colConfig.disabled;
            },
            onChange: (info) => {
                this.setState({
                    updateLoadFileList: info.fileList,
                });
                if (info.file.status === 'done') {
                    message.success(`${info.file.name} 上传成功`);
                    this.handleChange(info.file.uid, info.file.response.Data.imgFilePath)
                } else if (info.file.status === 'removed') {
                    this.handleChange()
                } else if (info.file.status === 'error') {
                    message.error(`${info.file.name} 上传失败`);
                }
            },
        };
        return <div className="clearfix">
            <Upload {...props}>
                <Button disabled={this.props.colConfig.disabled}>
                    <Icon type="upload" /> {this.props.colConfig.promptInfo || '上传附件'}
                </Button>
                {/* <Modal visible={this.state.previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="预览" style={{ width: '100%' }} src={this.state.previewImage} />
                </Modal> */}
            </Upload>
        </div>
    }

}
export default connect(({ login, loading, custom, app }) => ({ login, loading, custom, app }))(Attachment);
