import React, { Component } from 'react'
import { cloneDeep } from 'lodash'
import { AntIcon, AuthorityView } from 'components'
import { api } from 'common/api'
import { Empty, Spin } from 'antd'

export default class form extends Component {

    state = {
        // 加载状态
        loading: true,
        defaultSelectedKeys: []
    }

    selectedKeys = []

    view = 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 { data } = await api.sysRoleOwnMenu({ id: this.record.id })
        this.setState({
            defaultSelectedKeys: data
        })
        this.view.current.onLoadData()
        //#endregion

        this.setState({
            loading: false
        })
    }

    /**
     * 获取数据
     * 可以对postData进行数据结构调整
     * [异步,必要]
     * @returns 
     */
    async getData() {
        const postData = {}
        if (this.record) {
            postData.id = this.record.id
        }
        //#region 从前段转换后端所需格式
        postData.grantMenuIdList = this.selectedKeys
        //#endregion
        return postData
    }

    //#region 自定义方法
    async loadData() {
        const { data } = await api.SysMenuTreeForGrant()
        return data
    }
    //#endregion

    render() {
        return (
            <Spin spinning={this.state.loading} indicator={<AntIcon type="loading" />}>
                <AuthorityView
                    autoLoad={false}
                    loadData={this.loadData}
                    defaultSelectedKeys={this.state.defaultSelectedKeys}
                    onSelect={(s1, s2, s3) => this.selectedKeys = s3}
                    ref={this.view}
                />
                { this.state.loading && <Empty className="pt-lg pb-lg" />}
            </Spin>
        )
    }
}
