import React, { Component } from 'react'
import { Button, Card, Dropdown, Form, Input, Menu, message as Message, Popconfirm } from 'antd'
import { AntIcon, Auth, Container, ModalForm, QueryTable, QueryTableActions } from 'components'
import { api } from 'common/api'
import auth from 'components/authorized/handler'
import { isEqual } from 'lodash'
import FormBody from './form'
import MenuForm from './menu'
import DataForm from './data'

// 配置页面所需接口函数
const apiAction = {
    page: api.getRolePage,
    add: api.sysRoleAdd,
    edit: api.sysRoleEdit,
    delete: api.sysRoleDelete,

    grantMenu: api.sysRoleGrantMenu,
    grantData: api.sysRoleGrantData,
}

// 用于弹窗标题
const name = '角色'

export default class index extends Component {
    // 表格实例
    table = React.createRef()

    // 新增窗口实例
    addForm = React.createRef()
    // 编辑窗口实例
    editForm = React.createRef()

    menuForm = React.createRef()
    dataForm = React.createRef()

    columns = [
        {
            title: '角色名',
            dataIndex: 'name',
            width: 400,
            sorter: true,
        },
        {
            title: '唯一编码',
            dataIndex: 'code',
            width: 400,
            sorter: true,
        },
        {
            title: '排序',
            dataIndex: 'sort',
            width: 80,
            sorter: true,
            defaultSortOrder: 'ascend',
        },
    ]

    /**
     * 构造函数,在渲染前动态添加操作字段等
     * @param {*} props
     */
    constructor(props) {
        super(props)

        const flag = auth({ sysRole: [['edit'], ['delete']] })

        if (flag) {
            this.columns.push({
                title: '操作',
                width: 150,
                dataIndex: 'actions',
                render: (text, record) => (
                    <QueryTableActions>
                        <Auth auth="sysRole:edit">
                            <a onClick={() => this.onOpen(this.editForm, record)}>编辑</a>
                        </Auth>
                        <Auth auth="sysRole:delete">
                            <Popconfirm
                                placement="topRight"
                                title="是否确认删除"
                                onConfirm={() => this.onDelete(record)}
                            >
                                <a>删除</a>
                            </Popconfirm>
                        </Auth>
                        <Auth auth={{ sysRole: [['grantMenu'], ['grantData']] }}>
                            <Dropdown
                                placement="bottomRight"
                                overlay={
                                    <Menu>
                                        <Auth auth="sysRole:grantMenu">
                                            <Menu.Item>
                                                <a
                                                    onClick={() =>
                                                        this.onOpen(this.menuForm, record)
                                                    }
                                                >
                                                    授权菜单
                                                </a>
                                            </Menu.Item>
                                        </Auth>
                                        <Auth auth="sysRole:grantData">
                                            <Menu.Item>
                                                <a
                                                    onClick={() =>
                                                        this.onOpen(this.dataForm, record)
                                                    }
                                                >
                                                    授权数据
                                                </a>
                                            </Menu.Item>
                                        </Auth>
                                    </Menu>
                                }
                            >
                                <a className="ant-dropdown-link">
                                    授权
                                    <AntIcon type="down" />
                                </a>
                            </Dropdown>
                        </Auth>
                    </QueryTableActions>
                ),
            })
        }
    }

    /**
     * 阻止外部组件引发的渲染,提升性能
     * 可自行添加渲染条件
     * [必要]
     * @param {*} props
     * @param {*} state
     * @returns
     */
    shouldComponentUpdate(props, state) {
        return !isEqual(this.state, state)
    }

    /**
     * 调用加载数据接口,可在调用前对query进行处理
     * [异步,必要]
     * @param {*} params
     * @param {*} query
     * @returns
     */
    loadData = async (params, query) => {
        const { data } = await apiAction.page({
            ...params,
            ...query,
        })
        return data
    }

    /**
     * 打开新增/编辑弹窗
     * @param {*} modal
     * @param {*} record
     */
    onOpen(modal, record) {
        modal.current.open({
            record,
        })
    }

    /**
     * 对表格上的操作进行统一处理
     * [异步]
     * @param {*} action
     * @param {*} successMessage
     */
    async onAction(action, successMessage) {
        this.table.current.onLoading()
        try {
            await action
            Message.success(successMessage)
            this.table.current.onReloadData()
        } catch {
            this.table.current.onLoaded()
        }
    }

    /**
     * 删除
     * @param {*} record
     */
    onDelete(record) {
        this.onAction(apiAction.delete(record), '删除成功')
    }

    //#region 自定义方法
    //#endregion

    render() {
        return (
            <Container mode="fluid">
                <br />
                <Card bordered={false}>
                    <QueryTable
                        ref={this.table}
                        loadData={this.loadData}
                        columns={this.columns}
                        query={
                            <Auth auth="sysRole:page">
                                <Form.Item label="角色名称" name="name">
                                    <Input autoComplete="off" placeholder="请输入角色名称" />
                                </Form.Item>
                                <Form.Item label="唯一编号" name="code">
                                    <Input autoComplete="off" placeholder="请输入唯一编号" />
                                </Form.Item>
                            </Auth>
                        }
                        operator={
                            <Auth auth="sysRole:add">
                                <Button
                                    icon={<AntIcon type="plus" />}
                                    onClick={() => this.onOpen(this.addForm)}
                                >
                                    新增{name}
                                </Button>
                            </Auth>
                        }
                    />
                </Card>

                <ModalForm
                    title={`新增${name}`}
                    action={apiAction.add}
                    ref={this.addForm}
                    onSuccess={() => this.table.current.onReloadData()}
                >
                    <FormBody />
                </ModalForm>

                <ModalForm
                    title={`编辑${name}`}
                    action={apiAction.edit}
                    ref={this.editForm}
                    onSuccess={() => this.table.current.onReloadData()}
                >
                    <FormBody />
                </ModalForm>

                <ModalForm
                    title="授权菜单"
                    action={apiAction.grantMenu}
                    ref={this.menuForm}
                    width={1200}
                    onSuccess={() => this.table.current.onReloadData()}
                >
                    <MenuForm />
                </ModalForm>

                <ModalForm
                    title="数据授权"
                    action={apiAction.grantData}
                    ref={this.dataForm}
                    onSuccess={() => this.table.current.onReloadData()}
                >
                    <DataForm />
                </ModalForm>
            </Container>
        )
    }
}
