import React, { useState, useRef } from 'react';
import { Button, Space, Modal, Form, Input, message, Popconfirm } from 'antd';
import roleAPI from "@/api/sys/Role";

import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';

interface RoleType {
    id: string;
    name: string;
    description: string;
}

const Role: React.FC = () => {

    const [currentRole, setCurrentRole] = useState<RoleType>({
        id: '',
        name: '',
        description: ''
    });
    const [isModalVisible, setIsModalVisible] = useState(false);

    const [form] = Form.useForm();

    const roleColumns: ProColumns<RoleType>[] = [
        {
            title: '角色名称',
            dataIndex: 'name',
            key: 'name'
        },
        {
            title: '角色描述',
            dataIndex: 'description',
            key: 'description',
            search:false
        },
        {
            title: '操作',
            search:false,
            key: 'action',
            render: (_: any, record: any) => (
                <Space size="middle">
                    <a onClick={() => onEditRole(record)}>编辑</a>
                    <Popconfirm
                        title="确定要删除此角色吗？"
                        onConfirm={() => onDeleteRole(record)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <a>删除</a>
                    </Popconfirm>
                </Space>
            ),
        }
    ];

    const onEditRole = (record: any) => {
        setCurrentRole(record);
        form.setFieldsValue(record);
        setIsModalVisible(true);
        actionRef.current?.reload();
    }

    /**
     * 删除角色
     * @param record 
     */
    const onDeleteRole = async (record: RoleType) => {
        const response = await roleAPI.DeleteRole(record.id);
        if (response.statusCode === 200) {
            message.success('删除成功');
            actionRef.current?.reload();
        } else {
            message.error(response.msg || '删除失败');
        }
    }

    /**
     * 添加/修改角色
     */
    const onFinishRole = async (role: RoleType) => {
        if (role.id) {
            const response = await roleAPI.ModifyRole(role);
            if (response.statusCode === 200) {
                message.success('更新角色信息成功');
                setIsModalVisible(false);
                actionRef.current?.reload();
            } else {
                message.error(response.msg || '更新角色信息失败');
            }
        } else {
            const response = await roleAPI.CreateRole(role);
            if (response.statusCode === 200) {
                message.success('创建角色成功');
                setIsModalVisible(false);
                actionRef.current?.reload();
            } else {
                message.error(response.msg || '创建角色失败');
            }
        }
    }

    /**
     * 添加角色
     */
    const onAddRole = () => {
        setCurrentRole({
            id: '',
            name: '',
            description: ''
        });
        form.resetFields();
        setIsModalVisible(true);
    }

    const actionRef = useRef<ActionType>();


    return (
        <div >
            <ProTable<RoleType>
                columns={roleColumns}
                actionRef={actionRef}
                cardBordered
                request={async (params = {}) => {
                    const response = await roleAPI.GetRolePagedList({
                        keyword: params.name,
                        sortName: '',
                        sortByAsc: false,
                        pageIndex: params.current || 1,
                        pageSize: params.pageSize || 10
                    });
                    if (response.statusCode === 200) {
                        return {
                            data: response.data.items,
                            success: true,
                            total: response.data.total
                        }
                    } else {
                        message.error(response.errors || '获取角色列表失败');
                        return {
                            data: [],
                            success: false,
                            total: 0
                        }
                    }
                }}
                rowKey="id"
                pagination={{
                    pageSize: 10
                }}
                dateFormatter="string"
                headerTitle="角色列表"
                toolBarRender={() => [
                    <Button key="button" icon={<PlusOutlined />} type="primary" onClick={onAddRole}>
                        添加
                    </Button>
                ]}
            />
            <Modal footer={null} title={currentRole.id === '' ? '添加角色' : '编辑角色'} open={isModalVisible} onCancel={() => setIsModalVisible(false)}>
                <Form
                    name="basic"
                    form={form}
                    onFinish={onFinishRole}
                >
                    <Form.Item
                        label="id"
                        name="id"
                        hidden={true}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="名称"
                        name="name"
                        rules={[{ required: true, message: '请输入角色名称！' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="描述"
                        name="description"
                        rules={[{ required: true, message: '请输入角色描述！' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item >
                        <Button type="primary" htmlType="submit">
                            确定
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default Role;