import React, { Component } from 'react'
import { Cascader, Form, Input, InputNumber, Select, Spin, TreeSelect } from 'antd'
import { AntIcon } from 'components'
import { cloneDeep } from 'lodash'
import getDictData from 'util/dic'
import { EMPTY_ID } from 'util/global'
import { api } from 'common/api'

const initialValues = {
    sort: 100
}

export default class form extends Component {

    state = {
        // 加载状态
        loading: true,

        codes: {
            orgType: []
        },

        options: {
            orgData: [],
            areaData: []
        }
    }

    // 表单实例
    form = React.createRef()

    // 初始化数据
    record = {}

    /**
     * mount后回调
     */
    componentDidMount() {
        this.props.created && this.props.created(this)
    }

    /**
     * 填充数据
     * 可以在设置this.record之后对其作出数据结构调整
     * [异步,必要]
     * @param {*} params 
     */
    async fillData(params) {

        this.record = cloneDeep(params.record)
        //#region 从后端转换成前段所需格式
        const orgData = await this.loadOrgData()
        const areaData = await this.loadAreaData()

        const codes = await getDictData('org_type')
        this.setState({
            codes,
            options: {
                orgData,
                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 === params.record.areaCode) {
                    areaCode.length = level + 1;
                    return true;
                }

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

        if (params.record && params.record.areaCode) {
            findCode(areaData);
        }

        this.record = {
            pid: params.orgId,
            ...this.record,
            areaCode
        }
        this.record.areaCode = 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
        }
    }

    //#region 自定义方法
    async loadOrgData() {
        const { data } = await api.getOrgTree()
        return [{
            id: EMPTY_ID,
            parentId: undefined,
            title: '顶级',
            value: EMPTY_ID,
            pid: undefined,
            children: data,
        }]
    }

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

    onAreaCodeChange(selectedOptions) {
        const data = selectedOptions[selectedOptions.length - 1]
        this.form.current.setFieldsValue({
            name: data.name,
            code: data.code
        })
    }
    //#endregion

    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="areaCode" rules={[{ required: true, message: '请选择所属区域' }]}>
                            <Cascader
                                options={this.state.options.areaData}
                                fieldNames={{
                                    label: 'name',
                                    value: 'code',
                                    children: 'children'
                                }}
                                changeOnSelect
                                placeholder="请选择所属区域"
                                onChange={(val, selectedOptions) => this.onAreaCodeChange(selectedOptions)}
                            />
                        </Form.Item>
                        <Form.Item label="机构名称" name="name" rules={[{ required: true, message: '请输入机构名称', trigger: 'blur' }]}>
                            <Input autoComplete="off" placeholder="请输入机构名称" />
                        </Form.Item>
                        <Form.Item label="唯一编码" name="code" rules={[{ required: true, message: '请输入唯一编码', trigger: 'blur' }]}>
                            <Input autoComplete="off" placeholder="请输入唯一编码" />
                        </Form.Item>
                        <Form.Item label="机构类型" name="type" rules={[{ required: true, message: '请选择机构类型' }]}>
                            <Select placeholder="请选择机构类型">
                                {
                                    this.state.codes.orgType.map(item => {
                                        return <Select.Option
                                            key={item.code}
                                            value={+item.code}
                                        >{item.value}</Select.Option>
                                    })
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item label="上级机构" name="pid" rules={[{ required: true, message: '请选择上级机构' }]}>
                            <TreeSelect
                                treeData={this.state.options.orgData}
                                dropdownStyle={{ maxHeight: '300px', overflow: 'auto' }}
                                treeDefaultExpandAll
                                placeholder="请选择上级机构"
                            />
                        </Form.Item>
                        <Form.Item label="排序" name="sort">
                            <InputNumber
                                max={1000}
                                min={0}
                                placeholder="请输入排序"
                                className="w-100-p"
                            />
                        </Form.Item>
                        <Form.Item label="备注" name="remark">
                            <Input.TextArea placeholder="请输入备注" />
                        </Form.Item>
                    </div>
                </Spin>
            </Form>
        )
    }
}
