import { useState, useEffect, useMemo } from 'react';
import { Button,Form, Input,Select, Space, Card, Table, Tag, Badge, Modal, Radio, message, Flex, Typography, Drawer,Pagination } from 'antd';
import { getUserList, deleteUser, resetPassword, getDistrictSelect, getSchoolSelect,getUserDetail,saveUser } from '@/apis/user';
import { logger } from '@/apis/auth';
import { getRoleSelect } from '@/apis/role';
import styles from './index.less';


const RoleTypeBadges = {
    0: <Badge color="lime" text="教师" />,
    1: <Badge color="geekblue" text="教研员" />,
    2: <Badge color="purple" text="校长" />,
    3: <Badge color="yellow" text="院长" />,
    4: <Badge color="cyan" text="局长" />,
}

const roleTypeOptions = [
    {
        value: 0,
        label: '教师',
    },
    {
        value: 1,
        label: '教研员',
    },
    {
        value: 2,
        label: '校长',
    },
    {
        value: 3,
        label: '院长',
    },
    {
        value: 4,
        label: '局长',
    },
];

const AccountPage = () => {


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

    const [disabled, setDisabled] = useState(false);

    const [districtOptions, setDistrictOptions] = useState([]);
    const [schoolOptions, setSchoolOptions] = useState([]);
    const [roleOptions, setRoleOptions] = useState([]);
    const [districts, setDistricts] = useState([]);


    const [userId, setUserId] = useState('');

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

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

    const computedTitle = useMemo(() => {
        if (userId) {
            return '编辑账号';
        }
        return '新增账号';

    }, [userId]);

    useEffect(() => {
        init();
        getDistrictSelectData();
        getRoleSelectData();
    }, []);

    useEffect(() => {
        if (userId) {
            getUserDetailData();
        }
    }, [userId]);



    useEffect(() => {
        if (districts?.length > 0) {
            getSchoolSelectData();
        }

    }, [districts])


    const init = async () => {
        try {
            setTableLoading(true);
            const res = await getUserList({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 getDistrictSelectData = async () => {
        try {
            const res = await getDistrictSelect();
            if (res.code === 200) {
                setDistrictOptions(() => {
                    return res?.data?.map(item => {
                        return {
                            label: item.districtName,
                            value: item.id
                        }
                    })
                })
                return;
            }
            message.error(res?.msg);
        } catch (error) {
            console.log(error, 'getDistrictSelectData-error');

        }
    };

    const getSchoolSelectData = async () => {
        try {
            const res = await getSchoolSelect({ baseDistrictIds: districts.join(',') });
            if (res?.code === 200) {
                setSchoolOptions(() => {
                    return res?.data?.map(item => {
                        return {
                            label: item.cname,
                            value: item.id
                        }
                    })
                })
                return;
            }
            message.error(res?.msg);
        } catch (error) {
            console.log(error, 'getSchoolSelectData-error');

        }
    };

    const getRoleSelectData = async () => {
        try {
            const res = await getRoleSelect();
            if (res?.code === 200) {
                setRoleOptions(()=>{
                    return res?.data?.map(item=>{
                        return {
                            label:item.roleName,
                            value:item.id
                        }
                    })
                })
                return;
            }
            message.error(res?.msg);
        } catch (error) {
            console.log(error, 'getSchoolSelectData-error');

        }
    };

    const getUserDetailData = async () => {
        try {
            const res = await getUserDetail({ userId, });
            if (res?.code === 200) {
                setDistricts(res.data.districts);
                form.setFieldsValue(res.data);

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

        }
    };

    const handleCreateAccount = () => {
        setOpen(true);
        setUserId('');
        form.resetFields();
        setDisabled(false);
    };

    const handleFinish = async () => {
        setConfirmLoading(true);
        
        form.validateFields().then(async () => {
            const res = await saveUser(userId ? {
                id: userId,
                ...form.getFieldsValue()
            } : form.getFieldsValue());
            if (res.code === 200) {
                setConfirmLoading(false);
                setOpen(false);
                init();
                message.success('操作成功');
                if(userId){
                    await logger({description:"创建账号"});
                }else{
                    await logger({description:"修改账号"});
                }
                return;
            }
            setConfirmLoading(false);
        }).catch(error => {
            setConfirmLoading(false);
            console.log(error, 'handleFinish-error');
        });
    };


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

            onOk() {
                return new Promise((resolve, reject) => {
                    deleteUser({ userId: 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 handleResetPassword = (record) => {
        Modal.confirm({
            title: '重置密码',
            content: '确定重置密码吗？',
            okText: '确定',
            cancelText: '取消',
            centered: true,

            onOk() {
                return new Promise((resolve, reject) => {
                    resetPassword({ userId: record?.id }).then(async(res) => {
                        if (res.code === 200) {
                            message.success('重置密码成功');
                            init();
                            resolve();
                            await logger({description:"重置密码"});
                            return
                        }
                        message.error(res?.msg);
                        reject();
                    }).catch(error => {
                        console.log(error, 'handleResetPassword-error');
                        reject();
                    })
                });
            },
        });
    };

    const onPageChange = async (pageNum, pageSize) => {
        setPageNum(pageNum);
        setPageSize(pageSize);
        try {
            setTableLoading(true);
            const res = await getUserList({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: 'account',
            key: 'account',
            width: 200,
            align: 'center',
        },
        {
            title: '使用者名称',
            dataIndex: 'userName',
            key: 'userName',
            width: 200,
            align: 'center',
        },
        {
            title: '区域',
            dataIndex: 'district',
            key: 'district',
            // width: 360,
            align: 'center',
            render(value) {
                if (!value?.length) {
                    return '-';
                }
                return <>
                    {value?.map(item => {
                        return (
                            <Space style={{ width: '100%' }} wrap>
                                <Tag bordered={false} color="cyan">
                                    {item?.name}
                                </Tag>
                                {item?.schools?.length > 0 ? (
                                    <>
                                        {item?.schools?.map(item => {
                                            return (
                                                <Tag bordered={false} color="geekblue">
                                                    {item}
                                                </Tag>
                                            )
                                        })}
                                    </>
                                ) : null}
                            </Space>
                        )
                    })}
                </>

            }
        },
        {
            title: '角色',
            dataIndex: 'roleName',
            key: 'roleName',
            width: 220,
            align: 'center',
            
        },
        {
            title: '是否为管理员',
            dataIndex: 'isAdmin',
            key: 'isAdmin',
            width: 140,
            align: 'center',
            render(value) {
                if (value === 1) {
                    return <Badge status="success" text="是" />;
                }
                if (value === 0) {
                    return <Badge status="warning" text="否" />;
                }
            }
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 80,
            align: 'center',
            render(value) {
                if (value === 0) {
                    return <Badge status="success" text="启用" />;
                }
                if (value === 1) {
                    return <Badge status="error" text="禁用" />;
                }
            }
        },
        {
            title: '使用者称谓',
            dataIndex: 'userRoleType',
            key: 'userRoleType',
            width: 120,
            align: 'center',
            render: (value) => RoleTypeBadges?.[value],
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            width: 140,
            render(_, record) {
                return (
                    <Space size="middle">
                        <Button type="link" onClick={() => {
                            setOpen(true);
                            setUserId(record?.id);
                            setDisabled(true);
                        }}>编辑</Button>

                        <Button type='link' onClick={() => handleResetPassword(record)}>重置密码</Button>
                        <Button type='link' danger onClick={() => handleDeleteUser(record)}>删除</Button>
                    </Space>
                );
            }
        },
    ];


    return (
        <div className={styles.account}>
            <header className={styles.account_header}>
                <Card style={{ height: "100%" }}>
                    <Flex justify="space-between">
                        <Typography.Title level={4} >
                            创建账号
                        </Typography.Title>
                        <Button type="primary" onClick={handleCreateAccount}>
                            创建账号
                        </Button>
                    </Flex>
                </Card>
            </header>
            <main className={styles.account_main}>
                <Card>
                    <Table scroll={{ x: 1200 }} bordered columns={columns} loading={tableLoading} dataSource={dataSource} pagination={false} style={{ height: '100%' }} />
                </Card>
            </main>
            <footer className={styles.account_footer}>

                <Pagination showQuickJumper showSizeChanger  total={total}  onChange={onPageChange} showTotal={(total)=>`共${total}条数据`} />
            </footer>

            <Drawer
                title={computedTitle}
                open={open}
                destroyOnClose
                onClose={() => {
                    setOpen(false);
                    setUserId('');
                    form.resetFields();
                }}
                size="large"
            >
                <Form
                    form={form}
                    layout="vertical"

                >
                    <Form.Item label="账号名称" name="account" rules={[
                        {
                            required: true,
                            message: '请填写账号名称',
                        },
                    ]}>
                        <Input placeholder="请输入账号名称" disabled={disabled} />
                    </Form.Item>
                    <Form.Item label="使用者名称" name="userName" rules={[
                        {
                            required: true,
                            message: '请填写使用者名称',
                        },
                    ]}>
                        <Input placeholder="请输入使用者名称" />
                    </Form.Item>
                    <Form.Item label="账号权限范围" style={{ marginBottom: 0 }}>
                        <Form.Item name='districts' rules={[
                            {
                                required: true,
                                message: '请选择区县',
                            },
                        ]} style={{ display: 'inline-block', width: 'calc(50% - 8px)' }} >
                            <Select maxTagCount={2} options={districtOptions} placeholder="请选择区县" mode="multiple" allowClear onChange={(value) => {
                                if (!value?.length) {
                                    setDistricts([]);
                                    return;
                                }
                                setDistricts(value);
                                form.setFieldValue('districts', value);

                            }} />
                        </Form.Item>

                        <Form.Item name='schools'  style={{ display: 'inline-block', width: 'calc(50% - 8px)', margin: '0 8px' }}>
                            <Select maxTagCount={1} options={schoolOptions} placeholder="请选择学校" mode="multiple" allowClear onChange={(value) => {
                                if (!value?.length) {
                                    return;
                                }
                                form.setFieldValue('schools', value);

                            }} />
                        </Form.Item>
                    </Form.Item>
                    <Form.Item label="角色" name='roleId' rules={[
                        {
                            required: true,
                            message: "请选择角色"
                        },
                    ]}>
                        <Select options={roleOptions} placeholder="请选择角色" />
                    </Form.Item>
                    <Form.Item label="是否启为管理员" name='isAdmin' rules={[
                        {
                            required: true,
                            message: "请选择是否为管理员"
                        },
                    ]}>
                        <Radio.Group
                            options={[
                                { value: 0, label: '否' },
                                { value: 1, label: '是' },
                            ]}
                        />
                    </Form.Item>
                    <Form.Item label="使用者称谓" name='userRoleType' rules={[
                        {
                            required: true,
                            message: "请选择使用者称谓"
                        },
                    ]}>
                        <Select options={roleTypeOptions} placeholder="请选择使用者称谓" />
                    </Form.Item>
                    <Form.Item label="是否启用账号" name='status' rules={[
                        {
                            required: true,
                            message: "请选择是否启用账号"
                        },
                    ]}>
                        <Radio.Group
                            options={[
                                { value: 0, label: '启用' },
                                { value: 1, label: '禁用' },
                            ]}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Flex  style={{ width: '100%' }}>
                            <Space>
                                <Button onClick={() => {
                                    setOpen(false);
                                    setUserId('');
                                    form.resetFields();
                                }}>取消</Button>
                                <Button type='primary' loading={confirmLoading} onClick={handleFinish}>确定</Button>
                            </Space>
                        </Flex>
                    </Form.Item>
                </Form>

            </Drawer>
        </div>
    );
};

export default AccountPage;