import { api, useStaff } from "@nice/client";
import { useMainContext } from "../../layout/MainProvider";
import toast from "react-hot-toast";
import { Button, Form, Input, Modal, Select } from "antd";
import { useEffect } from "react";
import TrainContentTreeSelect from "@web/src/components/models/trainContent/train-content-tree-select";
import DepartmentChildrenSelect from "@web/src/components/models/department/department-children-select";

export default function StaffModal() {
    const { data: traincontents } = api.trainSituation.findMany.useQuery({
        select: {
            id: true,
            trainContent: {
                select: {
                    id: true,
                    title: true,
                    type: true,
                }
            },
        }
    });
    // useEffect(() => {
    //     traincontents?.forEach((situation)=>{
    //         console.log(situation.id);
    //     });
    // }, [traincontents]);

    const { form, formValue, setVisible, visible, editingRecord, setEditingRecord } = useMainContext()
    const { create, update } = useStaff();
    const handleOk = async () => {
        const values = await form.getFieldsValue();
        try {
            const staffData = {
                username: values.username,
                showname: values.username,
                department: values.deptId ? {
                    connect: { id: values.deptId }
                } : undefined,
                position: values.positionId ? {
                    connect: { id: values.positionId }
                } : undefined,
                absent: values.absent,
                trainSituations: values.trainSituations?.length > 0 ? {
                    create: values.trainSituations.map((situation) => ({
                        trainContent: {
                            connect: { id: situation.trainContentId }
                        },
                        mustTrainTime: parseFloat(situation.mustTrainTime) || 0,
                        alreadyTrainTime: 0,
                        score: 0
                    }))
                } : undefined
            };

            if (editingRecord?.id) {
                await update.mutateAsync({
                    where: { id: editingRecord.id },
                    data: {
                        ...staffData,
                        trainSituations: {
                            deleteMany: {},
                            create: values.trainSituations?.map((situation) => ({
                                trainContent: {
                                    connect: { id: situation.trainContentId }
                                },
                                mustTrainTime: parseFloat(situation.mustTrainTime) || 0,
                                alreadyTrainTime: situation.alreadyTrainTime || 0,
                                // score: situation.score || 0
                            })) || []
                        }
                    }
                });
            } else {
                await create.mutateAsync({
                    data: staffData
                });
            }

            toast.success("保存成功");
            setVisible(false);
            setEditingRecord(null);
            form.resetFields();
        } catch (error) {
            console.error("保存失败:", error);
            toast.error("保存失败");
        }
    };

    const handleCancel = () => {
        setVisible(false);
        setEditingRecord(null);
        form.resetFields();
    };

    useEffect(() => {
        if (visible && editingRecord) {
            form.setFieldsValue(editingRecord);
        }
    }, [visible, editingRecord]);
    return (
        <>
            <Modal
                title="编辑员工信息"
                open={visible}
                onOk={handleOk}
                onCancel={handleCancel}
            >
                <Form
                    form={form}
                    initialValues={formValue}
                >
                    <Form.Item
                        name={"username"}
                        label="姓名"
                    >
                        <Input className="rounded-lg" />
                    </Form.Item>
                    <Form.Item
                        name={"deptId"}
                        label="部门"
                    >
                        <DepartmentChildrenSelect></DepartmentChildrenSelect>
                    </Form.Item>
                    <Form.Item
                        name={["position", "type"]}
                        label="职务"
                    >
                        <Input className="rounded-lg" />
                    </Form.Item>
                    <Form.Item
                        name={"absent"}
                        label="在位"
                    >
                        <Select className="rounded-lg" >
                            <Select.Option value={true}>否</Select.Option>
                            <Select.Option value={false}>是</Select.Option>
                        </Select>
                    </Form.Item>

                    <Form.List name="trainSituations">
                        {(fields, { add, remove }) => (
                            <>
                                {fields.map(({ key, name, ...restField }) => (
                                    <div key={key} className="flex space-x-2">
                                        <Form.Item
                                            {...restField}
                                            name={[name, 'trainContentId']}  // 从 trainContent 改为 trainContentId
                                            label="培训内容"
                                            className="flex-1"
                                        >
                                            <TrainContentTreeSelect />
                                        </Form.Item>
                                        <Form.Item
                                            {...restField}
                                            name={[name, 'mustTrainTime']}
                                            label="需训时长"
                                            className="flex-1"
                                        >
                                            <Input type="number" />
                                        </Form.Item>
                                        <Button onClick={() => remove(name)}>删除</Button>
                                    </div>
                                ))}
                                <Button onClick={() => add()}>添加培训</Button>
                            </>
                        )}
                    </Form.List>
                </Form>
            </Modal>
            {/* <Button onClick={() =>{console.log(traincontents);}}>TEST</Button> */}
        </>
    )
}