import { useState, useEffect, useMemo } from "react";
import {
    Button,
    Col,
    Form,
    Input,
    Row,
    Select,
    Space,
    Card,
    Table,
    Tag,
    Badge,
    Modal,
    Radio,
    message,
    InputNumber,
} from "antd";
import { getSubjectList, getSubjectDetail, saveSubject } from "@/apis/subject";
import { logger } from "@/apis/auth";
import styles from "./index.less";

const SubjectPage = () => {
    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 [options, setOptions] = useState([]);

    const [subjectId, setSubjectId] = useState("");
    const stageOption = [
        {
            value: 1,
            label: "小学",
        },
        {
            value: 2,
            label: "初中",
        },
        {
            value: 3,
            label: "高中",
        },
    ];

    useEffect(() => {
        init(searchForm.getFieldsValue()?.stages);
        getSubjectSelectOptions();
    }, []);

    useEffect(() => {
        if (subjectId) {
            getSubjectDetailData();
        }
    }, [subjectId]);

    const modalTitle = useMemo(() => {
        if (!disabled) {
            return "创建学科";
        }
        return "编辑学科";
    }, [disabled]);

    const getSubjectSelectOptions = async () => {
        try {
            const res = await getSubjectList({
                stages: searchForm.getFieldsValue()?.stages,
                contain256: true,
            });
            if (res?.code === 200) {
                setOptions(() => {
                    return res?.data?.map((item) => {
                        return {
                            label: item?.cname,
                            value: item?.id,
                        };
                    });
                });
            }
        } catch (error) {
            console.log(error, "getSubjectSelectOptions-error");
        }
    };

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

    const getSubjectDetailData = async () => {
        try {
            const res = await getSubjectDetail({ id: subjectId });
            if (res?.code === 200) {
                const data = {
                    ...res.data,
                    combIds: res.data.combIds
                        ? res.data.combIds.split(",").map(Number)
                        : [],
                };
                form.setFieldsValue(data);
            }
        } catch (error) {
            console.log(error, "getSubjectDetailData-error");
        }
    };

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

    const handleFinish = async () => {
        setConfirmLoading(true);
        form
            .validateFields()
            .then(async () => {
                const selectedOptions = options?.filter((opt) =>
                    form.getFieldsValue().combIds?.includes(opt.value)
                );
                const formData = {
                    ...form.getFieldsValue(),
                    combIds: form.getFieldsValue()?.combIds?.join(","),
                    combNames: selectedOptions?.map((opt) => opt.label)?.join(","),
                };
                const res = await saveSubject(
                    subjectId
                        ? {
                            id: subjectId,
                            ...formData,
                        }
                        : {
                            ...formData,
                            subjectStage: searchForm.getFieldsValue()?.stages,
                        }
                );
                if (res.code === 200) {
                    setConfirmLoading(false);
                    setOpen(false);
                    init(searchForm.getFieldsValue()?.stages);
                    setSubjectId("");
                    message.success("操作成功");
                    if (subjectId) {
                        await logger({ description: "修改学科" });
                    } else {
                        await logger({ description: "创建学科" });
                    }
                    return;
                }
                setConfirmLoading(false);
            })
            .catch((error) => {
                setConfirmLoading(false);
                console.log(error, "handleFinish-error");
            });
    };

    const handleCreateSubject = () => {
        setSubjectId("");
        form.resetFields();
        setDisabled(false);
        setOpen(true);
    };

    const columns = [
        {
            title: "学科",
            dataIndex: "cname",
            key: "cname",
            align: "center",
        },
        {
            title: "适用范围",
            dataIndex: "stage",
            key: "stage",
            align: "center",
            render(value) {
                if (!value?.length) {
                    return "-";
                }

                return (
                    <Space>
                        {value?.split(",")?.map((item) => {
                            if (item === "1") {
                                return (
                                    <Tag bordered={false} color="cyan">
                                        小学
                                    </Tag>
                                );
                            }
                            if (item === "2") {
                                return (
                                    <Tag bordered={false} color="geekblue">
                                        初中
                                    </Tag>
                                );
                            }
                            if (item === "3") {
                                return (
                                    <Tag bordered={false} color="purple">
                                        高中
                                    </Tag>
                                );
                            }
                        })}
                    </Space>
                );
            },
        },
        {
            title: "关键字",
            dataIndex: "hitName",
            key: "hitName",
            align: "center",
            ellipsis: true,
        },
        {
            title: "排序",
            dataIndex: "orderNew",
            key: "orderNew",
            align: "center",
        },
        {
            title: "学科组合",
            dataIndex: "combNames",
            key: "combNames",
            align: "center",
            ellipsis: true,
        },
        {
            title: "学科层级",
            dataIndex: "level",
            key: "level",
            align: "center",
        },
        {
            title: "总分",
            dataIndex: "total",
            key: "total",
            align: "center",
        },
        {
            title: "是否计入总分",
            dataIndex: "inTotal",
            key: "inTotal",
            align: "center",
            render(value){
                return value === 1 ? <Badge status="success" text="是" /> :  <Badge status="error" text="否" />
            }
        },
        {
            title: "状态",
            dataIndex: "showflag",
            key: "showflag",
            align: "center",
            render(value) {
                return value ? (
                    <Badge status="success" text="启用" />
                ) : (
                    <Badge status="error" text="禁用" />
                );
            },
        },
        {
            title: "操作",
            key: "action",
            align: "center",
            render(_, record) {
                return (
                    <Space size="middle">
                        <Button
                            type="link"
                            onClick={() => {
                                setOpen(true);
                                setSubjectId(record?.id);
                                setDisabled(true);
                            }}
                        >
                            编辑
                        </Button>
                    </Space>
                );
            },
        },
    ];

    return (
        <div className={styles.subject}>
            <header className={styles.subject_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={handleCreateSubject}>
                                    创建学科
                                </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.subject_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={modalTitle}
                open={open}
                maskClosable={false}
                centered
                destroyOnClose
                width={600}
                onOk={handleFinish}
                confirmLoading={confirmLoading}
                onCancel={() => {
                    setOpen(false);
                    setSubjectId("");
                    form.resetFields();
                }}
            >
                <Form form={form} layout="vertical">
                    <Form.Item
                        label="学科名称"
                        name="cname"
                        rules={[
                            {
                                required: true,
                                message: "请填写学科",
                            },
                        ]}
                    >
                        <Input placeholder="请输入标题" />
                    </Form.Item>
                    <Form.Item
                        label="关键字"
                        name="hitName"
                        rules={[
                            {
                                required: true,
                                message: "请输入关键字",
                            },
                        ]}
                    >
                        <Input placeholder="请输入标题" />
                    </Form.Item>

                    <Form.Item
                        label="学科层级"
                        name="level"
                        rules={[
                            {
                                required: true,
                                message: "请输入学科层级",
                            },
                        ]}
                    >
                        <InputNumber
                            placeholder="请输入学科层级"
                            style={{ width: "100%" }}
                        />
                    </Form.Item>
                    <Form.Item
                        label="总分"
                        name="total"
                        rules={[
                            {
                                required: true,
                                message: "请输入总分",
                            },
                        ]}
                    >
                        <InputNumber placeholder="请输入总分" style={{ width: "100%" }} />
                    </Form.Item>
                    <Form.Item label="是否计入总分" name="inTotal">
                        <Radio.Group
                            options={[
                                { value: 1, label: "是" },
                                { value: 0, label: "否" },
                            ]}
                        />
                    </Form.Item>
                    <Form.Item
                        label="激活状态"
                        name="showflag"
                        rules={[
                            {
                                required: true,
                                message: "请选择激活状态",
                            },
                        ]}
                    >
                        <Radio.Group
                            options={[
                                { value: true, label: "启用" },
                                { value: false, label: "禁用" },
                            ]}
                        />
                    </Form.Item>
                    <Form.Item label="学科组合" name="combIds">
                        <Select
                            mode="multiple"
                            maxTagCount={7}
                            placeholder="请选择学科组合"
                            options={options}
                        />
                    </Form.Item>
                    
                    <Form.Item label="排序" name="orderNew">
                        <InputNumber placeholder="请输入排序" style={{ width: "100%" }} />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default SubjectPage;
