/* eslint-disable @typescript-eslint/no-use-before-define */
import React, { useState, useRef, useEffect } from 'react';
import { Button, Space, Modal, Form, Input, message, Popconfirm, Table, Spin, Tag } from 'antd';
import { roleApi, moduleApi } from '@/api/sys/service';
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 [showTemplateModal, setShowTemplateModal] = useState(false);
    const [submitKeys, setSubmitKeys] = useState<any[]>([]);
    const [selectedTempRowKeys, setSelectTempRowKeys] = useState<string[]>([]);
    const [isLoading, setIsLoading] = useState(false);
    const [form] = Form.useForm();
    const actionRef = useRef<ActionType>();
    // 模板列表数组
    const [moduleList, setModuleList] = useState<any[]>([]);
    const roleColumns: ProColumns<RoleType>[] = [
        {
            title: '角色名称',
            dataIndex: 'name',
            key: 'name'
        },
        {
            title: '角色描述',
            dataIndex: 'description',
            key: 'description',
            search: false
        },
        {
            title: '操作',
            search: false,
            key: 'action',
            fixed:'right',
            render: (_: any, record: any) => (
                <Space size="middle">
                    <a onClick={() => onEditRole(record)}>编辑</a>
                    <a onClick={() => onGetRoleModule(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 || '创建角色失败');
            }
        }
    }
    /**
        * 分配模块
        * @param values 
        */
    const onGetRoleModule = async (record: any) => {
        setCurrentRole(record);
        setShowTemplateModal(true);
        setIsLoading(true);
        const response: MyResponse.Content = await roleApi.GetRoleModuleList(record.id);
        setIsLoading(false);
        if (response.statusCode === 200) {
            console.log(' response.data', response.data);
            const selectKeys: string[] = [];
            response.data.forEach((item: any) => {
                selectKeys.push(item.moduleId!);
            });
            setSelectTempRowKeys(selectKeys);
        } else {
            setSelectTempRowKeys([])
        }
    }
    const formartModuleList = (moduleListPramrm: any[]) => {
        moduleListPramrm.forEach(item => {
            if (item.children && item.children.length > 0) {
                formartModuleList(item.children);
            }
        });
        return moduleListPramrm;
    }
    useEffect(() => {
        /**
    * 获取模板列表
    */
        const onFetchModuleList = async () => {
            const response = await moduleApi.GetTreeGridModule();
            if (response.statusCode === 200) {
                setModuleList(formartModuleList(response.data));
            } else {
                message.error(response.errors || '获取模板列表失败');
            }
        }
        onFetchModuleList();
    }, []);

    /**
         * 给模板 授权模块
         */
    const onAddRoleModule = async (roleId: string) => {
        const response = await roleApi.AddRoleModule({
            roleId: roleId,
            moduleIds: submitKeys
        });
        if (response.statusCode === 200) {
            message.success('授权成功');
        } else {
            message.error(response.errors || '授权失败');
        }
        setShowTemplateModal(false);
    }
    /**
     * 添加角色
     */
    const onAddRole = () => {
        setCurrentRole({
            id: '',
            name: '',
            description: ''
        });
        form.resetFields();
        setIsModalVisible(true);
    }




    return (
        <div >
            <ProTable<RoleType>
                columns={roleColumns}
                actionRef={actionRef}
                cardBordered
                bordered
                scroll={{ x: true }}
                rowClassName={(record: any, index: number, indent: number) => {
                    if (index % 2 === 0) {
                        return ''; // 偶数行的类名
                    } else {
                        return 'even-row-background'; // 奇数行的类名
                    }
                }}
                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,
                    showSizeChanger:false
                }}
                dateFormatter="string"
                headerTitle="角色列表"
                toolBarRender={() => [
                    <Button key="button" icon={<PlusOutlined />} type="primary" onClick={onAddRole}>
                        添加
                    </Button>
                ]}
            />
            <Modal
                maskClosable={false} 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>

            <Modal
                maskClosable={false} title={`分配授权模块【${currentRole?.name}】`} open={showTemplateModal} onOk={() => {
                    onAddRoleModule(currentRole?.id)
                }} onCancel={() => setShowTemplateModal(false)}>
                <Spin size="large" spinning={isLoading}>
                    <Table
                        rowSelection={{
                            checkStrictly: false,
                            type: 'checkbox',
                            selectedRowKeys: selectedTempRowKeys,
                            onChange: (selectedRowKeys, selectedRows) => {
                                let myselectedRows: any[] = selectedRows;
                                console.log(selectedRows);
                                console.log(selectedRowKeys);
                                myselectedRows.map((v: any) => (
                                    // if (!v.parentId) {
                                    //    if (v.children.length>0) {
                                    //     tempSelected =  tempSelected.filter(function(item) {
                                    //         return item !== v.id;
                                    //       });
                                    //    }
                                    // }
                                    v.moduleId = v.id
                                ))
                                setSubmitKeys(myselectedRows)


                                setSelectTempRowKeys(selectedRowKeys as string[]);
                            }
                        }}
                        pagination={false}
                        columns={[
                            {
                                title: '名称',
                                dataIndex: 'name',
                                key: 'name',
                            },
                            {
                                title: '类型',
                                dataIndex: 'category',
                                render: (_, record) => (
                                    <>
                                        {
                                            (() => {
                                                if (record.category === 1) {
                                                    return <Tag color='green'>
                                                        菜单
                                                    </Tag>
                                                } else if (record.category === 2) {
                                                    return <Tag color='geekblue'>
                                                        视图
                                                    </Tag>
                                                } else {
                                                    return <Tag color='volcano'>
                                                        功能
                                                    </Tag>
                                                }
                                            })()
                                        }
                                    </>
                                )
                            },
                        ]}
                        dataSource={moduleList}
                        rowKey="id"
                    />
                </Spin>
            </Modal>


        </div>
    );
};

export default Role;