import React, { Component } from 'react'
import { Col, Form, Input, Row, Spin, Upload } from 'antd'
import { AntIcon, PhotoPreview } 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 imageUploads = [{ key: 'settlementTiltFiles' }, { key: 'otherInfoFiles' }]

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

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

    photoPreview = React.createRef()

    // 初始化数据
    record = {}

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

    /**
     * DOM加载完成钩子,绑定数据
     */
    componentDidMount() {
        this.fillData({
            record: this.props.record,
        })
    }

    /**
     * 加载完成,通知父级组件并传递自身
     */
    call() {
        const { onRef } = this.props
        if (onRef) onRef(this)
    }

    /**
     * 填充数据
     * 可以在设置this.record之后对其作出数据结构调整
     * [异步,必要]
     * @param {*} params
     */
    async fillData(params) {
        this.record = cloneDeep(params.record)
        //#region 从后端转换成前段所需格式
        if (this.record) {
            const { patrolInfo } = this.record
            const keys = imageUploads.map(p => p.key)
            for (const key of keys) {
                const fileValue = []
                const fileList =
                    !patrolInfo[key] || !patrolInfo[key].length ? [] : patrolInfo[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',
                        })
                    }
                }

                patrolInfo[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 { patrolInfo } = postData
            const keys = imageUploads.map(p => p.key)
            for (const key of keys) {
                patrolInfo[key] = patrolInfo[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 onFilePreview(file, key) {
        const fileList = this.form.current
            .getFieldValue(['patrolInfo', key])
            .filter(p => p.status === 'done')
        const items = []
        for (const _file of fileList) {
            const img = new Image()
            const src = _file.url || _file.thumbUrl
            img.src = src
            items.push({
                src,
                w: img.naturalWidth,
                h: img.naturalHeight,
            })
        }
        this.photoPreview.current.initPhotoSwipe(items, {
            index: fileList.indexOf(file),
        })
    }

    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)
                    }
                >
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="沉降倾斜情况" name={['patrolInfo', 'settlementTilt']}>
                                <Input.TextArea
                                    autoSize={{ minRows: 4.6 }}
                                    placeholder="请输入沉降倾斜情况"
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                name={['patrolInfo', 'settlementTiltFiles']}
                                valuePropName="fileList"
                                getValueFromEvent={e => {
                                    if (Array.isArray(e)) {
                                        return e
                                    }
                                    return e && e.fileList
                                }}
                            >
                                <Upload
                                    listType="picture-card"
                                    customRequest={e => this.onFileUpload(e)}
                                    showUploadList={{
                                        showRemoveIcon: true,
                                        showDownloadIcon: true,
                                    }}
                                    onPreview={file =>
                                        this.onFilePreview(file, 'settlementTiltFiles')
                                    }
                                    onDownload={file => this.onFileDownload(file)}
                                >
                                    <div>
                                        <AntIcon type="plus" />
                                        <div className="ant-upload-text">沉降倾斜照片</div>
                                    </div>
                                </Upload>
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="其他情况" name={['patrolInfo', 'otherInfo']}>
                                <Input.TextArea
                                    autoSize={{ minRows: 4.6 }}
                                    placeholder="请输入其他情况"
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                name={['patrolInfo', 'otherInfoFiles']}
                                valuePropName="fileList"
                                getValueFromEvent={e => {
                                    if (Array.isArray(e)) {
                                        return e
                                    }
                                    return e && e.fileList
                                }}
                            >
                                <Upload
                                    listType="picture-card"
                                    customRequest={e => this.onFileUpload(e)}
                                    showUploadList={{
                                        showRemoveIcon: true,
                                        showDownloadIcon: true,
                                    }}
                                    onPreview={file => this.onFilePreview(file, 'otherInfoFiles')}
                                    onDownload={file => this.onFileDownload(file)}
                                >
                                    <div>
                                        <AntIcon type="plus" />
                                        <div className="ant-upload-text">其他情况照片</div>
                                    </div>
                                </Upload>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Form.Item label="主要安全隐患综述" name={['patrolInfo', 'mainSafety']}>
                        <Input.TextArea
                            autoSize={{ minRows: 4.6 }}
                            placeholder="请输入主要安全隐患综述"
                        />
                    </Form.Item>
                </Form>

                <PhotoPreview ref={this.photoPreview} />
            </Spin>
        )
    }
}
