import React, { useRef, useState, useEffect } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import type { ColumnsType } from 'antd/es/table';
import { ProTable } from '@ant-design/pro-components';
import { Button, Modal, Form, Input, message, Popconfirm, Table, Tag, Tabs, Space, Spin, TagProps, TabsProps } from 'antd';
import authTempAPI from '@/api/AuthTemplate';
import moduleAPI from '@/api/ModuleAPI';
const AuthTemplate: React.FC = () => {
    const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const [currentPage, setCurrentPage] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(10);
    const [total, setTotal] = useState<number>(0);
    const [authTempList, setAuthTempList] = useState<AuthTemplateTypes.AuthTemplateType[]>([]);
    const [authForm] = Form.useForm();
    const [isLoading, setIsLoading] = useState(false);
    

    const TabItems: TabsProps['items']=[
        {
         label:'用户',key:'account'
        },{
            label:'角色',key:'role'   
        }
    ]

    /**
     * 模板相关
     */
    //是否显示模板弹窗
    const [showTemplateModal, setShowTemplateModal] = useState<boolean>(false);
    // 模板列表数组
    const [moduleList, setModuleList] = useState<AuthTemplateTypes.ModuleType[]>([]);
    const [currentTemplate, setCurrentTemplate] = useState<AuthTemplateTypes.AuthTemplateType>();
    const [selectedTempRowKeys, setSelectTempRowKeys] = useState<string[]>([]);
    const [submitKeys, setSubmitKeys] = useState<string[]>([]);

   

    /**
     * 创建授权模板之前
     */
    const onBeforeCreate = () => {
        authForm.resetFields();
        setIsModalVisible(true);
    }

    /**
     * 点击编辑按钮
     */
    const onBeforeEdit = (values: AuthTemplateTypes.AuthTemplateType) => {
        setCurrentTemplate(values);
        setIsModalVisible(true);
        authForm.setFieldsValue(values);
    }

    /**
     * 删除权限模板
     * @param values 
     */
    const onDeleteAuth = async (values: AuthTemplateTypes.AuthTemplateType) => {
        const response = await authTempAPI.DeleteAuthTemp(values.id);
        if (response.statusCode === 200) {
            message.success('删除成功');
        } else {
            message.error(response.errors || '删除失败');
        }
        actionRef.current?.reload();
    }

    /**
     * 提交模板表单
     */
    const onFinishAuth = async (values: AuthTemplateTypes.AuthTemplateType) => {
        if (values.id) {
            const response = await authTempAPI.SaveModifyAuthTemp(values);
            if (response.statusCode === 200) {
                message.success('修改成功');
                setIsModalVisible(false);
            } else {
                message.error(response.errors || '修改失败');
            }
        } else {
            const response = await authTempAPI.SaveCreateAuthTemp(values);
            if (response.statusCode === 200) {
                message.success('添加成功');
                setIsModalVisible(false);
            } else {
                message.error(response.errors || '添加失败');
            }
        }
        actionRef.current?.reload();
    }

    /**
     * 获取授权模板列表
     */
    const onFetchAuthTempList = async (values: AuthTemplateTypes.AuthTemplateSearch) => {
        const response = await authTempAPI.GetPagedListAuthTemp(values);
        if (response.statusCode === 200) {
            setAuthTempList(response.data.items);
            return response.data.items;
        } else {
            message.error(response.errors || '获取授权模板列表失败');
            return [];
        }
    }

    /**
     * 分配模块
     * @param values 
     */
    const onDistributionModuleBefore = async (values: AuthTemplateTypes.AuthTemplateType) => {
        setShowTemplateModal(true);
        setCurrentTemplate(values);
        setIsLoading(true);
        const response = await authTempAPI.GetModules(values.id);
        setIsLoading(false);
        if (response.statusCode === 200) {
            const selectKeys: string[] = [];
            response.data.forEach((item: AuthTemplateTypes.ModuleType) => {
                if (item.hasPermission) {
                    if (item.childrens.length > 0) {
                        item.childrens.forEach((cItem: AuthTemplateTypes.ModuleType) => {
                            if (cItem.hasPermission) {
                                selectKeys.push(cItem.id);
                                if (cItem.childrens.length > 0) {
                                    cItem.childrens.forEach((fItem: AuthTemplateTypes.ModuleType) => {
                                        selectKeys.push(fItem.id);
                                    })
                                }
                            }
                        });
                    }
                }
            });
            console.log('selectKeys', selectKeys);
            setSelectTempRowKeys(selectKeys);
        } else {
            setSelectTempRowKeys([])
        }
    }

    const moduleColumns: ColumnsType<AuthTemplateTypes.ModuleType> = [
        {
            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>
                            }
                        })()
                    }
                </>
            )
        },
    ]
    const formartModuleList = (moduleListPramrm: AuthTemplateTypes.ModuleType[]) => {
        moduleListPramrm.forEach(item => {
            if (item.children && item.children.length > 0) {
                formartModuleList(item.children);
            }
        });
        return moduleListPramrm;
    }
   
  

    /**
     * 给模板 授权模块
     */
    const onTempAuthModule = async () => {
        const response = await authTempAPI.SaveUpdateItems({
            tB_TemplateId: currentTemplate?.id || '',
            tB_ModuleIds: submitKeys
        });
        if (response.statusCode === 200) {
            message.success('授权成功');
        } else {
            message.error(response.errors || '授权失败');
        }
        setShowTemplateModal(false);
    }

    /**
     * 模板授权： 账号/角色
     */
    const [showAuthAccRoleModal, setShowAuthAccRoleModal] = useState<boolean>(false);
    const [accRoleTabActive, setAccRoleTabActive] = useState<string>('account');
    const [personData, setPersonData] = useState<AuthTemplateTypes.AuthObjectItem[]>([]);

   

    /**
     * 根据模板ID 获取用户/角色授权列表
     */
    const onFetchUserOrRoleAuthTemp = async () => {
        const jsonData: AuthTemplateTypes.AuthObjectParams = {
            templateId: currentTemplate?.id || '',
            type: -1,
            keyWord: ''
        }
        if (accRoleTabActive === 'account') {
            jsonData.type = 1;
        } else {
            jsonData.type = 2;
        }
        const response = await authTempAPI.GetauthorizeObjects(jsonData);
        if (response.statusCode === 200) {
            setPersonData(response.data);
        } else {
            message.error(response.errors || '获取用户/角色列表失败！');
        }
    }

    /**
     * 添加授权
     */
    const onAddauthorize = async (id: string) => {
        const jsonData = {
            templateIds: [currentTemplate?.id as string],
            authorizeType: -1,
            objectId: id
        }
        if (accRoleTabActive === 'account') {
            jsonData.authorizeType = 1;
        } else {
            jsonData.authorizeType = 2;
        }
        const response = await authTempAPI.Addauthorize(jsonData);
        if (response.statusCode === 200) {
            message.success('授权成功');
            onFetchUserOrRoleAuthTemp();
        } else {
            message.error(response.errors || '授权失败');
        }
    }

    /**
     * 移除授权
     * @param id 
     */
    const onRemoveauthorize = async (id: string) => {
        const jsonData = {
            templateId: currentTemplate?.id as string,
            type: -1,
            objectIds: [id]
        }
        if (accRoleTabActive === 'account') {
            jsonData.type = 1;
        } else {
            jsonData.type = 2;
        }
        const response = await authTempAPI.Removeauthorize(jsonData);
        if (response.statusCode === 200) {
            message.success('移除成功');
            onFetchUserOrRoleAuthTemp();
        } else {
            message.error(response.errors || '移除失败');
        }
    }


    useEffect(() => {
         /**
     * 获取模板列表
     */
    const onFetchModuleList = async () => {
        const response = await moduleAPI.GetTreeGridModule(null);
        if (response.statusCode === 200) {
            setModuleList(formartModuleList(response.data));
        } else {
            message.error(response.errors || '获取模板列表失败');
        }
    }
        onFetchModuleList();
    }, []);

    useEffect(() => {
        actionRef.current?.reload();
    }, [currentPage, pageSize]);

    useEffect(() => {
        if (currentTemplate?.id) {
            onFetchUserOrRoleAuthTemp();
        }
    }, [accRoleTabActive, currentTemplate]);

    const authTempColums: ProColumns<AuthTemplateTypes.AuthTemplateType>[] = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '描述',
            dataIndex: 'remark',
            search:false,
            key: 'remark',
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            render: (_, record) => [
                <a key="edit" onClick={() => onBeforeEdit(record)}>编辑</a>,
                <Popconfirm
                    key="sure"
                    title="确定要删除此模块吗？"
                    onConfirm={() => onDeleteAuth(record)}
                    okText="确定"
                    cancelText="取消"
                >
                    <a >删除</a>
                </Popconfirm>,
                <a key="authModule" onClick={() => onDistributionModuleBefore(record)}>分配模块</a>,
                <a key="auth" onClick={() => { setCurrentTemplate(JSON.parse(JSON.stringify(record))); setShowAuthAccRoleModal(true); }}>授权角色/账号</a>
            ],
        },
    ];
    const personelColumns: ColumnsType<AuthTemplateTypes.AuthObjectItem> = [
        {
            title: '账号',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '状态',
            dataIndex: 'isauthorized',
            key: 'isauthorized',
            render: (_, record) => (
                <>
                    {
                        (() => {
                            if (record.isauthorized) {
                                return <div style={{ color: 'green' }}>
                                    已授权
                                </div>
                            } else {
                                return ""
                            }
                        })()
                    }

                </>
            )
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle" >
                    {
                        (() => {
                            if (record.isauthorized) {
                                return <a style={{ color: '#F84352' }} onClick={() => onRemoveauthorize(record.id)}>
                                    移除授权
                                </a>
                            } else {
                                return <a style={{ color: 'green' }} onClick={() => onAddauthorize(record.id)}>
                                    授权
                                </a>
                            }
                        })()
                    }
                </Space>
            ),
        },
    ];
    return (
        <div>
            <ProTable<AuthTemplateTypes.AuthTemplateType>
                columns={authTempColums}
                actionRef={actionRef}
                cardBordered
                rowKey="id"
                request={async (values) => {
                    const authList = await onFetchAuthTempList({
                        keyWord: values.name||'',
                        sortName: '',
                        sortByAsc: false,
                        pageIndex: values.current || 1,
                        pageSize: values.pageSize || 10
                    });
                    return {
                        data: authList,
                        success: true,
                        total: total,
                    }
                }}
                search={{
                    labelWidth: 'auto',
                }}
                options={{
                    setting: {
                        listsHeight: 400,
                    },
                }}
                pagination={{
                    current: currentPage,
                    pageSize: pageSize,
                    onChange: (page) => setCurrentPage(page)
                }}
                headerTitle="授权模板"
                toolBarRender={() => [
                    <Button key="button" icon={<PlusOutlined />} type="primary" onClick={onBeforeCreate}>
                        新建
                    </Button>
                ]}
            />
            <Modal destroyOnClose title={`编辑授权模块【${currentTemplate?.name}】`} footer={null} open={isModalVisible} onCancel={() => setIsModalVisible(false)}>
                <Form
                    name="basic"
                    onFinish={onFinishAuth}
                    autoComplete="off"
                    form={authForm}
                >
                    <Form.Item
                        name="id"
                        hidden={true}
                    >
                        <Input />
                    </Form.Item>

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

                    <Form.Item
                        label="备注"
                        name="remark"
                        rules={[{ required: true, message: '请输入授权模板备注！' }]}
                    >
                        <Input />
                    </Form.Item>

                    {/* <Form.Item
                        label="是否禁用"
                        name="isDisabled"
                        valuePropName="checked"
                    >
                        <Switch checkedChildren="是" unCheckedChildren="否"></Switch>
                    </Form.Item> */}

                    <Form.Item>
                        <Button type="primary" htmlType="submit">
                            确定
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
            <Modal title={`分配授权模块【${currentTemplate?.name}】`} open={showTemplateModal} onOk={onTempAuthModule} onCancel={() => setShowTemplateModal(false)}>
                <Spin size="large" spinning={isLoading}>
                    <Table
                        rowSelection={{
                            checkStrictly: false,
                            type: 'checkbox',
                            selectedRowKeys: selectedTempRowKeys,
                            onChange: (selectedRowKeys, selectedRows) => {
                                const tempSelected = [...selectedRowKeys];
                                selectedRows.forEach(rowItem => {
                                    const find = tempSelected.find(item => rowItem.parentId === item);
                                    const repetFind = tempSelected.find(reItem => reItem === rowItem.parentId);
                                    if (!find && rowItem.parentId != '' && !repetFind) {
                                        tempSelected.push(rowItem.parentId);
                                    }
                                });
                                // console.log('selectedRowKeys', selectedRowKeys);
                                // console.log('selectedRows', selectedRows);
                                // console.log('>>>>', tempSelected);
                                setSubmitKeys(tempSelected as string[]);
                                setSelectTempRowKeys(selectedRowKeys as string[]);
                            }
                        }}
                        pagination={false}
                        columns={moduleColumns}
                        dataSource={moduleList}
                        rowKey="id"
                    />
                </Spin>
            </Modal>
            <Modal width={800} footer={null} title={`授权模板【${currentTemplate?.name}】`} open={showAuthAccRoleModal} onCancel={() => setShowAuthAccRoleModal(false)}>
                <Tabs items={TabItems.map((item)=>{
                    return{
                    label: item.label,
                    key: item.key,
                    children: <Table rowKey={record => record.id} columns={personelColumns} dataSource={personData} />,
                    } 
                })} activeKey={accRoleTabActive} onChange={(active) => setAccRoleTabActive(active)} tabPosition="left">
                </Tabs>
            </Modal>
        </div>
    );
};

export default AuthTemplate;
