
import { useRef, useState, useEffect } from 'react';
import { connect } from '@umijs/max';
import { ConfigProvider, Space, Collapse, Tag, Modal, Row, Col, message } from 'antd';
import { PostRoleAddpermission, PostRoleDelpermission, getPermissionListWithchilds, getRoleGetpermissions, getRoleGetpermissionids } from '@/apis/api';
import { findId } from '@/utils/dataHelper';
const PagesMainPermissionRoleDispense: React.FC = ({ dispatch, dictModel, openModel, id }: any) => {
    const [openPreview, setOpenPreview] = useState(false);
    const [detail, setDetail] = useState(null)
    const [selectedIds, setSelectedIds] = useState<number[]>([0]);
    const [collapseKey, setCollapseKey] = useState<string[]>([]);


    useEffect(() => {
        setOpenPreview(openModel.openDispenseModal)

    }, [openModel.openDispenseModal])

    const handleChange = (tag: number, checked: boolean) => {
        const nextSelectedTags = checked
            ? [...selectedIds, tag]
            : selectedIds.filter((t) => t !== tag);
        setSelectedIds(nextSelectedTags);
        if (checked) {
            PostRoleAddpermission({ role_id: id, permission_id: tag }).then(res => {
                message.success('分配成功')
            }).catch(err => {
                message.error('添加失败')
            })
        } else {
            PostRoleDelpermission({ role_id: id, permission_id: tag }).then(res => {
                message.success('移除成功')
            }).catch(err => {
                message.error('移除成功')
            })
        }
    };

    // 检查给定的 id 是否存在于 res.data 中，并返回对应的下标加 1
    function checkIdInData(ids: number[], data: number) {
        const result: any = [];
        if (ids && ids.length > 0) {
            ids.forEach(id => {
                const index = data.findIndex(item => item.id === id);
                if (index !== -1) {
                    result.push((index + 1).toString());
                }
            })  // 去重
            const uniqueResult = [...new Set(result)];
            return uniqueResult;
        } else {
            return result;
        }
    }
    return (
        <>
            <ConfigProvider
                theme={{

                }}
            >
                <Modal
                    title={'分配权限'}
                    open={openPreview}
                    centered
                    maskClosable={true}
                    destroyOnClose
                    width={1200}
                    footer={null}
                    onCancel={() => {
                        dispatch({ type: 'openModel/getOpenDispenseModal', payload: false })
                    }}
                    afterOpenChange={async (open) => {
                        if (open) {
                            setDetail(null)
                            setSelectedIds([])
                            setCollapseKey([])
                            let res = await getPermissionListWithchilds()
                            setDetail(res.data)
                            let resrole = await getRoleGetpermissionids({ id: id })
                            console.log(findId(resrole.data.permissionIds, '53'))
                            if (!findId(resrole.data.permissionIds, '53')) {
                                handleChange(53, true)
                                resrole.data.permissionIds.push('53')
                            }
                            const nextSelectedTags = resrole.data.permissionIds && resrole.data.permissionIds.map(item => {
                                return Number(item)
                            })
                            setSelectedIds(nextSelectedTags);
                            const uniqueIndexes = checkIdInData(nextSelectedTags, res.data.permissions);
                            console.log(uniqueIndexes); // 输出去重后的结果
                            // 设置状态
                            if (uniqueIndexes.length > 0) {
                                setCollapseKey(uniqueIndexes);
                            } else {
                                setCollapseKey(["1"]);
                            }
                        }
                    }}
                    onOk={async () => {

                    }}
                >
                    {detail && collapseKey.length > 0 &&
                        <>
                            <Space direction="vertical">
                                {
                                    detail && detail.permissions.map((item: any, index: number) => (
                                        <>

                                            <Collapse
                                                defaultActiveKey={collapseKey}
                                                items={[
                                                    {
                                                        key: (index + 1).toString(),
                                                        label: (<>{item.name}</>),
                                                        children: (
                                                            <>
                                                                <Row gutter={[16, 16]}>
                                                                    <>
                                                                        <Col span={6} style={{ display: 'flex', justifyContent: 'flex-start', alignItems: 'center' }}>
                                                                            <Tag.CheckableTag checked={selectedIds.includes(item.id)} onChange={(checked) => { handleChange(item.id, checked) }}>{item.name}</Tag.CheckableTag>
                                                                        </Col>
                                                                        <Col span={18}>
                                                                            <Row gutter={[16, 16]}>
                                                                                {
                                                                                    item.childs && item.childs.length > 0 && item.childs.map((itemChild: any) => (
                                                                                        <>
                                                                                            <Col span={6} style={{ display: 'flex', justifyContent: 'flex-start', alignItems: 'center' }}>
                                                                                                <Tag.CheckableTag checked={selectedIds.includes(itemChild.id)} onChange={(checked) => { handleChange(itemChild.id, checked) }}>{itemChild.name}</Tag.CheckableTag>
                                                                                            </Col>
                                                                                            <Col span={18} style={{ display: 'flex', justifyContent: 'flex-start', alignItems: 'center' }}>
                                                                                                <Row gutter={[16, 16]}>
                                                                                                    {
                                                                                                        itemChild.childs && itemChild.childs.length > 0 && itemChild.childs.map((itemThird: any) => (
                                                                                                            <>
                                                                                                                <Col>
                                                                                                                    <Tag.CheckableTag checked={selectedIds.includes(itemThird.id)} onChange={(checked) => { handleChange(itemThird.id, checked) }}>{itemThird.name}</Tag.CheckableTag>
                                                                                                                </Col>
                                                                                                            </>
                                                                                                        ))
                                                                                                    }
                                                                                                </Row>
                                                                                            </Col>
                                                                                        </>
                                                                                    ))
                                                                                }
                                                                            </Row>
                                                                        </Col>
                                                                    </>
                                                                </Row>
                                                            </>
                                                        ),
                                                    },
                                                ]}
                                            />



                                        </>


                                    ))

                                }
                            </Space>


                        </>
                    }

                </Modal>
            </ConfigProvider >
        </>
    );
};



export default connect(({ dictModel, openModel }: any) => ({
    dictModel, openModel
}))(PagesMainPermissionRoleDispense);