
import { useRef, useState, useEffect } from 'react';
import { connect } from '@umijs/max';
import type { ActionType, ProFormInstance } from '@ant-design/pro-components';
import {
    ProFormText,
    ProFormSegmented,
    ProFormSelect,
    ProForm,
    FormControlRender,
    ProFormCascader,
    ProFormSwitch
} from '@ant-design/pro-components';
import { ConfigProvider, Flex, Space, Modal, message, Image, Row, Col, Switch, Form, Typography } from 'antd';
import { addPermission, updatePermission, getPermissionListWithchilds, GetDetailPermission } from '@/apis/api';


const selectfieldNames = { label: 'name', value: 'id' };
const cascaderfieldNames = { label: 'name', value: 'id', children: 'childs' };

export const filterChildPermissionsByType : Function = (permissions : Object[]) => {
	return permissions.map(parent => ({
	  ...parent,
	  childs: parent.childs ? filterOutPermissionsOfCertainType(parent.childs, 1) : undefined,
	}));
}

export const filterOutPermissionsOfCertainType : Function = (permissions : Object[], excludeType : number) => {
	return permissions.filter(permission => permission.p_type !== excludeType)
	  .map(child => ({
	    ...child,
	    childs: child.childs ? filterOutPermissionsOfCertainType(child.childs, excludeType) : undefined,
	  }));
}
const PagesPermissionListParent: React.FC = ({ dispatch, dictModel, openModel, id }: any) => {
    const formRef = useRef<ProFormInstance>();
    const [openPreview, setOpenPreview] = useState(false);
    const [detail, setDetail] = useState<PermissionType.list | null>(null)

    useEffect(() => {
        setOpenPreview(openModel.openParentModal)
    }, [openModel.openParentModal])


    return (
        <>
            <ConfigProvider
                theme={{
                    token: {
                        colorPrimary: '#4FBE70',
                    }, components: {
                        Segmented: {
                            itemSelectedBg: '#19be6e',
                            itemSelectedColor: '#ffffff'
                        },
                    },
                }}
            >
                <Modal
                    open={openPreview}
                    title="更换父级"
                    centered
                    maskClosable={false}
                    footer={null}
                    destroyOnClose
                    width={600}
                    onCancel={() => {
                        dispatch({ type: 'openModel/getOpenParentModal', payload: false })
                    }}
                >
                    <ProForm<PermissionType.list>
                        formRef={formRef}
                        request={async () => {
                            let res = await GetDetailPermission({ id: id.id })
                            setDetail(res.data)
                            return res.data;
                        }}
                        submitter={{
                            searchConfig: {
                                resetText: '取消',
                                submitText: '保存',
                            },
                            render: (_, dom) => { return <Flex justify='flex-end'> <Space>{dom}</Space></Flex> },
                            onReset: () => {
                                setDetail(null)
                                dispatch({ type: 'openModel/getOpenParentModal', payload: false })
                            }
                        }}
                        onFinish={async (values) => {
                            console.log(values)
                            values.id = id.id;
                            values.parent_id = values.parent_arr && values.parent_arr.length > 0 ? values.parent_arr[values.parent_arr.length - 1] : detail?.parent_id
                            delete values.parent_arr;
                            let res = await updatePermission(values)
                            message.success('提交成功')
                            dispatch({ type: 'openModel/getOpenParentModal', payload: false })
                        }}
                    >
                        <ProFormCascader
                            label="父级菜单"
                            name="parent_arr"
                            fieldProps={{
                                fieldNames: cascaderfieldNames,
                                changeOnSelect: true
                            }}
                            request={async () => {
                                let res = await getPermissionListWithchilds({ page: 1, pagesize: 9999 })
                                return filterChildPermissionsByType(res.data.permissions)
                            }}
                            placeholder="请选择要归属的父级菜单"
                        />
                    </ProForm>
                </Modal>
            </ConfigProvider>
        </>
    );
};



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