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

export default class role extends Component {
    state = {
        // 加载状态
        loading: true,

        options: {
            roleData: [],
        },
        roles: [],
    }

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

    // 初始化数据
    id = ''

    /**
     * mount后回调
     */
    componentDidMount() {
        this.props.created && this.props.created(this)
    }
    async fillData(params) {
        this.id = params.id
        //#region 从后端转换成前段所需格式
        const roleData = await this.loadRoleData()
        const roles = await this.loadRole(this.id)
        this.setState({
            options: {
                roleData,
            },
            roles,
        })
        this.form.current.setFieldsValue({
            id: this.id,
            grantRoleIdList: roles,
        })

        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.id) {
                postData.id = this.id
            }
            //#region 从前段转换后端所需格式
            //#endregion
            return postData
        }
    }
    async loadRoleData() {
        const { data } = await api.getRolePage()
        return data.items
    }
    async loadRole(id) {
        const { data } = await api.sysUserOwnRole({ id })
        return data
    }
    render() {
        return (
            <Form ref={this.form} className="yo-form">
                <Spin spinning={this.state.loading} indicator={<AntIcon type="loading" />}>
                    <div className="yo-form-group">
                        <Form.Item label="请选择角色" name="grantRoleIdList">
                            <Select mode="multiple" placeholder="请选择角色">
                                {this.state.options.roleData.map(item => {
                                    return (
                                        <Select.Option key={item.id} value={item.id}>
                                            {item.name}
                                        </Select.Option>
                                    )
                                })}
                            </Select>
                        </Form.Item>
                    </div>
                </Spin>
            </Form>
        )
    }
}
