import { useState, useEffect } from 'react';
import { Button, Col, Form, Input, Row, Select, Space, Card, Table, Tag, Badge, Modal, Radio, message, Flex, Typography } from 'antd';
import { getDistrictList, getDistrictDetail,saveDistrict } from '@/apis/district';
import { logger } from '@/apis/auth';
import styles from './index.less';

const DistrictPage = () => {
    const [searchForm] = Form.useForm();
    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 [districtId, setDistrictId] = useState('');
    const stageOption = [
        {
            value: 1,
            label: '小学',
        },
        {
            value: 2,
            label: '初中',
        },
        {

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


    useEffect(() => {
        init();

    }, []);

    useEffect(() => {
        if (districtId) {
            getDistrictDetailData();
        }
    }, [districtId])


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

        }
    };

    const getDistrictDetailData = async () => {
        try {
            const res = await getDistrictDetail({ id: districtId });
            if (res?.code === 200) {
                form.setFieldsValue(res.data);

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

        }
    };

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

    //     }
    // };


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

    const handleFinish = async () => {
        setConfirmLoading(true);
        form.validateFields().then(async () => {
            const res = await saveDistrict(districtId ? {
                id: districtId,
                ...form.getFieldsValue()
            } : form.getFieldsValue());
            if (res.code === 200) {
                setConfirmLoading(false);
                setOpen(false);
                init();
                setDistrictId('');
                message.success('操作成功');
                if(districtId){
                    await logger({description:"编辑区县"});
                }else{
                    await logger({description:"创建区县"});
                }
                return;
            }
            setConfirmLoading(false);
        }).catch(error => {
            setConfirmLoading(false);
            console.log(error, 'handleFinish-error');
        });
    };

    const columns = [
        {
            title: '区县',
            dataIndex: 'districtName',
            key: 'districtName',
            width: '40%',
            align: 'center',
        },
        {
            title: '状态',
            dataIndex: 'type',
            key: 'type',
            width: '30%',
            align: 'center',
            render(value) {
                if(value === 0){
                    return (<Badge status="success" text="启用" />);
                }
                if(value === 2){
                    return (<Badge status="error" text="禁用" />);
                }
            }
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            render(_, record) {
                return (
                    <Space size="middle">
                        <Button type="link" onClick={() => {
                            setOpen(true);
                            setDistrictId(record?.id);
                            setDisabled(true);
                        }}>编辑</Button>
                    </Space>
                );
            }
        },
    ];


    return (
        <div className={styles.district}>
            <header className={styles.district_header}>
                <Card style={{ height: "100%" }}>
                    <Flex justify="space-between">
                        <Typography.Title level={4} >
                            区县
                        </Typography.Title>
                        <Button type="primary" onClick={handleCreateDistrict}>
                            创建区县
                        </Button>
                    </Flex>
                </Card>
            </header>
            <main className={styles.district_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={districtId ? '编辑区县' : '创建区县'}
                open={open}
                maskClosable={false}
                centered
                destroyOnClose
                width={800}
                onOk={handleFinish}
                confirmLoading={confirmLoading}
                onCancel={() => {
                    setOpen(false);
                    setDistrictId('');
                    form.resetFields();
                }}
            >

                <Form
                    form={form}
                >
                    <Form.Item label="区县名称" name="districtName" rules={[
                        {
                            required: true,
                            message: '请填写学科',
                        },
                    ]}>
                        <Input placeholder="请输入标题" disabled={disabled} />
                    </Form.Item>
                    <Form.Item label="激活状态" name='type' rules={[
                        {
                            required: true,
                            message: "请选择激活状态"
                        },
                    ]}>
                        <Radio.Group
                            options={[
                                { value: 0, label: '启用' },
                                { value: 2, 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 DistrictPage;