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

const { getState, subscribe } = store
const storePath = 'user'
const initialValues = {
    sort: 100,
}
export default class form extends Component {
    state = {
        // 加载状态
        loading: true,
        exist: false,
        options: {
            orgData: [],
        },
        user: getState(storePath),
    }

    constructor(props) {
        super(props)

        this.unsubscribe = subscribe(storePath, () => {
            this.setState({
                user: getState(storePath),
            })
        })
    }
    // 表单实例
    form = React.createRef()

    // 初始化数据
    record = {}

    /**
     * mount后回调
     */
    componentDidMount() {
        this.props.created && this.props.created(this)
    }
    componentWillUnmount() {
        this.unsubscribe()
    }
    /**
     * 填充数据
     * 可以在设置this.record之后对其作出数据结构调整
     * [异步,必要]
     * @param {*} params
     */
    async fillData(params) {
        const { user } = this.state
        if (params.id) {
            this.setState({
                loading: true,
            })

            api.houseZoneGetById({ zoneId: params.id }).then(({ data }) => {
                this.record = data

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

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

        //街道角色新增，不管左侧树选中与否，默认值均为本街道
        if (user.adminType === 2) {
            user.roles.map(role => {
                if (role.code == 'road_manager') {
                    params.orgId = user.loginEmpInfo.orgId
                }
            })
        }

        this.record = {
            pid: params.orgId,
            ...this.record,
        }

        //#endregion
        if (!params.id && !!params.orgId) {
            this.onOrgIdChanged(params.orgId)
        }
        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 从前段转换后端所需格
            //#endregion
            return postData
        }
    }

    async loadOrgData() {
        const { data } = await api.getOrgTree({ type: 4 })
        return data
    }

    onOrgIdChanged(value) {
        this.loading = true

        api.houseZoneAutoIncrement({ roadId: value })
            .then(({ data }) => {
                this.form.current.setFieldsValue({
                    name: `片区${numberToChinese(data)}`,
                    sort: data,
                })
            })
            .catch(() => {
                this.form.current.setFieldsValue({
                    name: '',
                    sort: 0,
                })
            })
            .finally(() => {
                this.loading = false
            })
    }

    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="pid"
                            rules={[{ required: true, message: '请选择所属街道' }]}
                        >
                            <TreeSelect
                                treeData={this.state.options.orgData}
                                dropdownStyle={{ maxHeight: '300px', overflow: 'auto' }}
                                treeDefaultExpandAll
                                placeholder="请选择所属街道"
                                onChange={(value, label, extra) => this.onOrgIdChanged(value)}
                                disabled={this.state.exist}
                            />
                        </Form.Item>

                        <Form.Item
                            label="片区名称"
                            name="name"
                            rules={[{ required: true, message: '片区名称', trigger: 'blur' }]}
                        >
                            <Input autoComplete="off" placeholder="请输入机构名称" disabled />
                        </Form.Item>
                        <Form.Item label="排序" name="sort">
                            <InputNumber
                                max={1000}
                                min={0}
                                placeholder="请输入排序"
                                className="w-100-p"
                                disabled
                            />
                        </Form.Item>
                        <Form.Item label="备注" name="remark">
                            <Input.TextArea placeholder="请输入备注" />
                        </Form.Item>
                    </div>
                </Spin>
            </Form>
        )
    }
}
