import { useState, useEffect, useMemo } from 'react';
import { Button,Form, Input, Select, Space, Card, Table, Checkbox, Tree,Modal, message, Flex, Typography, Drawer, Pagination } from 'antd';
import { getRoleList, deleteRole, saveRole, getRoleTree } from '@/apis/role';
import { getStageList, getSubjectListSelect } from '@/apis/common';
import { logger } from '@/apis/auth';
import { getAllCheckedListIds } from '@/utils/data';
import styles from './index.less';

const AccessPage = () => {


    const [form] = Form.useForm();
    const [tableLoading, setTableLoading] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [dataSource, setDataSource] = useState([]);
    const [open, setOpen] = useState(false);

    const [roleId, setRoleId] = useState(false);

    const [stageOptions, setStageOptions] = useState([]);
    const [stageIds, setStageIds] = useState([]);
    const [subjectOptions, setSubjectOptions] = useState([]);


    const [treeData, setTreeData] = useState({});

    const [permissions, setPermissions] = useState([]);

    const [total, setTotal] = useState(0);

    const [pageNum, setPageNum] = useState(1);
    const [pageSize, setPageSize] = useState(10);

    const computedTitle = useMemo(() => {
        return roleId ? '编辑角色' : '新增角色';
    }, [roleId]);

    useEffect(() => {
        init();
        getStageListData();


    }, []);


    useEffect(() => {
        if (stageIds?.length > 0) {
            getSubjectData();
        }
    }, [stageIds]);


    useEffect(() => {
        if (stageIds?.length > 0 && !roleId) {
            getAccessTreeData();
        }
    }, [stageIds, roleId])


    useEffect(() => {
        if (!permissions?.length) {
            form.setFieldValue('permissions', [])
        }
        form.setFieldValue('permissions', permissions);
    }, [permissions])


    const init = async () => {
        try {
            setTableLoading(true);
            const res = await getRoleList({ pageNum, pageSize, });
            if (res?.code === 200) {
                setTableLoading(false);
                setDataSource(res?.data || []);
                setTotal(res?.total || 0);
                return;
            }
            setTableLoading(false);
        } catch (error) {
            setTableLoading(false);
            console.log(error, 'init-error');

        }
    };

    const getStageListData = async () => {
        try {
            const res = await getStageList();
            if (res?.code === 200) {
                setStageOptions(() => {
                    return res?.data?.map((item) => {
                        return {
                            label: item.value,
                            value: item.key
                        }
                    })
                });
                setStageIds(res?.data?.map((item) => item.key));

            }
        } catch (error) {
            console.log(error, 'getStageListData-error');

        }
    };


    const getSubjectData = async () => {
        try {
            const res = await getSubjectListSelect({ stages: stageIds?.join(',') });
            if (res?.code === 200) {

                setSubjectOptions(() => {
                    return res?.data?.map((item) => {
                        return {
                            label: item?.cname,
                            value: item?.id
                        }
                    })
                })

            }
        } catch (error) {
            console.log(error, 'getStageListData-error');

        }
    };


    const getAccessTreeData = async () => {
        try {
            const res = await getRoleTree({ stage: stageIds?.join(',') });
            if (res?.code === 200) {
                setTreeData(res?.data)
            }
        } catch (error) {
            console.log(error, 'getStageListData-error');

        }
    };


    const handlePrimaryCityCheck = (value) => {

        setPermissions((prev) => {
            return Array.from(new Set([...prev, ...value]));
        })


    };
    const handlePrimaryDistrictCheck = (value) => {
        setPermissions((prev) => {
            return Array.from(new Set([...prev, ...value]));
        })


    };
    const handlePrimarySchoolCheck = (value) => {
        setPermissions((prev) => {
            return Array.from(new Set([...prev, ...value]));
        })


    };

    const handleJuniorCityCheck = (value) => {
        setPermissions((prev) => {
            return Array.from(new Set([...prev, ...value]));
        })


    };
    const handleJuniorDistrictCheck = (value) => {
        setPermissions((prev) => {
            return Array.from(new Set([...prev, ...value]));
        })


    };
    const handleJuniorSchoolCheck = (value) => {
        setPermissions((prev) => {
            return Array.from(new Set([...prev, ...value]));
        })


    };

    const handleHighCityCheck = (value) => {
        setPermissions((prev) => {
            return Array.from(new Set([...prev, ...value]));
        })


    };
    const handleHighDistrictCheck = (value) => {
        setPermissions((prev) => {
            return Array.from(new Set([...prev, ...value]));
        })


    };
    const handleHighSchoolCheck = (value) => {
        setPermissions((prev) => {
            return Array.from(new Set([...prev, ...value]));
        })

    };

    const handleDataImportCheck = (value) => {
        setPermissions((prev) => {
            return Array.from(new Set([...prev, ...value]));
        });
    };

    const handleSecondaryAdminCheck = (value) => {
        setPermissions((prev) => {
            return Array.from(new Set([...prev, ...value]));
        });
    };


    // const onFormValuesChange = async (values) => {
    //     try {
    //         setTableLoading(true);
    //         const res = await getSubjectList(values);
    //         if (res?.code === 200) {
    //             setTableLoading(false);
    //             setDataSource(res?.data || []);
    //             return;
    //         }
    //         setTableLoading(false);
    //     } catch (error) {
    //         setTableLoading(false);
    //         console.log(error, 'onFormValuesChange-error');

    //     }
    // };


    const handleCreateRole = () => {
        setOpen(true);
        setRoleId('');
        form.resetFields();
    };

    const handleFinish = async () => {
        setConfirmLoading(true);
        form.validateFields().then(async () => {
            const res = await saveRole(roleId ? {
                id: roleId,
                ...form.getFieldsValue()
            } : form.getFieldsValue());
            if (res.code === 200) {
                setConfirmLoading(false);
                setOpen(false);
                init();
                form.resetFields();
                setRoleId('');
                setPermissions([]);
                message.success('操作成功');
                if(roleId){
                    await logger({description:"修改角色"});
                }else{
                    await logger({description:"创建角色"});
                }
                return;
            }
            setConfirmLoading(false);
        }).catch(error => {
            setConfirmLoading(false);
            console.log(error, 'handleFinish-error');
        });
    };


    const handleDeleteRole = (record) => {
        Modal.confirm({
            title: '删除角色',
            content: '确定删除角色吗？',
            okText: '确定',
            cancelText: '取消',
            centered: true,

            onOk() {
                return new Promise((resolve, reject) => {
                    deleteRole({ roleId: record?.id }).then(async(res) => {
                        if (res.code === 200) {
                            message.success('删除角色成功');
                            resolve();
                            init();
                            await logger({description:"删除角色"});
                            return
                        }
                        message.error(res?.msg);
                        reject();
                    }).catch(error => {
                        console.log(error, 'handleResetPassword-error');
                        reject();
                    })
                });
            },
        });
    };


    const handleEditRole = async (record) => {

        try {
            const res = await getRoleTree({ roleId: record?.id, stage: record?.stage });
            if (res?.code === 200) {
                setTreeData(res?.data)
                setOpen(true);
                setRoleId(record?.id);
                form.setFieldsValue({
                    roleName: res?.data?.roleName,
                    subjects: res?.data?.subjects,
                    stages: res?.data?.stages
                });
                setStageIds(res?.data?.stages);
                const checkIds = getAllCheckedListIds(res?.data);
                form.setFieldValue('permissions', checkIds);
                setPermissions(checkIds);

            }

        } catch (error) {
            console.log(error, 'handleEditRole-error');

        }
        ;
    };


    const onPageChange = async (pageNum, pageSize) => {
        setPageNum(pageNum);
        setPageSize(pageSize);
        try {
            setTableLoading(true);
            const res = await getRoleList({ pageNum, pageSize });
            if (res?.code === 200) {
                setTableLoading(false);
                setDataSource(res?.data || []);
                setTotal(res?.total || 0);
                return;
            }
            setTableLoading(false);
        } catch (error) {
            setTableLoading(false);
            console.log(error, 'init-error');

        }


    };

    const columns = [
        {
            title: '角色名称',
            dataIndex: 'roleName',
            key: 'roleName',
            width: 280,
            align: 'center',
        },
        {
            title: '学科',
            dataIndex: 'subject',
            key: 'subject',
            align: 'center',
        },
        {
            title: '适用范围',
            dataIndex: 'stage',
            key: 'stage',
            align: 'center',
            width: 140
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            render(_, record) {
                return (
                    <Space size="middle">
                        <Button type="link" onClick={() => { handleEditRole(record) }}>编辑</Button>
                        <Button type='link' danger onClick={() => handleDeleteRole(record)}>删除</Button>
                    </Space>
                );
            }
        },
    ];


    return (
        <div className={styles.access}>
            <header className={styles.access_header}>
                <Card style={{ height: "100%" }}>
                    <Flex justify="space-between">
                        <Typography.Title level={4} >
                            角色
                        </Typography.Title>
                        <Button type="primary" onClick={handleCreateRole}>
                            创建角色
                        </Button>
                    </Flex>
                </Card>
            </header>
            <main className={styles.access_main}>
                <Card>
                    <Table bordered columns={columns} loading={tableLoading} dataSource={dataSource} pagination={false} style={{ height: '100%' }} />
                </Card>
            </main>
            <footer className={styles.access_footer}>
                <Pagination showQuickJumper showSizeChanger total={total} onChange={onPageChange} showTotal={(total) => `共${total}条数据`} />

            </footer>

            <Drawer
                title={computedTitle}
                open={open}
                destroyOnClose
                onClose={() => {
                    setOpen(false);
                    setRoleId('');
                    form.resetFields();
                    setPermissions([]);
                    setTreeData({});
                }}
                size="large"
                width={1000}
            >
                <Form
                    form={form}
                    layout="vertical"
                    initialValues={{
                        stages: stageOptions?.map(item => item.value),
                    }}

                >
                    <Form.Item label="角色名称" name="roleName" rules={[
                        {
                            required: true,
                            message: '请填写角色名称',
                        },
                    ]}>
                        <Input placeholder="请输入角色名称" />
                    </Form.Item>
                    <Form.Item label="学段" name="stages" rules={[
                        {
                            required: true,
                            message: '请至少选择一个学段',
                        },
                    ]}>
                        <Checkbox.Group options={stageOptions} onChange={(value) => {
                            if (!value?.length) {
                                // setStageIds([]);
                                return;
                            }
                            setStageIds(value);

                        }} />
                    </Form.Item>
                    <Form.Item label="学科" name="subjects" rules={[
                        {
                            required: true,
                            message: '请至少选择一门学科',
                        },
                    ]}>
                        <Select
                            mode="multiple"
                            placeholder="请选择学科"
                            options={subjectOptions}
                            maxTagCount={6}
                            style={{ width: '100%' }}
                            allowClear
                        />
                    </Form.Item>

                    <Form.Item label="权限" name="permissions" rules={[
                        {
                            required: true,
                            message: '请选择权限',
                        },
                    ]}>
                        <div className={styles.access_list}>
                            {stageIds?.length > 0 ? stageIds.map((item) => {
                                if (item == 1) {

                                    return (
                                        <div>
                                            <div className={styles.access_list_title} style={{ marginTop: 8 }}>小学</div>
                                            <Flex justify="space-evenly" style={{ marginTop: 8 }}>
                                                <Card title='市级报告' hoverable style={{ width: 300, height: 320, overflow: "auto", marginLeft: 8 }}>
                                                    <Tree
                                                        checkable
                                                        fieldNames={{ title: 'label', key: 'id', children: "children" }}
                                                        defaultCheckedKeys={treeData?.primarySchoolRole?.city?.checkedList}
                                                        onCheck={handlePrimaryCityCheck}
                                                        defaultExpandAll={true}
                                                        treeData={treeData?.primarySchoolRole?.city?.permissionTree}
                                                    />
                                                </Card>
                                                <Card title='区县报告' hoverable style={{ width: 300, height: 320, overflow: "auto", marginLeft: 8 }}>
                                                    <Tree
                                                        checkable
                                                        defaultExpandAll={true}
                                                        fieldNames={{ title: 'label', key: 'id', children: "children" }}
                                                        defaultCheckedKeys={treeData?.primarySchoolRole?.district?.checkedList}
                                                        onCheck={handlePrimaryDistrictCheck}
                                                        treeData={treeData?.primarySchoolRole?.district?.permissionTree}
                                                    />
                                                </Card>
                                                <Card title='学校报告' hoverable style={{ width: 300, height: 320, overflow: "auto", marginLeft: 8 }}>
                                                    <Tree
                                                        checkable
                                                        defaultExpandAll={true}
                                                        fieldNames={{ title: 'label', key: 'id', children: "children" }}
                                                        defaultCheckedKeys={treeData?.primarySchoolRole?.school?.checkedList}
                                                        onCheck={handlePrimarySchoolCheck}
                                                        treeData={treeData?.primarySchoolRole?.school?.permissionTree}
                                                    />
                                                </Card>
                                            </Flex>
                                        </div>

                                    )

                                }
                                if (item == 2) {

                                    return (
                                        <div>
                                            <div className={styles.access_list_title} style={{ marginTop: 8 }}>初中</div>
                                            <Flex style={{ marginTop: 8 }}>
                                                <Card title='市级报告' hoverable style={{ width: 300, height: 320, overflow: "auto", marginLeft: 8 }}>
                                                    <Tree
                                                        checkable
                                                        fieldNames={{ title: 'label', key: 'id', children: "children" }}
                                                        defaultCheckedKeys={treeData?.juniorSchoolRole?.city?.checkedList}
                                                        onCheck={handleJuniorCityCheck}
                                                        defaultExpandAll={true}
                                                        treeData={treeData?.juniorSchoolRole?.city?.permissionTree}
                                                    />
                                                </Card>
                                                <Card title='区县报告' hoverable style={{ width: 300, height: 320, overflow: "auto", marginLeft: 8 }}>
                                                    <Tree
                                                        checkable
                                                        defaultExpandAll={true}
                                                        fieldNames={{ title: 'label', key: 'id', children: "children" }}
                                                        defaultCheckedKeys={treeData?.juniorSchoolRole?.district?.checkedList}
                                                        onCheck={handleJuniorDistrictCheck}
                                                        treeData={treeData?.juniorSchoolRole?.district.permissionTree}
                                                    />
                                                </Card>
                                                <Card title='学校报告' hoverable style={{ width: 300, height: 320, overflow: "auto", marginLeft: 8 }}>
                                                    <Tree
                                                        checkable
                                                        defaultExpandAll={true}
                                                        fieldNames={{ title: 'label', key: 'id', children: "children" }}
                                                        defaultCheckedKeys={treeData?.juniorSchoolRole?.school?.checkedList}
                                                        onCheck={handleJuniorSchoolCheck}
                                                        treeData={treeData?.juniorSchoolRole?.school.permissionTree}
                                                    />
                                                </Card>
                                            </Flex>
                                        </div>

                                    )

                                }
                                if (item == 3) {

                                    return (
                                        <div>
                                            <div className={styles.access_list_title} style={{ marginTop: 8 }}>高中</div>
                                            <Flex style={{ marginTop: 8 }}>
                                                <Card title='市级报告' hoverable style={{ width: 300, height: 320, overflow: "auto", marginLeft: 8 }}>
                                                    <Tree
                                                        checkable
                                                        fieldNames={{ title: 'label', key: 'id', children: "children" }}
                                                        defaultCheckedKeys={treeData?.highSchoolRole?.city?.checkedList}
                                                        onCheck={handleHighCityCheck}
                                                        defaultExpandAll={true}
                                                        treeData={treeData?.highSchoolRole?.city?.permissionTree}
                                                    />
                                                </Card>
                                                <Card title='区县报告' hoverable style={{ width: 300, height: 320, overflow: "auto", marginLeft: 8 }}>
                                                    <Tree
                                                        checkable
                                                        defaultExpandAll={true}
                                                        fieldNames={{ title: 'label', key: 'id', children: "children" }}
                                                        defaultCheckedKeys={treeData?.highSchoolRole?.district?.checkedList}
                                                        onCheck={handleHighDistrictCheck}
                                                        treeData={treeData?.highSchoolRole?.district.permissionTree}
                                                    />
                                                </Card>
                                                <Card title='学校报告' hoverable style={{ width: 300, height: 320, overflow: "auto", marginLeft: 8 }}>
                                                    <Tree
                                                        checkable
                                                        defaultExpandAll={true}
                                                        fieldNames={{ title: 'label', key: 'id', children: "children" }}
                                                        defaultCheckedKeys={treeData?.highSchoolRole?.school?.checkedList}
                                                        onCheck={handleHighSchoolCheck}
                                                        treeData={treeData?.highSchoolRole?.school?.permissionTree}
                                                    />
                                                </Card>
                                            </Flex>
                                        </div>

                                    )

                                }

                            }) : null}
                            {stageIds?.length > 0 ? (
                                <>
                                    <div className={styles.access_list_title} style={{ marginTop: 8 }}>数据导入</div>
                                    <Flex style={{ marginTop: 8 }}>
                                        <Card title='数据导入' hoverable style={{ width: 300, height: 320, overflow: "auto", marginLeft: 8 }}>
                                            <Tree
                                                checkable
                                                fieldNames={{ title: 'label', key: 'id', children: "children" }}
                                                defaultCheckedKeys={treeData?.importDataRole?.upload?.checkedList}
                                                onCheck={handleDataImportCheck}
                                                defaultExpandAll={true}
                                                treeData={treeData?.importDataRole?.upload?.permissionTree}
                                            />
                                        </Card>
                                        <Card title='次级管理员' hoverable style={{ width: 300, height: 320, overflow: "auto", marginLeft: 8 }}>
                                            <Tree
                                                checkable
                                                defaultExpandAll={true}
                                                fieldNames={{ title: 'label', key: 'id', children: "children" }}
                                                defaultCheckedKeys={treeData?.importDataRole?.report?.checkedList}
                                                onCheck={handleSecondaryAdminCheck}
                                                treeData={treeData?.importDataRole?.report.permissionTree}
                                            />
                                        </Card>
                                    </Flex>
                                </>
                            ) : null}
                        </div>
                    </Form.Item>
                    <Form.Item>
                        <Flex style={{ width: '100%' }}>
                            <Space>
                                <Button onClick={() => {
                                    setOpen(false);
                                    setRoleId("");
                                    form.resetFields();
                                    setPermissions([]);
                                    setTreeData({});
                                }}>取消</Button>
                                <Button type='primary' loading={confirmLoading} onClick={handleFinish}>确定</Button>
                            </Space>
                        </Flex>
                    </Form.Item>
                </Form>
            </Drawer>
        </div>
    );
};

export default AccessPage;