import { useState, useEffect } from 'react';
import { Button, Col, Form, Input, Row, Select, Space, Card, Table, Tag, Badge, Modal, Radio, message } from 'antd';
import { getSchoolList, getSchoolDetail, saveSchool, getSchoolDistrictList } from '@/apis/school';
import { logger } from '@/apis/auth';
import styles from './index.less';

const SchoolPage = () => {
    const [searchForm] = Form.useForm();
    const [form] = Form.useForm();
    const [tableLoading, setTableLoading] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [dataSource, setDataSource] = useState([]);
    const [disabled, setDisabled] = useState(false);
    const [open, setOpen] = useState(false);

    const [schoolId, setSchoolId] = useState('');

    const [districtOptions, setDistrictOptions] = useState([]);
    const [schoolTypeOptions, setSchoolTypeOptions] = useState([]);

    const stageOption = [
        {
            value: 1,
            label: '小学',
        },
        {
            value: 2,
            label: '初中',
        },
        {

            value: 3,
            label: '高中'
        }
    ];


    useEffect(() => {
        init(searchForm.getFieldsValue()?.stages);
        getSchoolTypeOptions();
        getDistrictOptions();

    }, []);

    useEffect(() => {
        if (schoolId) {
            getSchoolDetailData();
        }
    }, [schoolId]);




    const getSchoolTypeOptions = async () => {
        try {

            const res = await getSchoolDistrictList({ type: 1 });
            if (res.code === 200) {
                setSchoolTypeOptions(res.data || []);
            }
        } catch (error) {
            console.log(error, 'getSchoolTypeOptions-error');

        }
    };

    const getDistrictOptions = async () => {
        try {

            const res = await getSchoolDistrictList({ type: 0 });
            if (res.code === 200) {
                setDistrictOptions(res.data || []);
            }
        } catch (error) {
            console.log(error, 'getSchoolTypeOptions-error');

        }
    };


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

        }
    };

    const getSchoolDetailData = async () => {
        try {
            const res = await getSchoolDetail({ id: schoolId });
            if (res?.code === 200) {
                form.setFieldsValue(res.data);

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

        }
    };

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

        }
    };


    const handleCreateSchool = () => {
        setSchoolId('');
        form.resetFields();
        setDisabled(false);
        setOpen(true);

    };

    const handleFinish = async () => {
        setConfirmLoading(true);
        form.validateFields().then(async () => {

            const data = disabled ? {
                id: schoolId,
                ...form.getFieldsValue(),
                stage: searchForm.getFieldsValue()?.stages,
            } : {
                ...form.getFieldsValue(),
                stage: searchForm.getFieldsValue()?.stages,
            };
            const res = await saveSchool(data);
            if (res.code === 200) {
                setConfirmLoading(false);
                setOpen(false);
                init(searchForm.getFieldsValue()?.stages);
                setSchoolId('');
                message.success('操作成功');
                if(schoolId){
                    await logger({description:"编辑学校"});
                }else{
                    await logger({description:"创建学校"});
                }
                return;
            }
            setConfirmLoading(false);
        }).catch(error => {
            setConfirmLoading(false);
            console.log(error, 'handleFinish-error');
        });
    };

    const columns = [
        {
            title: '学校名称',
            dataIndex: 'cname',
            key: 'cname',
            width: 320,
            align: 'center',
        },
        {
            title: '简称',
            dataIndex: 'shortName',
            key: 'shortName',
            width: 280,
            align: 'center',
        },
        {
            title: '学校代码',
            dataIndex: 'orderCode',
            key: 'orderCode',
            width: 160,
            align: 'center',
        },
        {
            title: '所属区县',
            dataIndex: 'district',
            key: 'district',
            width: 140,
            align: 'center',
        },
        {
            title: '学校类别',
            dataIndex: 'schoolType',
            key: 'schoolType',
            width: 100,
            align: 'center',
        },
        {
            title: '状态',
            dataIndex: 'ctype',
            key: 'ctype',
            width: 80,
            align: 'center',
            render(value) {
                if (value === 0) {
                    return (<Badge status="success" text="启用" />);
                }
                if (value === 1) {
                    return (<Badge status="error" text="禁用" />);
                }

            }
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            width: 80,
            render(_, record) {
                return (
                    <Space size="middle">
                        <Button type="link" onClick={() => {
                            setOpen(true);
                            setDisabled(true);
                            setSchoolId(record?.id);
                        }}>编辑</Button>
                    </Space>
                );
            }
        },
    ];


    return (
        <div className={styles.school}>
            <header className={styles.school_header}>
                <Card>
                    <Form form={searchForm} initialValues={{ stages: 3 }} name="advanced_search" onValuesChange={onFormValuesChange}>
                        <Row gutter={24}>
                            <Col span={8}>
                                <Form.Item
                                    name='stages'
                                    label='学段'
                                >
                                    <Select placeholder="请选择学段" options={stageOption} style={{maxWidth:120}} />
                                </Form.Item>

                            </Col>
                            <Col span={2} offset={14}>
                                <Button type="primary" onClick={handleCreateSchool}>创建学校</Button>
                            </Col>
                        </Row>
                        {/* <div style={{ textAlign: 'right' }}>
                            <Space size="small">
                                <Button type="primary" htmlType="submit">
                                    查询
                                </Button>
                                <Button
                                    onClick={() => {
                                        searchForm.resetFields();
                                    }}
                                >
                                    重置
                                </Button>
                            </Space>
                        </div> */}

                    </Form>
                </Card>
            </header>
            <main className={styles.school_main}>
                <Card>
                    <Table bordered columns={columns} loading={tableLoading} dataSource={dataSource} pagination={false} style={{ height: '100%' }} />
                </Card>
            </main>
            {/* <footer className={styles.subject_footer}></footer> */}

            <Modal
                title={!disabled ? '新增学校' : '编辑学校'}
                open={open}
                maskClosable={false}
                centered
                destroyOnClose
                width={800}
                onOk={handleFinish}
                confirmLoading={confirmLoading}
                onCancel={() => {
                    setOpen(false);
                    setSchoolId('');
                    form.resetFields();
                }}
            >

                <Form
                    form={form}
                    layout="vertical"
                >
                    <Form.Item label="学校名称" name="cname" rules={[
                        {
                            required: true,
                            message: '请填写学校名称',
                        },
                    ]}>
                        <Input placeholder="请输入学校名称" disabled={disabled} />
                    </Form.Item>
                    <Form.Item label="学校简称(多个用分号或逗号隔开)" name="shortName" rules={[
                        {
                            required: true,
                            message: '请填写学校简称',
                        },
                    ]}>
                        <Input placeholder="请输入学校简称" />
                    </Form.Item>
                    <Form.Item label="学校代码" name="orderCode" rules={[
                        {
                            required: true,
                            message: '请填写学校代码',
                        },
                    ]}>
                        <Input placeholder="请输入学校代码" />
                    </Form.Item>

                    <Form.Item label="所属区县" name="districtId" rules={[
                        {
                            required: true,
                            message: '请选择区县',
                        },
                    ]}>
                        <Select placeholder="请选择区县" options={districtOptions} style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item label="学校类别" name="schoolTypeId" rules={[
                        {
                            required: true,
                            message: '请选择学校类别',
                        },
                    ]}>
                        <Select placeholder="请选择学校类别" options={schoolTypeOptions} style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item label="激活状态" name='ctype' rules={[
                        {
                            required: true,
                            message: "请选择激活状态"
                        },
                    ]}>
                        <Radio.Group
                            options={[
                                { value: 0, label: '启用' },
                                { value: 1, label: '禁用' },
                            ]}
                        />
                    </Form.Item>
                    {/* <Form.Item label="所属学段" name='subjectStage' rules={[
                        {
                            required: true,
                            message: "请选择"
                        },
                    ]}>
                        <Checkbox.Group options={[
                            { label: '小学', value: 1 },
                            { label: '初中', value: 2 },
                            { label: '高中', value: 3 },
                        ]}/>
                    </Form.Item> */}
                </Form>

            </Modal>
        </div>
    );
};

export default SchoolPage;