import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Select, Button, Upload, message, Row, Col, Descriptions } from 'antd';
import type { UploadProps } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { uploadFile, attachmentskView, attachmentsAdd, attachmentsEdit } from '../services';
interface props {
    visible: boolean;
    onOk: () => void;
    onCancel: () => void;
    initialValues?: any;
    readOnly?: boolean;
}
interface viewDataData {
    id?: string;
    attachmentsType?: string;
    fileName?: string;
    filePath?: string;
    fileSize?: string;
    fileType?: string;
    fileUrl?: string;
    supplierId?: string;
}
const InvoiceFormModal: React.FC<props> = ({
    visible,
    onOk,
    onCancel,
    initialValues,
    readOnly = false,
}) => {
    // 新增与修改
    const [form] = Form.useForm();
    //查看
    const [viewData, setViewData] = useState<viewDataData>({});
    useEffect(() => {
        if (visible) {
            if (initialValues) {
                attachmentskView(initialValues.id).then((res) => {
                    const { code, data } = res;
                    if (code === 200) {
                        const fields = {
                            ...data,
                            id: data.id ? data.id : null,
                            attachment: data.fileUrl
                                ? [{ 
                                    uid: '-1', 
                                    name: data.fileName, 
                                    url: data.fileUrl, status: 'done', 
                                    response: { 
                                        url: data.fileUrl,
                                        filePath: data.filePath,
                                        fileSize: data.fileSize,
                                        fileName: data.fileName,
                                        fileUrl: data.fileUrl,
                                        fileType: data.fileType,
                                     } }]
                                : [],
                        };
                        console.log(fields, 'fields');

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

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

            
            const response = values.attachment?.[0]?.response.response; // uploadFile 返回的 data
            const payload = {
                ...values,
                ...response,
                fileUrl: response.url,
                "supplierId": "9c12e8ea-a681-4184-81ba-5fa276299a00",
            };

            console.log(payload, 'values');
            if (!values.id) {
                attachmentsAdd(payload).then((res) => {
                    if (res.code == 200) {
                        message.success('新增成功');
                        onOk();
                    }
                })
            } else {
                attachmentsEdit(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,
                };
                console.log(uploadedFile);
                
                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.attachmentsType}</Descriptions.Item>
                    <Descriptions.Item label="文件名称">{viewData.fileName}</Descriptions.Item>
                    <Descriptions.Item label="文件链接"  >
                        {viewData.fileUrl ? (
                            <a href={viewData.fileUrl} target="_blank" rel="noopener noreferrer">
                                {viewData.fileName || '查看文件'}
                            </a>
                        ) : '无'}
                    </Descriptions.Item>
                </Descriptions>
            ) : (
            <Form form={form} labelCol={{ flex: '120px' }} wrapperCol={{ flex: 1 }}>
                <Row gutter={24}>
                    <Col span={24}>
                        <Form.Item name="attachmentsType" label="附件类型" rules={[{ required: true }]}>
                            <Input />
                        </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>
                    <Form.Item name="id" noStyle>
                        <Input type="hidden" />
                    </Form.Item>
                </Row>
            </Form>
            )}
        </Modal>
    );
};

export default InvoiceFormModal;
