import ExamPlanController from "@/services/apis/ExamPlanController";
import ExamSampleController from "@/services/apis/ExamSampleController";
import { DrawerForm, ProFormCheckbox, ProFormDependency, ProFormDigit, ProFormItem, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from "@ant-design/pro-components";
import { useRequest } from "ahooks";
import { App, Space, Typography } from "antd";
import { useState } from "react";

/** 添加修改抽样方案 */
const ExamSampleEditModal: React.FC<{
    /** 抽样方案 */
    data: Partial<API.ExamSampleOutput>;
    /** 保存成功回调 */
    onFinish: () => void;
    /** 关闭回调 */
    onClose: () => void;
}> = ({ data, onFinish, onClose }) => {
    const [open, setOpen] = useState<boolean>(true);
    const handleClose = () => { setOpen(false); setTimeout(onClose, 300); };

    const { message } = App.useApp();

    const [isEnabledOnlyOneClassStudentMin, setIsEnabledOnlyOneClassStudentMin] = useState(data.config?.isEnabledOnlyOneClassStudentMin);
    const [isEnabledGradeNoSampleStudentMin, setIsEnabledGradeNoSampleStudentMin] = useState(data.config?.isEnabledGradeNoSampleStudentMin);
    const [isEnabledClassStudentMin, setIsEnabledClassStudentMin] = useState(data.config?.isEnabledClassStudentMin);

    const { data: refPlanList } = useRequest(async () => { return await ExamPlanController.getSampleRefPlanList({ id: data.examPlanId }) });

    const { config, ...restData } = data;
    return (
        <DrawerForm<API.ExamSampleOutput>
            title="监测抽样方案参数配置"
            width={800}
            open={open}
            drawerProps={{
                maskClosable: false,
                onClose: handleClose,
            }}
            initialValues={{
                config: {
                    percent: 40,
                    startPosition: 1,
                    interval: 2,
                    isRandomSampling: false,
                    isExcludeSpecialStudent: true,
                    specialStudentMustApproved: true,
                    ...config,
                },
                ...restData
            }}
            onFinish={async (values) => {
                try {
                    const { config, ...restValues } = values;
                    let p: API.AddExamSampleInput = {
                        ...restValues,
                        examPlanId: data.examPlanId ?? 0,
                        config: {
                            ...data.config,
                            ...config,
                        },
                    };
                    if ((data.id ?? 0) > 0) {
                        const up = { id: data.id ?? 0, ...p } as API.UpdateExamSampleInput;
                        await ExamSampleController.update(up);
                    }
                    else {
                        await ExamSampleController.add(p);
                    }
                    message.success('操作成功！');
                    onFinish();
                    handleClose();
                    return true;
                } catch {
                    message.error('操作失败！');
                    return false;
                }
            }}
        >
            {(data.id ?? 0) > 0 &&
                <>
                    <ProFormText
                        label={<strong>方案全称</strong>}
                        name="fullName"
                        required
                        rules={[{ required: true, message: '请输入方案全称' }]}
                    />
                    <ProFormText
                        label={<strong>方案名称</strong>}
                        name="name"
                        required
                        rules={[{ required: true, message: '请输入方案名称' }]}
                    />
                    <ProFormText
                        label={<strong>方案简称</strong>}
                        name="shortName"
                        required
                        rules={[{ required: true, message: '请输入方案简称' }]}
                    />
                </>
            }
            <ProFormSelect
                label={<strong>抽样参照成绩所在监测计划</strong>}
                name="examScoreRefExamPlanId"
                rules={[{ required: true, message: '请选择' }]}
                fieldProps={{
                    options: refPlanList?.map(t => ({ label: t.name, value: t.id })) ?? [],
                }}
            />
            <ProFormDigit
                label={<strong>抽样比例</strong>}
                name={['config', 'percent']}
                fieldProps={{ addonAfter: '%' }}
                rules={[{ required: true, message: '请输入抽样比例' }]}
            />
            <ProFormRadio.Group
                label={<strong>抽样方式</strong>}
                name={['config', 'isRandomSampling']}
                fieldProps={{
                    options: [
                        { label: '随机抽样', value: true },
                        { label: <Typography.Text>等距抽样<Typography.Text type="secondary">（班级无成绩时将采用随机抽样）</Typography.Text></Typography.Text>, value: false }
                    ],
                }}
                rules={[{ required: true, message: '请选择抽样方式' }]}
            />
            <ProFormItem label={<strong>位置间距</strong>} required>
                <Space size="large">
                    <div>
                        <label>开始抽样位置：</label>
                        <ProFormDigit
                            name={['config', 'startPosition']}
                            noStyle
                            width={96}
                            fieldProps={{ min: 1, max: 50 }}
                            // help={false}
                            rules={[{ required: true, message: '请输入开始抽样位置' }]}
                        />
                    </div>
                    <div>
                        <label>抽样间距：</label>
                        <ProFormDigit
                            name={['config', 'interval']}
                            noStyle
                            width={96}
                            fieldProps={{ min: 1, max: 50 }}
                            // help={false}
                            rules={[{ required: true, message: '请输入抽样间距' }]}
                        />
                    </div>
                </Space>
            </ProFormItem>
            <ProFormItem label={<strong>全抽配置</strong>} tooltip="以下全抽规则序号越小优先级越高">
                <Space direction="vertical">
                    <div>
                        <ProFormCheckbox
                            name={['config', 'isEnabledOnlyOneClassStudentMin']}
                            noStyle
                            fieldProps={{
                                onChange: (e) => setIsEnabledOnlyOneClassStudentMin(e.target.checked),
                            }}
                        >1. 年级仅有一个班，且该班学生人数小于等于</ProFormCheckbox>
                        <Space>
                            <ProFormDigit
                                name={['config', 'onlyOneClassStudentMin']}
                                noStyle
                                width={96}
                                fieldProps={{ min: 10, max: 100 }}
                                disabled={!isEnabledOnlyOneClassStudentMin}
                                help={false}
                                rules={[{ required: isEnabledOnlyOneClassStudentMin }]}
                            />
                            <label>人，则该班学生全抽</label>
                        </Space>
                    </div>
                    <div>
                        <ProFormCheckbox
                            name={['config', 'isEnabledGradeNoSampleStudentMin']}
                            noStyle
                            fieldProps={{
                                onChange: (e) => setIsEnabledGradeNoSampleStudentMin(e.target.checked),
                            }}
                        >2. 年级多于一个班，且年级未抽样部分学生人数小于</ProFormCheckbox>
                        <Space>
                            <ProFormDigit
                                name={['config', 'gradeNoSampleStudentMin']}
                                noStyle
                                width={96}
                                fieldProps={{ min: 10, max: 100 }}
                                disabled={!isEnabledGradeNoSampleStudentMin}
                                help={false}
                                rules={[{ required: isEnabledGradeNoSampleStudentMin }]}
                            />
                            <label>人，则该年级所有学生全抽</label>
                        </Space>
                    </div>
                    <div>
                        <ProFormCheckbox
                            name={['config', 'isEnabledClassStudentMin']}
                            noStyle
                            fieldProps={{
                                onChange: (e) => setIsEnabledClassStudentMin(e.target.checked),
                            }}
                        >3. 班级学生人数小于等于</ProFormCheckbox>
                        <Space>
                            <ProFormDigit
                                name={['config', 'classStudentMin']}
                                noStyle
                                width={96}
                                fieldProps={{ min: 10, max: 100 }}
                                disabled={!isEnabledClassStudentMin}
                                help={false}
                                rules={[{ required: isEnabledClassStudentMin }]}
                            />
                            <label>人，则该班学生全抽</label>
                        </Space>
                    </div>
                </Space>
            </ProFormItem>
            <ProFormItem label={<strong>特殊学生</strong>}>
                <Space>
                    <ProFormCheckbox name={['config', 'isExcludeSpecialStudent']} noStyle>
                        不参与抽样
                    </ProFormCheckbox>
                    <ProFormDependency name={[['config', 'isExcludeSpecialStudent'], ['config', 'specialStudentMustApproved']]}>
                        {({ config }) => (
                            <ProFormCheckbox
                                name={['config', 'specialStudentMustApproved']}
                                noStyle
                                disabled={!config?.isExcludeSpecialStudent}
                            >必须审核通过{config?.specialStudentMustApproved ? '（勾选仅审核已通过不参与抽样）' : '（未勾选待审核和审核已通过均不参与抽样）'}</ProFormCheckbox>
                        )}
                    </ProFormDependency>
                </Space>
            </ProFormItem>
            <ProFormItem label={<strong>排序设置</strong>}>
                <ProFormCheckbox name={['config', 'isGradeSeatNumberRandom']} noStyle>
                    监测顺序号在年级内随机打乱
                    <Typography.Text type="secondary">（默认在班内按前期成绩排序）</Typography.Text>
                </ProFormCheckbox>
            </ProFormItem>
            <ProFormTextArea
                label={<strong>备注说明</strong>}
                name="remark"
            />
        </DrawerForm>
    );
}

export default ExamSampleEditModal;
