import React, { Component } from 'react'
import { Button, Form, Spin, Upload } from 'antd'
import { AntIcon } from 'components'
import { cloneDeep, isEqual } from 'lodash'
import { BlobToBase64, GetFileName, PreviewFile } from 'util/file'
import { api } from 'common/api'

const initialValues = {}

const layout = {
    labelCol: { flex: '150px' },
    wrapperCol: { flex: '1' },
}

const uploads = [
    {
        key: 'anEntryDocument',
        label: '立项文件',
    },
    {
        key: 'planningPermission',
        label: '规划许可',
    },
    {
        key: 'completionRecord',
        label: '竣工验收备案',
    },
    {
        key: 'monitorDocument',
        label: '监理文件',
    },
    {
        key: 'identificationReport',
        label: '鉴定报告',
    },
    {
        key: 'otherDocument',
        label: '其他附件',
    },
]

export default class attachments extends Component {
    state = {
        loading: true,
        codes: {},
        options: {},
    }

    // 表单实例
    form = React.createRef()

    // 初始化数据
    record = {}

    /**
     * 阻止外部组件引发的渲染,提升性能
     * 可自行添加渲染条件
     * [必要]
     * @param {*} props
     * @param {*} state
     * @returns
     */
    shouldComponentUpdate(props, state) {
        return !isEqual(this.state, state)
    }

    /**
     * 绑定数据
     */
    componentDidMount() {
        this.fillData({
            record: this.props.record,
        })
    }

    /**
     * DOM加载完成钩子,在此将自身传递给父级
     */
    call() {
        if (this.props.onRef) {
            this.props.onRef(this)
        }
    }

    /**
     * 填充数据
     * 可以在设置this.record之后对其作出数据结构调整
     * [异步,必要]
     * @param {*} params
     */
    async fillData(params) {
        this.record = cloneDeep(params.record)
        //#region 从后端转换成前段所需格式
        if (this.record) {
            const { houseInfo } = this.record
            const keys = uploads.map(p => p.key)
            for (const key of keys) {
                const fileValue = []
                const fileList =
                    !houseInfo[key] || !houseInfo[key].length ? [] : houseInfo[key].split(',')
                for (const fileId of fileList) {
                    try {
                        const file = await PreviewFile(fileId)
                        const base64 = await BlobToBase64(file)
                        fileValue.push({
                            uid: fileId,
                            response: fileId,
                            name: file.name,
                            url: base64,
                            status: 'done',
                        })
                    } catch {
                        const { data: file } = await api.sysFileInfoDetail({ id: fileId })
                        fileValue.push({
                            uid: fileId,
                            response: '文件已丢失',
                            name: file.fileOriginName,
                            status: 'error',
                        })
                    }
                }

                houseInfo[key] = fileValue
            }
        }
        //#endregion
        this.form.current && this.form.current.setFieldsValue(this.record)

        this.setState({ loading: false })
        this.call()
    }

    /**
     * 获取数据
     * 可以对postData进行数据结构调整
     * [异步,必要]
     * @returns
     */
    async getData() {
        const form = this.form.current

        const valid = await form.validateFields()
        if (valid) {
            const postData = form.getFieldsValue()
            //#region 从前段转换后端所需格式
            const { houseInfo } = postData
            for (const key in houseInfo) {
                houseInfo[key] = houseInfo[key]
                    .map(item => (item.uid.startsWith('rc-upload') ? item.response : item.uid))
                    .join(',')
            }
            //#endregion
            return postData
        }
    }

    //#region 自定义方法
    /**
     * 表单change事件处理,包括了所有字段的change
     * [异步,非必要]
     * @param {*} changedValues
     * @param {*} allValues
     */
    async onValuesChange(changedValues, allValues) {}

    async onFileUpload({ file, onProgress, onSuccess, onError }) {
        onProgress({
            percent: 0,
        })
        const fd = new FormData()
        fd.append('file', file)
        try {
            const { data: fileId } = await api.sysFileInfoUpload(fd)
            onSuccess(fileId)
        } catch {
            onError()
        }
    }

    async onFileDownload(file) {
        const { data, headers } = await api.sysFileInfoDownload({ id: file.response })
        const url = window.URL.createObjectURL(data)
        const fileName = GetFileName(headers['content-disposition'])
        const a = document.createElement('a')
        a.href = url
        a.download = fileName
        a.click()
        window.URL.revokeObjectURL(url)
        a.remove()
    }
    //#endregion

    render() {
        const { loading } = this.state

        return (
            <Spin spinning={loading} indicator={<AntIcon type="loading" />}>
                <Form
                    initialValues={initialValues}
                    ref={this.form}
                    {...layout}
                    onValuesChange={(changedValues, allValues) =>
                        this.onValuesChange(changedValues, allValues)
                    }
                >
                    {uploads.map((item, i) => (
                        <Form.Item
                            key={i}
                            label={item.label}
                            name={['houseInfo', item.key]}
                            valuePropName="fileList"
                            getValueFromEvent={e => {
                                if (Array.isArray(e)) {
                                    return e
                                }
                                return e && e.fileList
                            }}
                        >
                            <Upload
                                customRequest={e => this.onFileUpload(e)}
                                showUploadList={{
                                    showRemoveIcon: true,
                                    showDownloadIcon: true,
                                }}
                                onPreview={() => false}
                                onDownload={file => this.onFileDownload(file)}
                            >
                                <Button type="dashed" icon={<AntIcon type="upload" />}>
                                    上传{item.label}
                                </Button>
                            </Upload>
                        </Form.Item>
                    ))}
                </Form>
            </Spin>
        )
    }
}
