import {
    Button,
    Col,
    DatePicker, Flex,
    Form,
    GetProp,
    Input,
    message,
    Radio,
    Row,
    Spin,
    Upload,
    UploadFile,
    UploadProps
} from "antd";
import {DevUserId, downloadUrl, get, uploadImageUrl} from "../../util/AjaxUtils.ts";
import {useEffect, useState} from "react";
import locale from "antd/es/date-picker/locale/zh_CN";
import dayjs, {Dayjs} from "dayjs";

type FormDataType = {
    userId: string;
    userInfoId: string;
    userInfoType: string;
    userInfoName: string;
    idCardType: string;
    idCardNumber: string;
    idCardFront: string;
    idCardBack: string;
    idCardStartDate: Dayjs;
    idCardEndDate: Dayjs;
    legalPerson: string;
    establishDate: Dayjs;
    contactAddress: string;
    contactPhone: string;
}

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const dateFormat = 'YYYY年MM月DD日';

export interface IUserEditProps {

    handleConfirm(data: FormDataType): void;
}

export default function UserEdit(props: IUserEditProps) {

    const [messageApi, contextHolder] = message.useMessage();
    const [form] = Form.useForm<FormDataType>();
    const [userInfoType, setUserInfoType] = useState('PERSONAL');
    const [idCardFrontImgArray, setIdCardFrontImgArray] = useState<UploadFile[]>([]);
    const [idCardBackImgArray, setIdCardBackImgArray] = useState<UploadFile[]>([]);
    const [loading, setLoading] = useState(false);

    const beforeUpload = (file: FileType) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('只能上传 JPG/PNG 格式文件!');
            return;
        }
        return isJpgOrPng;
    };

    useEffect(() => {
        get<any>({
            messageApi,
            url: 'api/user-info/get-self',
            onSuccess({data}) {
                form.setFieldsValue({
                    userId: data.userId,
                    userInfoId: data.userInfoId,
                    userInfoName: data.userInfoName,
                    userInfoType: data.userInfoType,
                    contactAddress: data.contactAddress,
                    contactPhone: data.contactPhone,
                    establishDate: data.establishDate ? dayjs(data.establishDate, 'YYYY-MM-DD') : '',
                    idCardNumber: data.idCardNumber,
                    idCardFront: data.idCardFront,
                    idCardStartDate: data.idCardStartDate ? dayjs(data.idCardStartDate, 'YYYY-MM-DD') : '',
                    idCardBack: data.idCardBack,
                    idCardEndDate: data.idCardEndDate ? dayjs(data.idCardEndDate, 'YYYY-MM-DD') : '',
                    idCardType: data.idCardType,
                    legalPerson: data.legalPerson,
                })
                if (data.idCardFront) {
                    const url = downloadUrl(data.idCardFront);
                    idCardFrontImgArray.splice(0, 1, {
                        uid: data.idCardFront,
                        name: 'front.png',
                        status: 'done',
                        url: url,
                        thumbUrl: url,
                    })
                    setIdCardFrontImgArray([
                        ...idCardFrontImgArray,
                    ])
                }
                if (data.idCardBack) {
                    const url = downloadUrl(data.idCardBack);
                    idCardBackImgArray.splice(0, 1, {
                        uid: data.idCardBack,
                        name: 'back.png',
                        status: 'done',
                        url: url,
                        thumbUrl: url,
                    })
                    setIdCardBackImgArray([
                        ...idCardBackImgArray,
                    ])
                }
                setUserInfoType(data.userInfoType);
            }
        })
    }, [form])

    return (
        <>
            <Form
                layout="vertical"
                form={form}
                onFinish={() => {
                    props.handleConfirm({
                        userId: form.getFieldValue('userId'),
                        userInfoId: form.getFieldValue('userInfoId'),
                        userInfoName: form.getFieldValue('userInfoName'),
                        userInfoType: form.getFieldValue('userInfoType'),
                        contactAddress: form.getFieldValue('contactAddress'),
                        contactPhone: form.getFieldValue('contactPhone'),
                        establishDate: form.getFieldValue('establishDate') ? form.getFieldValue('establishDate').format(dateFormat) : '',
                        idCardBack: form.getFieldValue('idCardBack'),
                        idCardEndDate: form.getFieldValue('idCardEndDate') ? form.getFieldValue('idCardEndDate').format(dateFormat) : '',
                        idCardFront: form.getFieldValue('idCardFront'),
                        idCardNumber: form.getFieldValue('idCardNumber'),
                        idCardStartDate: form.getFieldValue('idCardStartDate') ? form.getFieldValue('idCardStartDate').format(dateFormat) : '',
                        idCardType: form.getFieldValue('idCardType'),
                        legalPerson: form.getFieldValue('legalPerson'),
                    });
                }}
            >
                <Form.Item label="类型"
                           name="userInfoType"
                           rules={[{required: true, message: '请选择类型'}]}
                >
                    <Radio.Group onChange={(e) => {
                        setUserInfoType(e.target.value);
                        if (e.target.value === 'PERSONAL') {
                            form.setFieldValue('idCardType', 'ID_CARD');
                        }
                        if (e.target.value === 'ENTERPRISE') {
                            form.setFieldValue('idCardType', 'ORGANIZATION_CODE');
                        }
                    }}>
                        <Radio.Button value="PERSONAL">个人</Radio.Button>
                        <Radio.Button value="ENTERPRISE">企业</Radio.Button>
                    </Radio.Group>
                </Form.Item>
                <Form.Item label="名称"
                           name="userInfoName"
                           rules={[{required: true, message: '请输入名称'}]}
                >
                    <Input placeholder="请输入名称"/>
                </Form.Item>
                {
                    userInfoType == 'PERSONAL' ? (
                        <Form.Item label="证件类型"
                                   name="idCardType"
                                   rules={[{required: true, message: '请选择证件类型'}]}
                        >
                            <Radio.Group>
                                <Radio.Button value="ID_CARD">身份证</Radio.Button>
                            </Radio.Group>
                        </Form.Item>
                    ) : <></>
                }
                {
                    userInfoType == 'ENTERPRISE' ? (
                        <Form.Item label="证件类型"
                                   name="idCardType"
                                   rules={[{required: true, message: '请选择证件类型'}]}
                        >
                            <Radio.Group>
                                <Radio.Button value="ORGANIZATION_CODE">组织机构代码证</Radio.Button>
                            </Radio.Group>
                        </Form.Item>
                    ) : <></>
                }

                <Form.Item label="证件号"
                           name="idCardNumber"
                           rules={[{required: true, message: '请输入证件号'}]}
                >
                    <Input placeholder="请输入证件号"/>
                </Form.Item>
                <Row gutter={15}>
                    <Col span={12}>
                        <Form.Item label="证件照正面"
                                   name="idCardFront"
                                   rules={[{required: true, message: '请上传证件照正面'}]}
                        >
                            <Upload
                                name="image"
                                listType="picture"
                                maxCount={1}
                                defaultFileList={idCardFrontImgArray}
                                action={uploadImageUrl()}
                                headers={{'X-USER-ID': DevUserId}}
                                beforeUpload={beforeUpload}
                                onChange={(info) => {
                                    if (info.file.status === 'uploading') {
                                        setLoading(true);
                                        return;
                                    }
                                    if (info.file.status === 'done') {
                                        setLoading(false);
                                        const fileId = info.file.response.data.fileId;
                                        const url = downloadUrl(fileId);
                                        idCardFrontImgArray[0] = {
                                            uid: info.file.response.data.fileId,
                                            name: 'bg.png',
                                            status: 'done',
                                            url: url,
                                            thumbUrl: url,
                                        }
                                        setIdCardFrontImgArray([
                                            ...idCardFrontImgArray
                                        ])
                                        form.setFieldValue('idCardFront', fileId);
                                        return;
                                    }
                                }}
                                onRemove={() => {
                                    idCardFrontImgArray.splice(0)
                                    setIdCardFrontImgArray([
                                        ...idCardFrontImgArray
                                    ])
                                }}
                            >
                                <Button size="small" type="primary"
                                        style={{backgroundColor: 'var(--color-primary)'}}
                                        disabled={idCardFrontImgArray.length > 0}>上传</Button>
                            </Upload>
                        </Form.Item>
                    </Col>
                    {
                        userInfoType == 'PERSONAL' ? (
                            <Col span={12}>
                                <Form.Item label="证件照反面"
                                           name="idCardBack"
                                           rules={[{required: true, message: '请上传证件照反面'}]}
                                >
                                    <Upload
                                        name="image"
                                        listType="picture"
                                        maxCount={1}
                                        defaultFileList={idCardBackImgArray}
                                        action={uploadImageUrl()}
                                        headers={{'X-USER-ID': DevUserId}}
                                        beforeUpload={beforeUpload}
                                        onChange={(info) => {
                                            if (info.file.status === 'uploading') {
                                                setLoading(true);
                                                return;
                                            }
                                            if (info.file.status === 'done') {
                                                setLoading(false);
                                                const fileId = info.file.response.data.fileId;
                                                const url = downloadUrl(fileId);
                                                idCardBackImgArray[0] = {
                                                    uid: info.file.response.data.fileId,
                                                    name: 'bg.png',
                                                    status: 'done',
                                                    url: url,
                                                    thumbUrl: url,
                                                }
                                                setIdCardBackImgArray([
                                                    ...idCardBackImgArray
                                                ])
                                                form.setFieldValue('idCardBack', fileId);
                                                return;
                                            }
                                        }}
                                        onRemove={() => {
                                            idCardBackImgArray.splice(0)
                                            setIdCardBackImgArray([
                                                ...idCardBackImgArray
                                            ])
                                        }}
                                    >
                                        <Button size="small" type="primary"
                                                style={{backgroundColor: 'var(--color-primary)'}}
                                                disabled={idCardBackImgArray.length > 0}>上传</Button>
                                    </Upload>
                                </Form.Item>
                            </Col>
                        ) : <></>
                    }
                </Row>
                <Row gutter={15}>
                    <Col span={12}>
                        <Form.Item<FormDataType>
                            label="证件开始时间"
                            name="idCardStartDate"
                            rules={[{required: true, message: '请选择证件开始时间'}]}
                        >
                            <DatePicker placeholder="证件开始时间"
                                        format={dateFormat}
                                        locale={locale}
                                        style={{width: '100%'}}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item<FormDataType>
                            label="证件结束时间"
                            name="idCardEndDate"
                            rules={[{required: true, message: '请选择证件结束时间'}]}
                        >
                            <DatePicker placeholder="证件结束时间"
                                        format={dateFormat}
                                        locale={locale}
                                        style={{width: '100%'}}
                            />
                        </Form.Item>
                    </Col>
                </Row>
                {
                    userInfoType == 'ENTERPRISE' ? (
                        <Row gutter={15}>
                            <Col span={12}>
                                <Form.Item label="法人"
                                           name="legalPerson"
                                           rules={[{required: true, message: '请输入法人'}]}
                                >
                                    <Input placeholder="请输入法人"/>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item<FormDataType>
                                    label="成立时间"
                                    name="establishDate"
                                    rules={[{required: true, message: '请选择成立时间'}]}
                                >
                                    <DatePicker placeholder="成立时间"
                                                format={dateFormat}
                                                locale={locale}
                                                style={{width: '100%'}}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                    ) : <></>
                }
                <Row gutter={15}>
                    <Col span={12}>
                        <Form.Item label="联系地址"
                                   name="contactAddress"
                                   rules={[{required: true, message: '请输入联系地址'}]}
                        >
                            <Input placeholder="请输入联系地址"/>
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="联系电话"
                                   name="contactPhone"
                                   rules={[{required: true, message: '请输入联系电话'}]}
                        >
                            <Input placeholder="请输入联系电话"/>
                        </Form.Item>
                    </Col>
                </Row>
                <Form.Item wrapperCol={{span: 24}}>
                    <Flex align="center" justify="center" gap="large">
                        <Button type="primary"
                                htmlType="submit"
                                style={{backgroundColor: 'var(--color-primary)'}}>
                            保存
                        </Button>
                    </Flex>
                </Form.Item>
            </Form>
            <Spin tip="正在提交..." spinning={loading} fullscreen/>
            {contextHolder}
        </>
    )

}