import React, { Component } from 'react'
import {
    Button,
    Card,
    Col,
    Divider,
    Form,
    Input,
    message as Message,
    Modal,
    Row,
    Space,
    Spin,
    Tag,
    Typography,
    Upload,
} from 'antd'
import { AntIcon, Auth, Container } from 'components'
import { api } from 'common/api'
import { BlobToBase64, GetFileName, PreviewFile } from 'util/file'
import { isEqual } from 'lodash'

export default class detail extends Component {
    state = {
        loading: false,
        saving: false,
        record: {},
        updateRecord: {},
    }

    form = React.createRef()

    componentDidMount() {
        this.fillData()
    }

    async fillData() {
        this.setState({ loading: true })
        const { data, uploads, action } = this.props
        const keys = uploads.map(p => p.key)
        let record = {},
            updateRecord = {}
        if (action === 'review') {
            record = data.updateRecord
        } else if (action === 'updateReview') {
            record = data.record
            updateRecord = data.updateRecord
        } else {
            record = data.record || data.updateRecord
        }

        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

            const updateFileValue = []
            const updateItem = updateRecord[key]
            if (!Array.isArray(updateItem)) {
                const fileList = !updateItem || !updateItem.length ? [] : updateItem.split(',')
                for (const fileId of fileList) {
                    try {
                        const file = await PreviewFile(fileId)
                        const base64 = await BlobToBase64(file)
                        updateFileValue.push({
                            uid: fileId,
                            response: fileId,
                            name: file.name,
                            url: base64,
                            status: 'done',
                        })
                    } catch {
                        const { data: file } = await api.sysFileInfoDetail({ id: fileId })
                        updateFileValue.push({
                            uid: fileId,
                            response: '文件已丢失',
                            name: file.fileOriginName,
                            status: 'error',
                        })
                    }
                }
            }

            updateRecord[key] = updateFileValue
        }

        this.setState({
            loading: false,
            record,
            updateRecord,
        })
    }

    onFinish(approved = false) {
        const remark = this.form.current.getFieldValue('remark')
        if (!approved && !remark) {
            Message.error('请输入退回理由')
            return
        }

        Modal.confirm({
            title: '提示',
            content: '是否确定' + ['退回', '审核通过'][+approved],
            onOk: async () => {
                this.setState({ saving: true })
                try {
                    const { id } = this.props.data
                    if (approved) {
                        await api.inspectionOrgReviewApproved({ id })
                    } else {
                        await api.inspectionOrgReviewNotApproved({ id, remark })
                    }

                    // 提交成功时应该关闭当前页并且等待
                    Modal.info({
                        title: '提示',
                        content: '审核已完成',
                        onOk: () => {
                            if (this.props.list) {
                                this.props.list.current.onReloadData()
                            }
                            window.closeContentWindow()
                        },
                    })
                } finally {
                    this.setState({ saving: false })
                }
            },
        })
    }

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

    compareTo(scoure, target, type) {
        if (type === 'file') {
            const s = scoure.map(p => p.uid),
                t = target.map(p => p.uid)

            return isEqual(s.sort(), t.sort())
        } else {
            return scoure === target
        }
    }

    renderDetail(record, compare) {
        const { loading } = this.state

        const { uploads } = this.props

        return (
            <>
                <Card>详细信息</Card>
                <Card className="yo-form-page--body">
                    <section>
                        <h5>申请材料</h5>
                        <Spin spinning={loading} indicator={<AntIcon type="loading" />}>
                            <Space className="w-100-p" split={<Divider />} direction="vertical">
                                {uploads.map((item, i) => {
                                    let fileList = []
                                    if (
                                        record &&
                                        record[item.key] &&
                                        Array.isArray(record[item.key])
                                    ) {
                                        fileList = record[item.key]
                                    }

                                    let compareResult = true
                                    if (compare) {
                                        compareResult = this.compareTo(
                                            fileList,
                                            compare[item.key] || [],
                                            'file'
                                        )
                                    }

                                    return (
                                        <div className="w-100-p" key={i}>
                                            <Row>
                                                <Col flex="1">
                                                    <Typography.Text>{item.label}</Typography.Text>
                                                    <Upload
                                                        showUploadList={{
                                                            showRemoveIcon: false,
                                                            showDownloadIcon: true,
                                                        }}
                                                        onPreview={() => false}
                                                        onDownload={file =>
                                                            this.onFileDownload(file)
                                                        }
                                                        fileList={fileList}
                                                    />
                                                </Col>
                                                {compare && !loading && (
                                                    <Col flex="60px">
                                                        {compareResult ? (
                                                            <Tag color="green">未修改</Tag>
                                                        ) : (
                                                            <Tag color="orange">已修改</Tag>
                                                        )}
                                                    </Col>
                                                )}
                                            </Row>
                                        </div>
                                    )
                                })}
                            </Space>
                        </Spin>
                    </section>
                </Card>
            </>
        )
    }

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

        const { uploads, action } = this.props

        return (
            <Container mode="fluid">
                <br />
                <Row gutter={16}>
                    {action === 'updateReview' ? (
                        <>
                            <Col span={12}>
                                <Typography.Title level={5}>修改前</Typography.Title>
                                {this.renderDetail(record)}
                            </Col>
                            <Col span={12}>
                                <Typography.Title level={5}>修改后</Typography.Title>
                                {this.renderDetail(updateRecord, record)}
                            </Col>
                        </>
                    ) : (
                        <Col span={24}>{this.renderDetail(record)}</Col>
                    )}
                </Row>
                <Card>历史记录</Card>
                <Auth auth={{ inspectionOrg: ['reviewApproved', 'reviewNotApproved'] }}>
                    {['review', 'updateReview'].includes(action) && (
                        <Form ref={this.form}>
                            <Card className="yo-form-page--body">
                                <section>
                                    <h5>退回理由</h5>
                                    <Form.Item name="remark">
                                        <Input.TextArea
                                            autoComplete="off"
                                            placeholder="请输入退回理由"
                                            rows={5}
                                        />
                                    </Form.Item>
                                    <div className="text-center">
                                        <Space>
                                            <Button
                                                type="danger"
                                                loading={saving}
                                                onClick={() => this.onFinish(false)}
                                            >
                                                退回
                                            </Button>
                                            <Button
                                                type="primary"
                                                loading={saving}
                                                onClick={() => this.onFinish(true)}
                                            >
                                                审核通过
                                            </Button>
                                        </Space>
                                    </div>
                                </section>
                            </Card>
                        </Form>
                    )}
                </Auth>
            </Container>
        )
    }
}
