import React, { Component } from 'react'
import { Form, Button, Input, Descriptions, message as Message, Modal, Spin, Tabs } from 'antd'
import { merge, isEqual, pickBy } from 'lodash'
import { AntIcon, ComponentDynamic, Container, Auth } from 'components'
import { api } from 'common/api'

const tabs = [
    {
        title: '房屋基本情况',
        component: () => import('./base'),
        active: true,
        show: true,
    },
    // {
    //     title: '幕墙信息',
    //     name: 'curtainWall',
    //     path: 'curtainWall',
    //     active: false,
    //     show: false,
    // },
    // {
    //     title: '面砖信息',
    //     name: 'faceBrick',
    //     path: 'faceBrick',
    //     active: false,
    //     show: false,
    // },
    // {
    //     title: '墙面粉刷信息',
    //     name: 'whiteWash',
    //     path: 'whiteWash',
    //     active: false,
    //     show: false,
    // },
    // {
    //     title: '墙面涂料信息',
    //     name: 'coating',
    //     path: 'coating',
    //     active: false,
    //     show: false,
    // },
    {
        title: '巡查登记',
        component: () => import('./patrol'),
        active: false,
        show: true,
    },
]
const actions = {
    save: {
        action: 'houseInfoSave',
        remark: '保存',
        after: 'reload',
    },
    submit: {
        action: 'houseInfoSubmitToCheck',
        remark: '提交',
        after: 'close',
    },
    check: {
        action: 'houseInfoCheck',
        remark: '审核',
        after: 'close',
    },
}

export default class index extends Component {
    state = {
        actived: '0',

        loading: true,
        record: null,

        saveDisabled: true,
        saving: false,
        taskStatus: 0,
    }

    children = []

    formData = {}
    checkForm = React.createRef()

    shouldComponentUpdate(props, state) {
        return !isEqual(this.state, state)
    }

    componentDidMount() {
        // 获取详细数据
        this.onLoadInitData()
    }

    call(child, index) {
        this.children[index] = child
        if (this.children.filter(p => p).length === tabs.filter(p => p.show).length) {
            this.setState({ saveDisabled: false })
        }
    }

    onLoadInitData() {
        this.setState({
            loading: true,
        })
        const { taskId } = this.props.param
        if (taskId) {
            api.houseInfoGetByTaskId({ taskId }).then(({ data }) => {
                // 删除空节点
                for (const key in data) {
                    data[key] = pickBy(data[key], p => p !== null && p !== undefined)
                }
                this.setState({
                    taskStatus: data.patrolInfo.status,
                    record: data,
                    loading: false,
                })
            })
        }
    }

    async onSave() {
        await this.onPostData(actions.save)
    }

    async onSubmit() {
        Modal.confirm({
            content: '确认提交审核吗？',
            onOk: () => {
                this.onPostData(actions.submit)
            },
            onCancel: () => {},
        })
    }

    async onCheck(pass_or_back) {
        const form = this.checkForm.current
        const valid = await form.validateFields()

        Modal.confirm({
            content: '审核结果即将提交，请确认',
            onOk: () => {
                if (valid) {
                    var checkRecord = {
                        taskCheckRecord: {
                            taskId: this.props.param.taskId,
                            passOrBack: +pass_or_back,
                            content: form.getFieldValue(['taskCheckRecord', 'content']),
                        },
                    }
                    this.onPostData(actions.check, checkRecord)
                }
            },
            onCancel: () => {},
        })
    }

    async onPostData(action, append) {
        for (const child of this.children) {
            try {
                const data = await child.getData()
                merge(this.formData, data)
            } catch (e) {
                return e
            }
        }

        //#region 提交数据

        if (append) {
            this.formData = {
                ...this.formData,
                ...append,
            }
        }
        if (this.formData.houseCode) {
            this.formData.houseCode.id = this.state.record.houseCode.id
        }

        if (this.formData.patrolInfo && this.props.param.taskId) {
            this.formData.patrolInfo.id = this.props.param.taskId
        }

        this.setState({ saving: true })

        if (action) {
            try {
                const { success } = await api[action.action](this.formData)
                if (success) {
                    Message.success(action.remark + '成功')
                    this.setState({ saving: false })
                    if (this.props.param.table.current) {
                        this.props.param.table.current.onReloadData()
                    }
                    switch (action.after) {
                        case 'close':
                            window.closeContentWindow()
                            break
                        default:
                            this.onLoadInitData()
                            break
                    }
                }
            } finally {
                this.setState({ saving: false })
            }
        }

        // setTimeout(() => {
        //     Message.success('提交成功')
        //     this.setState({ saving: false })
        // }, 3000)
        //#endregion
    }

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

        return (
            <div className="yo-form-page">
                <div className="yo-form-page-layout">
                    {/* 底部工具栏(需放在前面) */}
                    <div className="yo-form-page--bar yo-form-page--bar--with-tab">
                        <Container mode="fluid">
                            <div className="yo-form-page--bar-inner">
                                <span>
                                    <Auth auth={{ houseInfo: 'check' }}>
                                        {this.state.taskStatus == 3 && (
                                            <Form ref={this.checkForm} layout="inline">
                                                <Form.Item
                                                    label="审核意见"
                                                    name={['taskCheckRecord', 'content']}
                                                    rules={[
                                                        {
                                                            required: true,
                                                            message: '请输入审核意见',
                                                        },
                                                    ]}
                                                >
                                                    <Input.TextArea
                                                        autoSize
                                                        autoComplete="off"
                                                        placeholder="请输入审核意见"
                                                        className="w-500"
                                                    />
                                                </Form.Item>
                                                <Form.Item>
                                                    <Button
                                                        type="primary"
                                                        onClick={() => this.onCheck(6)}
                                                    >
                                                        通过
                                                    </Button>
                                                    <Button
                                                        type="danger"
                                                        onClick={() => this.onCheck(-1)}
                                                    >
                                                        退回
                                                    </Button>
                                                </Form.Item>
                                            </Form>
                                        )}
                                    </Auth>
                                </span>
                                <span>
                                    {this.state.taskStatus >= -1 && this.state.taskStatus < 3 && (
                                        <Button
                                            disabled={saveDisabled}
                                            loading={saving}
                                            type="primary"
                                            onClick={() => this.onSave()}
                                        >
                                            保存
                                        </Button>
                                    )}
                                    {this.state.taskStatus == 2 && (
                                        <Button type="primary" onClick={() => this.onSubmit()}>
                                            提交审核
                                        </Button>
                                    )}
                                    <Button onClick={() => window.closeContentWindow()}>
                                        取消
                                    </Button>
                                </span>
                            </div>
                        </Container>
                    </div>
                    <div className="yo-form-page--header" style={{ paddingBottom: 0 }}>
                        <Container mode="fluid">
                            <Spin spinning={loading} indicator={<AntIcon type="loading" />}>
                                <Descriptions column={4}>
                                    <Descriptions.Item label="区县（市）">
                                        {record && record.houseCode.areaName}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="街道（乡镇）">
                                        {record && record.houseCode.roadName}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="社区">
                                        {record && record.houseCode.commName}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="片区">
                                        {record && record.houseCode.zoneName}
                                    </Descriptions.Item>
                                    <Descriptions.Item span="2" label="编号">
                                        {record &&
                                            `${record.houseCode.areaName}-${
                                                record.houseCode.roadName
                                            }-${record.houseCode.commName}-${
                                                record.houseCode.fullProjName
                                            }-${record.houseCode.no.toString().padStart(3, '0')}`}
                                    </Descriptions.Item>
                                    <Descriptions.Item span="2" label="编码">
                                        {record && record.houseCode.houseCode}
                                    </Descriptions.Item>
                                </Descriptions>
                            </Spin>
                        </Container>
                    </div>
                    <div className="yo-tab-external-mount">
                        <Tabs
                            activeKey={this.state.actived}
                            animated={false}
                            onChange={activeKey => {
                                this.setState({ actived: activeKey })
                            }}
                        >
                            {tabs.map((tab, i) => {
                                if (tab.show) {
                                    return (
                                        <Tabs.TabPane
                                            key={i}
                                            forceRender={false}
                                            tab={tab.title}
                                        ></Tabs.TabPane>
                                    )
                                }
                                return <></>
                            })}
                        </Tabs>
                        <div className="yo-tab-external-mount-content">
                            {tabs.map((tab, i) => {
                                if (tab.show) {
                                    return (
                                        <div
                                            key={i}
                                            className={[
                                                this.state.actived === i.toString()
                                                    ? 'yo-tab-external-tabpane-active'
                                                    : 'yo-tab-external-tabpane-inactive',
                                                'yo-tab-external-tabpane',
                                            ].join(' ')}
                                        >
                                            <ComponentDynamic
                                                is={tab.component}
                                                id={this.props.id}
                                                record={record}
                                                loading={loading}
                                                onRef={child => this.call(child, i)}
                                            />
                                        </div>
                                    )
                                }
                                return <></>
                            })}
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}
