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 DepartmentSelect from "@web/src/components/models/department/department-select";

export default function StaffModal() {
    // const { data: trainontents} = api.trainContent.findMany.useQuery({
    //     where: {
            
    //     }
    // });
    const { form, formValue, setVisible, visible, editingRecord } = useMainContext()
    const { create, update } = useStaff();
    const handleOk = async () => {
        const values = await form.getFieldsValue();
        console.log(values.username);
        try {
            if (editingRecord && editingRecord.id) {
                const result = await update.mutateAsync(
                    {
                        where: {
                            id: editingRecord.id,
                        },
                        data: {
                            username: values.username,
                            deptId: values.deptId,
                            position: values.position,
                            absent: values.absent,
                            trainSituations: values.trainSituations ? {
                                upsert: values.trainSituations.map((situation) => ({
                                    where: { id: situation.id || "" },
                                    update: {
                                        mustTrainTime: situation.mustTrainTime,
                                        trainContent: { connect: { id: situation.trainContentId } },
                                        // 其他字段...
                                    },
                                }))
                            } : undefined,
                            updatedAt: new Date()
                        } as any
                    }
                );
                // console.log(result);
            } else {
                await create.mutateAsync(
                    {
                        data: {
                            username: values.username,
                            deptId: values.deptId,
                            createdAt: new Date(),
                            showname: values.username,
                            absent: values.absent,
                            trainSituations: {
                                create: values.trainSituations.map((situation) => ({
                                    trainContent: { connect: { id: situation.trainContentId } },
                                    mustTrainTime: situation.mustTrainTime,
                                    // 其他必填字段...
                                }))
                            }
                        }
                    }
                );
            }
            toast.success("保存成功");
            setVisible(false);
        } catch (error) {
            toast.error("保存失败");
            throw error;
        }
    };

    const handleCancel = () => {
        setVisible(false);
    };
    return (
        <>
            {/* 模态框样式更新 */}
            <Modal
                title="编辑员工信息"
                visible={visible}
                onOk={handleOk}
                onCancel={handleCancel}
            >
                <Form
                    form={form}
                    initialValues={formValue}
                >
                    <Form.Item
                        name={"username"}
                        label="姓名"
                    // labelClassName="text-gray-300"
                    >
                        <Input className="rounded-lg" />
                    </Form.Item>
                    <Form.Item
                        name={"deptId"}
                        label="部门"
                    // labelClassName="text-gray-300"
                    >
                        <DepartmentSelect></DepartmentSelect>
                    </Form.Item>
                    <Form.Item
                        name={"positionId"}
                        label="职务"
                    // labelClassName="text-gray-300"
                    >
                        <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']}
                                            label="培训内容"
                                            className="flex-1"
                                        >
                                            <Select placeholder="选择培训内容">
                                                {/* 这里需要从后端获取培训内容选项 */}
                                                <Select.Option value="1">培训内容1</Select.Option>
                                            </Select>
                                        </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>
        </>
    )
}