import React, { Component } from 'react'
import {
    Alert,
    Button,
    Card,
    Col,
    Divider,
    Form,
    Input,
    Modal,
    Row,
    Space,
    Spin,
    Upload,
} from 'antd'
import { AntIcon, Container } from 'components'
import { api } from 'common/api'
import moment from 'moment'
import { BlobToBase64, GetFileName, PreviewFile } from 'util/file'

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

export default class form extends Component {
    state = {
        loading: false,
        saving: false,
        code: '',
        date: '',
        record: {},
    }

    form = React.createRef()

    componentDidMount() {
        this.fillData()
    }

    async fillData() {
        this.setState({ loading: true })
        const { data, uploads } = this.props
        const record = data && (data.updateRecord || data.record)
        if (record) {
            const keys = uploads.map(p => p.key)
            for (const key of keys) {
                const fileValue = []
                const item = record[key]
                if (!Array.isArray(item)) {
                    const fileList = !item || !item.length ? [] : item.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',
                            })
                        }
                    }
                }

                record[key] = fileValue
            }

            this.form.current.setFieldsValue(record)

            this.setState({
                loading: false,
                code: data.code,
                date: moment(data.createdTime).format('YYYY年MM月DD日'),
                record,
            })
        } else {
            const { data: code } = await api.inspectionOrgNewCode()
            this.setState({
                loading: false,
                code,
                date: moment().format('YYYY年MM月DD日'),
            })
        }
    }

    async onFinish(values) {
        this.setState({ saving: true })
        const { uploads, action } = this.props
        try {
            for (const upload of uploads) {
                values[upload.key] = (values[upload.key] || [])
                    .map(item => (item.uid.startsWith('rc-upload') ? item.response : item.uid))
                    .join(',')
            }
            if (action === 'edit') {
                await api.inspectionOrgUpdate(values)
            } else {
                await api.inspectionOrgRegister(values)
            }

            // 提交成功时应该关闭当前页并且等待
            Modal.info({
                title: '提示',
                content: '备案已提交申请，请等待上级部门审核',
                onOk() {
                    window.closeContentWindow()
                },
            })
        } finally {
            this.setState({ saving: false })
        }
    }

    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()
    }

    render() {
        const { loading, saving, code, date, record } = this.state

        const { uploads, action } = this.props

        return (
            <Container mode="fluid">
                <br />
                <Form ref={this.form} {...layout} onFinish={values => this.onFinish(values)}>
                    {record.updateStatus === -1 && (
                        <>
                            <Alert
                                message="备案登记未通过"
                                description={record.remark}
                                type="error"
                                showIcon
                            />
                            <br />
                        </>
                    )}
                    <Card className="yo-form-page--body">
                        <section>
                            <h5>基本信息</h5>
                            <Spin spinning={loading} indicator={<AntIcon type="loading" />}>
                                <Row>
                                    <Col span={12}>
                                        <Form.Item label="机构备案编号">
                                            <span>{code}</span>
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item label="申请时间">
                                            <span>{date}</span>
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item
                                            label="社会统一信用代码"
                                            name="creditCode"
                                            rules={[
                                                {
                                                    required: true,
                                                    message: '请输入社会统一信用代码',
                                                },
                                            ]}
                                        >
                                            <Input
                                                autoComplete="off"
                                                placeholder="请输入社会统一信用代码"
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={12} />
                                    <Col span={12}>
                                        <Form.Item
                                            label="机构名称"
                                            name="name"
                                            rules={[{ required: true, message: '请输入机构名称' }]}
                                        >
                                            <Input
                                                autoComplete="off"
                                                placeholder="请输入机构名称"
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item
                                            label="地址"
                                            name="address"
                                            rules={[{ required: true, message: '请输入地址' }]}
                                        >
                                            <Input autoComplete="off" placeholder="请输入地址" />
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item
                                            label="联系人"
                                            name="contacts"
                                            rules={[{ required: true, message: '请输入联系人' }]}
                                        >
                                            <Input autoComplete="off" placeholder="请输入联系人" />
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item
                                            label="联系人手机号"
                                            name="contactsPhone"
                                            rules={[
                                                { required: true, message: '请输入联系人手机号' },
                                            ]}
                                        >
                                            <Input
                                                autoComplete="off"
                                                placeholder="请输入联系人手机号"
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item
                                            label="法人代表"
                                            name="legalPerson"
                                            rules={[{ required: true, message: '请输入法人代表' }]}
                                        >
                                            <Input
                                                autoComplete="off"
                                                placeholder="请输入法人代表"
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item label="固定电话" name="orgTelephone">
                                            <Input
                                                autoComplete="off"
                                                placeholder="请输入固定电话"
                                            />
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </Spin>
                        </section>
                        <section>
                            <h5>申请材料</h5>
                            <Spin spinning={loading} indicator={<AntIcon type="loading" />}>
                                <Space className="w-100-p" split={<Divider />} direction="vertical">
                                    {uploads.map((item, i) => (
                                        <div className="w-100-p" key={i}>
                                            <Form.Item
                                                labelCol={{ flex: '100%' }}
                                                labelAlign="left"
                                                colon={false}
                                                name={item.key}
                                                label={item.label}
                                                valuePropName="fileList"
                                                getValueFromEvent={e => {
                                                    if (Array.isArray(e)) {
                                                        return e
                                                    }
                                                    return e && e.fileList
                                                }}
                                                rules={[
                                                    {
                                                        required: item.required,
                                                        message: `请上传${item.label}`,
                                                    },
                                                ]}
                                            >
                                                <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" />}
                                                    >
                                                        添加材料
                                                    </Button>
                                                </Upload>
                                            </Form.Item>
                                        </div>
                                    ))}
                                </Space>
                            </Spin>
                        </section>
                        <div className="text-center">
                            <Button type="primary" htmlType="submit" loading={saving}>
                                {action === 'edit' ? '提交更改申请' : '提交备案申请'}
                            </Button>
                        </div>
                        <br />
                    </Card>
                </Form>
            </Container>
        )
    }
}
