import { buildTreeData } from '@/common/converter';
import { MovableModalForm } from '@/components';
import SysOrgController from '@/services/apis/SysOrgController';
import { FormInstance, ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea, ProFormTreeSelect } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { App, Col, Row } from 'antd';
import { useRef, useState } from 'react';

/** 创建/修改机构 */
const OrgEditModal: React.FC<{
    data: Partial<API.SysOrgOutput>;
    onFinish: () => void;
    onClose?: () => void;
}> = ({ data, onFinish, onClose }) => {
    const formRef = useRef<FormInstance>();
    const { message } = App.useApp();

    const [open, setOpen] = useState(true);

    const handleClose = () => { setOpen(false); setTimeout(() => onClose?.(), 300); };
    const isEdit = (data.id ?? 0) > 0;

    const { getDictValueEnum } = useModel('useDict');

    return (
        <MovableModalForm
            title={`${isEdit ? '修改' : '创建'}机构`}
            width={960}
            open={open}
            formRef={formRef}
            initialValues={{
                ...data,
                educationStage: data.educationStage !== undefined ? `${data.educationStage}` : undefined,
                orgType: data.orgType !== undefined ? `${data.orgType}` : undefined,
                orgFundSource: data.orgFundSource !== undefined ? `${data.orgFundSource}` : undefined,
                urbanRuralType: data.urbanRuralType !== undefined ? `${data.urbanRuralType}` : undefined,
                status: data.status !== undefined ? `${data.status}` : undefined,
            }}
            modalProps={{
                centered: true,
                maskClosable: false,
                onCancel: () => {
                    formRef?.current?.resetFields();
                    handleClose();
                },
            }}
            onFinish={async (values: any) => {
                try {
                    const { educationStage, orgType, orgFundSource, urbanRuralType, status, ...restValues } = values;
                    let p: API.AddSysOrgInput = {
                        educationStage: JSON.parse(educationStage),
                        orgType: JSON.parse(orgType),
                        orgFundSource: JSON.parse(orgFundSource),
                        urbanRuralType: JSON.parse(urbanRuralType),
                        status: JSON.parse(status),
                        ...restValues
                    };
                    if ((data.id ?? 0) > 0) {
                        const up = { id: data.id ?? 0, ...p } as API.UpdateSysOrgInput;
                        await SysOrgController.update(up);
                    }
                    else {
                        await SysOrgController.add(p);
                    }
                    message.success('操作成功！');
                    formRef?.current?.resetFields();
                    onFinish();
                    handleClose();
                    return true;
                } catch {
                    message.error('操作失败！');
                    return false;
                }
            }}
        >
            <Row gutter={[24, 0]}>
                <Col span={12}>
                    <ProFormTreeSelect
                        label="父机构"
                        name="pid"
                        required
                        rules={[{ required: true }]}
                        fieldProps={{ showSearch: true }}
                        request={async () => {
                            const res = await SysOrgController.getAllList() ?? [];
                            return buildTreeData(res, 0, (item: API.SysOrgLiteOutput) => ({
                                ...item,
                                title: item.name,
                                value: item.id
                            }));
                        }}
                    />
                </Col>
                <Col span={12}>
                    <ProFormSelect
                        label="机构类型"
                        name="orgType"
                        valueEnum={getDictValueEnum('org_type')}
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <Col span={12}>
                    <ProFormSelect
                        label="办学性质"
                        name="orgFundSource"
                        valueEnum={getDictValueEnum('org_fund_source')}
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <Col span={12}>
                    <ProFormSelect
                        label="学段"
                        name="educationStage"
                        valueEnum={getDictValueEnum('education_stage')}
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <Col span={12}>
                    <ProFormSelect
                        label="城乡类别"
                        name="urbanRuralType"
                        valueEnum={getDictValueEnum('urban_rural_type')}
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <Col span={12}>
                    <ProFormText
                        label="机构编码"
                        name="code"
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <Col span={12}>
                    <ProFormText
                        label="机构全称"
                        name="fullName"
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <Col span={12}>
                    <ProFormText
                        label="机构名称"
                        name="name"
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <Col span={12}>
                    <ProFormText
                        label="机构简称"
                        name="shortName"
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <Col span={12}>
                    <ProFormText
                        label="机构简称2"
                        name="shortName2"
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <Col span={12}>
                    <ProFormDigit
                        label="排序"
                        name="sort"
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <Col span={12}>
                    <ProFormDigit
                        label="经度"
                        name="longitude"
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <Col span={12}>
                    <ProFormDigit
                        label="纬度"
                        name="latitude"
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <Col span={12}>
                    <ProFormSelect
                        label="状态"
                        name="status"
                        valueEnum={getDictValueEnum('common_status')}
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
            </Row>

            <ProFormText label="地址" name="address" />
            <ProFormTextArea label="备注" name="remark" />
        </MovableModalForm >
    );
};

export default OrgEditModal;
