import React, { useEffect ,useMemo} from 'react'
import { useState } from 'react';
import { Space, Table, Tag, Button, Pagination ,Modal,message ,Form,Radio,Input,InputNumber,Tree} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import './index.scss'
import { getRolesDataAPI, delRoleAPI ,getMenuLiseAPI,getRoleAPI,setRoleDataAPI} from '../../../../api/system/role.ts'
import { number } from 'echarts'
import { ExclamationCircleFilled } from '@ant-design/icons';
const { confirm } = Modal
interface getValueType {
    valueSch: any
}
interface Values {
    title: string;
    description: string;
    modifier: string;
}
interface CollectionCreateFormProps {
    open: boolean;
    onCreate: (values: Values) => void;
    onCancel: () => void;
}
const fieldNames = {
    key: 'menuId',
    title: 'menuName',
    value:'menuId',
    children: 'children'
}
let treeData:any=[]
let thisrole:any={}
const CollectionCreateForm: React.FC<CollectionCreateFormProps> = ({
    open,
    onCreate,
    onCancel,
}) => {
    const [form] = Form.useForm();
    form.setFieldsValue({...thisrole})
    const [menulist, setMenulist] = useState<any>([])
    const getMenuList = async () => {
        try {
            let menul = await getMenuLiseAPI()
            treeData = menul.data
            setMenulist(menul.data)
        } catch (error) {
            console.log(error);
            
        }

    }
    const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
    const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
    const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
    const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
    
    const onExpand = (expandedKeysValue: React.Key[]) => {
        console.log('onExpand', expandedKeysValue);
        // if not set autoExpandParent to false, if children expanded, parent can not collapse.
        // or, you can remove all expanded children keys.
        setExpandedKeys(expandedKeysValue);
        setAutoExpandParent(false);
    };
    const onCheck = (checkedKeysValue: any) => {
        console.log('onCheck', checkedKeysValue);
        form.setFieldsValue({menuIds:checkedKeysValue})
        setCheckedKeys(checkedKeysValue);
    };

    const onSelect = (selectedKeysValue: React.Key[], info: any) => {
        console.log('onSelect', info);
        
        setSelectedKeys(selectedKeysValue);
    };

    useEffect(() => {
        getMenuList()
        form.setFieldsValue({menuIds:thisrole.menuIds})
    }, [])

    return (
        <Modal
            open={open}
            title="修改角色"
            okText="确定"
            cancelText="取消"
            onCancel={onCancel}
            onOk={() => {
                form
                    .validateFields()
                    .then((values) => {
                        form.resetFields()
                        onCreate(values);
                        setSelectedKeys([])
                    })
                    .catch((info) => {
                        console.log('Validate Failed:', info);
                    });
            }}
        >
            <Form
                form={form}
                layout="horizontal"
                name="form_in_modal"
                initialValues={ {dataScope:"1",state:"0"} }
            >
                <Form.Item
                    name="roleName"
                    label="角色名称"
                    initialValue={thisrole.roleName}
                    rules={[{ required: true, message: '请输入角色名称' }]}
                >
                    <Input placeholder="请输入角色名称"/>
                </Form.Item>
                <Form.Item
                    name="roleKey"
                    label="角色权限"
                    rules={[{ required: true, message: '请输入角色权限' }]}
                    initialValue={thisrole.roleKey}
                >
                    <Input placeholder="请输入角色权限"/>
                </Form.Item>

                <Form.Item required name="roleSort" label="显示顺序" >
                    <InputNumber min={0} max={10} controls={true} />
                </Form.Item>
                <Form.Item name="dataScope" label="数据范围" initialValue={thisrole.dataScope}>
                    <Radio.Group>
                        <Radio value="1" defaultChecked={true}>所有数据权限</Radio>
                        <Radio value="2">自定义数据权限</Radio>
                        <Radio value="3">本部门数据权限</Radio>
                        <Radio value="4">本部门及以下数据权限</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item name="state" label="状态" className="collection-create-form_last-form-item" initialValue={thisrole.state}>
                    <Radio.Group>
                        <Radio defaultChecked={true} value="0">正常</Radio>
                        <Radio value="1">停用</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item name="menuIds" label="菜单权限" className="collection-create-form_last-form-item" initialValue={thisrole.menuIds}>
                        <Tree
                            fieldNames={fieldNames}
                            checkable
                            onExpand={onExpand}
                            expandedKeys={expandedKeys}
                            autoExpandParent={autoExpandParent}
                            onCheck={onCheck}
                            checkedKeys={checkedKeys}
                            onSelect={onSelect}
                            selectedKeys={selectedKeys}
                            treeData={treeData}
                        />
                </Form.Item>
            </Form>
        </Modal>
    );
};
const RoleTable: React.FC<getValueType> = ({ valueSch }) => {
    const [messageApi,contextHolder]=message.useMessage();
    console.log('111', valueSch);
    interface DataType {
        createTime: string,
        dataScope: string,
        deptIds: any[],
        menuIds: any[],
        roleId: number,
        roleKey: string,
        roleName: string,
        roleSort: string,
        state: string,
        updateTime: string,
        key?: number,
        total?: number
    }
    let [queryParams,setQueryParams]=useState<any>({
        roleKey: undefined,
        roleName: undefined,
        state: undefined,
        endTime: undefined,
        startTime: undefined,
        pageNum: undefined,
        pageSize: undefined
    })
    
    // let queryParams: any = {
    //     roleKey: undefined,
    //     roleName: undefined,
    //     state: undefined,
    //     endTime: undefined,
    //     startTime: undefined,
    //     pageNum: undefined,
    //     pageSize: undefined
    // }
    
    const handleClickDel = (role: DataType) => {
        console.log(role);
        let { roleId } = role
        del(roleId);
    }
    const showDeleteConfirm = (role:any) => {
        console.log(role);
        
        confirm({
          title: '系统提示',
          icon: <ExclamationCircleFilled />,
          content: `确定删除角色名称为${role.roleName}的数据吗`,
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            handleClickDel(role);
          },
          onCancel() {
            console.log('Cancel');
          },
        });
      };
    const del = async (roleId: number) => {
        try {
            let { code } = await delRoleAPI({ roleId })
            if (code === 1000) {
                console.log('del',valueSch);
                messageApi.open({
                    type: 'success',
                    content: '操作成功',
                  });
                getRoleData1({pageNum:count})
            }
        } catch (error) {
            console.log(error);
        }
    }
    
    const setRoleData=async(role:any)=>{
        // const {roleId,roleKey,roleName,roleSort,dataScope,state,meunIds}=role
        thisrole=role
        try {
            let { code ,data} = await getRoleAPI(role)
            if (code === 1000) {
                console.log('role:',data);
                thisrole=data
                }
        } catch (error) {
            console.log(error);
        }
        setOpen(true);
    }
    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'key',
            key: 'key',
        },
        {
            title: '角色名称',
            dataIndex: 'roleName',
            key: 'roleName',
        },
        {
            title: '角色权限',
            dataIndex: 'roleKey',
            key: 'roleKey',
        },
        {
            title: '数据范围',
            key: 'dataScope',
            dataIndex: 'dataScope',
            render:(text)=>{
                switch(text){
                    case '1':
                        return <>所有数据权限</>
                    case '2':
                        return <>自定义数据权限</>
                    case '3':
                        return <>本部门数据权限</>
                    default:
                        return <>本部门及以下数据权限</>
                }
            }
        },
        {
            title: '显示顺序',
            key: 'roleSort',
            dataIndex: 'roleSort'
        },
        {
            title: '状态',
            key: 'state',
            dataIndex: 'state',
            render: (text) => (
                <>{
                    text === '0'
                        ? <Tag color='processing'>
                            正常
                        </Tag>
                        : <Tag color='processing'>
                            停用
                        </Tag>
                }
                </>
            )
        },
        {
            title: '创建时间',
            key: 'createTime',
            dataIndex: 'createTime',
        },
        {
            title: '操作',
            key: '',
            dataIndex: '',
            render: (text) => (
                <>
                    <Button type='link' onClick={() => setRoleData(text)} >{'修改'}</Button>
                    {/* <Button type='link' danger onClick={() => handleClickDel(text)}>{'删除'}</Button> */}
                    <Button type='link' danger onClick={()=>showDeleteConfirm(text)}>{'删除'}</Button>
                    <Button type='link' >{'分配用户'}</Button>
                </>
            ),
        }
    ];
    let [data, setData] = useState<DataType[]>([])
    let [total, setTotal] = useState<number>(0)
    const getRoleData1 = async (queryParams: any) => {
        try {
            const { code, data } = await getRolesDataAPI(queryParams)
            if (code === 1000) {
                const sortData=data.rows.sort((a:DataType,b:DataType)=>parseInt(a.roleSort)-parseInt(b.roleSort))
                sortData.forEach((element: DataType, i: number) => {
                    element.key = i + 1;
                });
                setData(sortData)
                setTotal(data.total)
            }
        } catch (err: any) {
            console.log(err);
        }
    }
    let [count, setCount] = useState(1)
    const change = (page: number, pageSize: number) => {
        console.log(page, pageSize);
        queryParams={...queryParams,pageNum:page,pageSize}
        // setQueryParams({...queryParams,pageNum:page,pageSize})
        console.log(queryParams);
        getRoleData1(queryParams)
        setCount(page)
    }
    const [open, setOpen] = useState(false);
    const setDataapi=async(values:any)=>{
        try {
            console.log('ssssss',values);
            let {code}=await setRoleDataAPI(values)
            if(code===1000){
                messageApi.open({
                    type: 'success',
                    content: '操作成功',
                });
            }
        } catch (error) {
            console.log(error);
            
        }
    }
    const onCreate = (values: any) => {
        // values.menuIds=[]
        values={...thisrole,...values}
        console.log('Received values of form: ', values);
        setDataapi(values)
        getRoleData1({pageNum:count})
        setOpen(false);
    };
    useEffect(() => {
        // setQueryParams({...queryParams,...valueSch})
        queryParams={...queryParams,...valueSch,pageNum:count}
        // setCount(1)
        getRoleData1(queryParams);
        // console.log(queryParams);
    }, [valueSch])
    return (

        <div className='tablebox'>
            {contextHolder}
            <Table
                columns={columns}
                dataSource={data}
                pagination={false}
            />
            <Pagination
                style={{
                    float: 'right'
                }}
                total={total}
                current={count}
                showSizeChanger
                showQuickJumper
                onChange={(page, pageSize) => change(page, pageSize)}
                showTotal={(total) => `共 ${total} 条`}
            />
            <CollectionCreateForm
                open={open}
                onCreate={onCreate}
                onCancel={() => {
                    setOpen(false);
                }}
            />
        </div>
    )
}
export default RoleTable