import React, { Component } from 'react'
import { Cascader, Form, Input, InputNumber, Radio, Spin, TreeSelect } from 'antd'
import { AntIcon } from 'components'
import { cloneDeep } from 'lodash'
import { api } from 'common/api'
import { numberToChinese } from 'util/format'

const initialValues = {
    sort: 100,
    type: 1,
}
export default class form extends Component {
    state = {
        // 加载状态
        loading: true,
        exist: false,

        options: {
            areaData: [],
        },
    }
    areaCode = ''
    houseType = 1
    // 表单实例
    form = React.createRef()

    // 初始化数据
    record = {}
    initRecord = {}
    /**
     * mount后回调
     */
    componentDidMount() {
        this.props.created && this.props.created(this)
    }

    /**
     * 填充数据
     * 可以在设置this.record之后对其作出数据结构调整
     * [异步,必要]
     * @param {*} params
     */
    async fillData(params) {
        let areaCodeDefault = params.pid ? params.pid : ''
        this.houseType = params.record ? params.record.type : 1
        if (params.id) {
            this.setState({
                loading: true,
            })

            api.houseProjectGetById({ projectId: params.id }).then(({ data }) => {
                areaCodeDefault = data.areaCode
                this.record = data

                this.setState({
                    loading: false,
                })
            })
        }
        // this.record = cloneDeep(params.record)
        this.initRecord = cloneDeep(params.record)
        //#region 从后端转换成前段所需格式
        const areaData = await this.loadAreaData()

        this.setState({
            exist: !!params.id,
            options: { areaData },
        })

        const areaCode = []
        const findCode = (data, level) => {
            level = level || 0
            for (let i = 0; i < data.length; i++) {
                const item = data[i]
                areaCode[level] = item.code

                if (item.code === areaCodeDefault) {
                    areaCode.length = level + 1
                    return true
                }

                if (item.children && item.children.length) {
                    const found = findCode(item.children, level + 1)
                    if (found) {
                        return true
                    }
                }
            }
        }

        if (areaCodeDefault) {
            findCode(areaData)
            this.areaCode = areaCodeDefault
            if (!this.state.exist) {
                this.nextSort(this.areaCode, this.houseType)
            }
        }

        this.record = {
            pid: params.pid,
            ...this.record,
            areaCode:
                areaCode.length > 0 && areaCode[areaCode.length - 1].length == 12 ? areaCode : [],
        }
        //#endregion

        this.form.current.setFieldsValue(this.record)

        this.setState({
            loading: false,
        })
    }
    /**
     * 获取数据
     * 可以对postData进行数据结构调整
     * [异步,必要]
     * @returns
     */
    async getData() {
        const form = this.form.current

        const valid = await form.validateFields()
        if (valid) {
            const postData = form.getFieldsValue()
            if (this.record) {
                postData.id = this.record.id
            }
            //#region 从前段转换后端所需格式
            postData.areaCode = postData.areaCode[postData.areaCode.length - 1]
            //#endregion
            return postData
        }
    }

    async loadAreaData() {
        const { data } = await api.getAreaTree()
        console.log(data)
        const clearChiildren = data => {
            data.forEach(item => {
                if (item.children && item.children.length) {
                    clearChiildren(item.children)
                } else {
                    delete item.children
                }
            })
        }
        clearChiildren(data)
        return data
    }

    async nextSort(areaCode, houseType) {
        this.loading = true
        if (
            !!this.initRecord &&
            this.initRecord.areaCode == areaCode &&
            this.initRecord.type == houseType
        ) {
            this.form.current.setFieldsValue({
                name: this.initRecord.name,
                sort: this.initRecord.sort,
            })
        } else if (areaCode.length < 12) {
            this.form.current.setFieldsValue({
                name: '',
                sort: 0,
                areaCode: [],
            })
        } else {
            await api
                .houseProjectNextSort({ areaCode, type: houseType })
                .then(({ data }) => {
                    this.form.current.setFieldsValue({
                        name: `项目${numberToChinese(data)}`,
                        sort: data,
                    })
                })
                .catch(() => {
                    this.form.current.setFieldsValue({
                        name: '',
                        sort: 0,
                        areaCode: [],
                    })
                })
                .finally(() => {
                    this.loading = false
                })
        }
    }

    onHouseTypeChange(e) {
        this.houseType = e.target.value
        if (this.areaCode != '') {
            this.nextSort(this.areaCode, this.houseType)
        }
    }

    onAreaCodeChange(value) {
        this.areaCode = value[value.length - 1]
        if (this.houseType > 0) {
            this.nextSort(this.areaCode, this.houseType)
        }
    }

    render() {
        return (
            <Form initialValues={initialValues} ref={this.form} className="yo-form">
                <Spin spinning={this.state.loading} indicator={<AntIcon type="loading" />}>
                    <div className="yo-form-group">
                        <Form.Item label="类型" name="type">
                            <Radio.Group
                                disabled={this.state.exist}
                                buttonStyle="solid"
                                onChange={e => this.onHouseTypeChange(e)}
                            >
                                <Radio.Button value={1}>
                                    <span>住宅</span>
                                </Radio.Button>
                                <Radio.Button value={2}>
                                    <span>非住宅</span>
                                </Radio.Button>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item
                            label="所属区域"
                            name="areaCode"
                            rules={[{ required: true, message: '请选择所属区域' }]}
                        >
                            <Cascader
                                disabled={this.state.exist}
                                options={this.state.options.areaData}
                                fieldNames={{
                                    label: 'name',
                                    value: 'code',
                                    children: 'children',
                                }}
                                expandTrigger="hover"
                                // changeOnSelect
                                placeholder="请选择所属区域"
                                onChange={(val, selectedOptions) => this.onAreaCodeChange(val)}
                            />
                        </Form.Item>
                        <Form.Item
                            label="项目名称"
                            name="name"
                            rules={[{ required: true, message: '片区名称', trigger: 'blur' }]}
                        >
                            <Input
                                autoComplete="off"
                                placeholder="选择所属区域和类型之后自动生成"
                                disabled={true}
                            />
                        </Form.Item>
                        <Form.Item label="序号" name="sort">
                            <InputNumber
                                max={1000}
                                min={0}
                                placeholder="选择所属区域和类型之后自动生成"
                                className="w-100-p"
                                disabled={true}
                            />
                        </Form.Item>
                        <Form.Item label="备注" name="note">
                            <Input.TextArea
                                rows="4"
                                placeholder="填写房屋所属单位的名称、道路的名称或大厦的名称，比如XX中学、XX大厦、XX小区等。登记项目时，应在项目备注中明确项目所指对象。"
                            />
                        </Form.Item>
                    </div>
                </Spin>
            </Form>
        )
    }
}
