import React, { Component } from 'react'
import { Checkbox, Form, Input, Radio, Spin } from 'antd'
import { AntIcon } from 'components'
import { cloneDeep, first, isEqual, last, sortBy } from 'lodash'
import getDictData from 'util/dic'

const initialValues = {
    patrolInfo: {
        houseSite: ['1'],
        adjacentConstruction: ['0'],
        chemicalErosion: ['0'],
        structuralDismantling: 0,
        addingLayer: 0,
        repairAndReinforce: ['0'],
        historicalCalamity: ['0'],
        functionalChange: ['0'],
    },
}

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

const checkboxKeys = [
    'houseSite',
    'adjacentConstruction',
    'chemicalErosion',
    'repairAndReinforce',
    'historicalCalamity',
    'functionalChange',
]

export default class investigation extends Component {
    state = {
        loading: true,
        codes: {
            houseHouseSite: [],
            houseAdjacentConstruction: [],
            houseChemicalErosion: [],
            houseStructuralDismantling: [],
            houseAddingLayer: [],
            houseRepairAndReinforce: [],
            houseHistoricalCalamity: [],
            houseFunctionalChange: [],
        },
        options: {},
    }

    // 表单实例
    form = 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
            // checkbox
            checkboxKeys.forEach(key => {
                if (patrolInfo[key]) {
                    patrolInfo[key] = patrolInfo[key].split(',')
                }
            })
        }
        const codes = await getDictData(
            'house_house_site',
            'house_adjacent_construction',
            'house_chemical_erosion',
            'house_structural_dismantling',
            'house_adding_layer',
            'house_repair_and_reinforce',
            'house_historical_calamity',
            'house_functional_change'
        )
        this.setState({ codes })
        //#endregion
        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
            // checkbox
            checkboxKeys.forEach(key => {
                if (patrolInfo[key]) {
                    patrolInfo[key] = sortBy(patrolInfo[key], p => +p).join(',')
                }
            })
            //#endregion
            return postData
        }
    }

    //#region 自定义方法
    /**
     * 表单change事件处理,包括了所有字段的change
     * [异步,非必要]
     * @param {*} changedValues
     * @param {*} allValues
     */
    async onValuesChange(changedValues, allValues) {
        const { patrolInfo } = changedValues
        const key = Object.keys(patrolInfo).shift()
        if (
            [
                'adjacentConstruction',
                'chemicalErosion',
                'repairAndReinforce',
                'historicalCalamity',
                'functionalChange',
            ].includes(key)
        ) {
            this.checkedNone(patrolInfo[key], key)
        }
    }

    checkedNone(value, key) {
        const form = this.form.current
        if (first(value) == 0 && value.length > 1) {
            // 在'无'之后选中其他值
            value.shift()
            form.setFieldsValue({
                patrolInfo: { [key]: value },
            })
        } else if (last(value) == 0 && value.length > 1) {
            // 在其他值之后选中'无'
            value = ['0']
            form.setFieldsValue({
                patrolInfo: { [key]: value },
            })
        }
        return value
    }
    //#endregion

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

        return (
            <Spin spinning={loading} indicator={<AntIcon type="loading" />}>
                <Form
                    initialValues={initialValues}
                    ref={this.form}
                    {...layout}
                    onValuesChange={(changedValues, allValues) =>
                        this.onValuesChange(changedValues, allValues)
                    }
                >
                    <Form.Item
                        label="房屋场地"
                        name={['patrolInfo', 'houseSite']}
                        rules={[{ required: true, message: '请选择房屋场地' }]}
                    >
                        <Checkbox.Group>
                            {codes.houseHouseSite.map(item => (
                                <Checkbox key={item.code} value={item.code}>
                                    {item.value}
                                </Checkbox>
                            ))}
                        </Checkbox.Group>
                    </Form.Item>
                    <Form.Item
                        label="相邻施工"
                        name={['patrolInfo', 'adjacentConstruction']}
                        rules={[{ required: true, message: '请选择相邻施工' }]}
                    >
                        <Checkbox.Group>
                            {codes.houseAdjacentConstruction.map(item => (
                                <Checkbox key={item.code} value={item.code}>
                                    {item.value}
                                </Checkbox>
                            ))}
                        </Checkbox.Group>
                    </Form.Item>
                    <Form.Item
                        label="化学侵蚀"
                        name={['patrolInfo', 'chemicalErosion']}
                        rules={[{ required: true, message: '请选择化学侵蚀' }]}
                    >
                        <Checkbox.Group>
                            {codes.houseChemicalErosion.map(item => (
                                <Checkbox key={item.code} value={item.code}>
                                    {item.value}
                                </Checkbox>
                            ))}
                        </Checkbox.Group>
                    </Form.Item>
                    <Form.Item
                        label="结构拆改"
                        name={['patrolInfo', 'structuralDismantling']}
                        rules={[{ required: true, message: '请选择结构拆改' }]}
                    >
                        <Radio.Group buttonStyle="solid">
                            {codes.houseStructuralDismantling.map(item => (
                                <Radio.Button key={item.code} value={+item.code}>
                                    {item.value}
                                </Radio.Button>
                            ))}
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="加层改造"
                        name={['patrolInfo', 'addingLayer']}
                        rules={[{ required: true, message: '请选择加层改造' }]}
                    >
                        <Radio.Group buttonStyle="solid">
                            {codes.houseAddingLayer.map(item => (
                                <Radio.Button key={item.code} value={+item.code}>
                                    {item.value}
                                </Radio.Button>
                            ))}
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="修缮加固"
                        name={['patrolInfo', 'repairAndReinforce']}
                        rules={[{ required: true, message: '请选择修缮加固' }]}
                    >
                        <Checkbox.Group>
                            {codes.houseRepairAndReinforce.map(item => (
                                <Checkbox key={item.code} value={item.code}>
                                    {item.value}
                                </Checkbox>
                            ))}
                        </Checkbox.Group>
                    </Form.Item>
                    <Form.Item
                        label="历史灾害"
                        name={['patrolInfo', 'historicalCalamity']}
                        rules={[{ required: true, message: '请选择历史灾害' }]}
                    >
                        <Checkbox.Group>
                            {codes.houseHistoricalCalamity.map(item => (
                                <Checkbox key={item.code} value={item.code}>
                                    {item.value}
                                </Checkbox>
                            ))}
                        </Checkbox.Group>
                    </Form.Item>
                    <Form.Item
                        label="使用功能变更"
                        name={['patrolInfo', 'functionalChange']}
                        rules={[{ required: true, message: '请选择使用功能变更' }]}
                    >
                        <Checkbox.Group>
                            {codes.houseFunctionalChange.map(item => (
                                <Checkbox key={item.code} value={item.code}>
                                    {item.value}
                                </Checkbox>
                            ))}
                        </Checkbox.Group>
                    </Form.Item>
                    <Form.Item label="其他调查内容" name={['patrolInfo', 'otherContents']}>
                        <Input.TextArea autoSize placeholder="请输入其他调查内容" />
                    </Form.Item>
                </Form>
            </Spin>
        )
    }
}
