import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, DatePicker, Button, Upload, message, Row, Col, Descriptions } from 'antd';
import type { UploadProps } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { uploadFile, qualificationsView, qualificationsaAdd, qualificationsEdit } from '../services';
import moment from 'moment';
interface QualificationFormModalProps {
    visible: boolean;
    onOk: () => void;
    onCancel: () => void;
    initialValues?: any;
    readOnly?: boolean;
}
interface QualificationData {
    id?: string | null;
    certificateType?: string;
    name?: string;
    code?: string;
    typeLevel?: string;
    authority?: string;
    dateTime?: moment.Moment;
    termOfValidity?: moment.Moment;
    attachment?: {
        uid: string;
        name: string;
        url: string;
        status: string;
    }[];
}
const QualificationFormModal: React.FC<QualificationFormModalProps> = ({
    visible,
    onOk,
    onCancel,
    initialValues,
    readOnly = false,
}) => {
    const userId = sessionStorage.getItem('userId') || '';
    // 新增与修改
    const [form] = Form.useForm();
    //查看
    const [viewData, setViewData] = useState<QualificationData>({});
    useEffect(() => {
        if (visible) {
            if (initialValues) {
                qualificationsView(initialValues.id).then((res) => {
                    const { code, data } = res;
                    if (code === 200) {
                        const fields = {
                            ...data,
                            id: data.id ? data.id : null,
                            dateTime: data.dateTime ? moment(data.dateTime) : undefined,
                            termOfValidity: data.termOfValidity ? moment(data.termOfValidity) : undefined,

                            attachment: data.accessory
                                ? [{ uid: '-1', name: data.accessory, url: data.accessory, status: 'done', response: { url: data.accessory } }]
                                : [],
                        };
                        console.log(fields, 'fields');

                        form.setFieldsValue(fields);
                        setViewData(fields);
                    }
                });
            } else {
                form.resetFields(); // ✅ 只有无 initialValues 才重置
            }
        }
    }, [visible, initialValues]);

    // 提交
    const handleFinish = async () => {
        try {
            const values = await form.validateFields();
            console.log(values, 'values');

            const accessory = values.attachment?.[0]?.response.url; // uploadFile 返回的 data
            const payload = {
                ...values,
                dateTime: values.dateTime ? moment(values.dateTime) : undefined,
                termOfValidity: values.termOfValidity ? moment(values.termOfValidity) : undefined,
                accessory,
                supplierId: userId,
            };
            if(!values.id) {
                qualificationsaAdd(payload).then((res) => {
                    if (res.code == 200) {
                        message.success('新增成功');
                        onOk();
                    }
                })
            } else {
                qualificationsEdit(payload).then((res) => {
                    if (res.code == 200) {
                        message.success('修改成功');
                        onOk();
                    }
                })
            }

        } catch (error) {
            console.error('表单校验失败:', error);
        }
    };

    //上传接口
    const uploadProps: UploadProps = {
        name: 'file',
        showUploadList: true,
        customRequest: async ({ file, onSuccess, onError }) => {
            try {
                const realFile = file as File;
                const res = await uploadFile(realFile);
                const uploadedFile = {
                    uid: res.fileSize,
                    name: res.fileName,
                    status: 'done',
                    url: res.url,
                    response: res,
                };
                onSuccess?.(uploadedFile, new XMLHttpRequest())
                message.success('上传成功');
            } catch (err: any) {
                onError?.(err);
                message.error(err.message || '上传失败');
            }
        }
    };

    return (
        <Modal
            title={readOnly ? '查看资质' : initialValues ? '修改资质' : '新增资质'}
            visible={visible}
            onCancel={onCancel}
            onOk={readOnly ? onCancel : handleFinish}
            footer={readOnly ? null : undefined}
            destroyOnClose
            width={600}
        >
            {readOnly ? (
                <Descriptions
                    column={1}
                    bordered
                    size="middle"
                    labelStyle={{ width: 160 }}
                >
                    <Descriptions.Item label="资质证书类型">{viewData.certificateType}</Descriptions.Item>
                    <Descriptions.Item label="资质名称">{viewData.name}</Descriptions.Item>
                    <Descriptions.Item label="资质证书编号">{viewData.code}</Descriptions.Item>
                    <Descriptions.Item label="资质类别和等级">{viewData.typeLevel}</Descriptions.Item>
                    <Descriptions.Item label="发证机构">{viewData.authority}</Descriptions.Item>
                    <Descriptions.Item label="发证日期">{viewData.dateTime ? moment(viewData.dateTime).format('YYYY-MM-DD') : ''}</Descriptions.Item>
                    <Descriptions.Item label="资质有效期至">{viewData.termOfValidity ? moment(viewData.termOfValidity).format('YYYY-MM-DD') : ''}</Descriptions.Item>
                    <Descriptions.Item label="附件">
                        {viewData.attachment?.[0]?.url ? (
                            <a href={viewData.attachment[0].url} target="_blank" rel="noopener noreferrer">
                                {viewData.attachment[0].name || '查看附件'}
                            </a>
                        ) : '无'}
                    </Descriptions.Item>
                </Descriptions>
            ) : (<Form
                form={form}
                labelCol={{ flex: '140px' }}
                wrapperCol={{ flex: 1 }}
            >
                <Form.Item name="id" noStyle>
                    <Input type="hidden" />
                </Form.Item>
                <Row gutter={24}>
                    <Col span={24}>
                        <Form.Item name="certificateType" label="资质证书类型" rules={[{ required: true }]}>
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item name="name" label="资质名称" rules={[{ required: true }]}>
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item name="code" label="资质证书编号" rules={[{ required: true }]}>
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item name="typeLevel" label="资质类别和等级" rules={[{ required: true }]}>
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item name="authority" label="发证机构" rules={[{ required: true }]}>
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item name="dateTime" label="发证日期" rules={[{ required: true }]}>
                            <DatePicker style={{ width: '100%' }} />
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item name="termOfValidity" label="资质有效期至" rules={[{ required: true }]}>
                            <DatePicker style={{ width: '100%' }} />
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item
                            name="attachment"
                            label="附件"
                            valuePropName="fileList"
                            getValueFromEvent={(e) => Array.isArray(e) ? e : e?.fileList}
                            rules={[{ required: true }]}
                        >
                            <Upload {...uploadProps} maxCount={1}>
                                <Button icon={<UploadOutlined />}>上传</Button>
                            </Upload>
                        </Form.Item>
                    </Col>
                </Row>
            </Form>)}
        </Modal>
    );
};

export default QualificationFormModal;
