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, invoiceView, invoiceAdd, invoiceEdit } from '../services';
import { getDictList } from '@/servers/api/dicts'

interface props {
    visible: boolean;
    onOk: () => void;
    onCancel: () => void;
    initialValues?: any;
    readOnly?: boolean;
}
interface Dict {
    dicName: string;
    code: string;
}
interface viewDataData {
    id?: string | null;
    account?: string;
    address?: string;
    bank?: string;
    head?: string;
    phone?: string;
    qualificationCertificate?: string;
    supplierId?: string;
    taxpayerCode?: string;
    taxpayerType?: string;
    attachment?: {
        uid: string;
        name: string;
        url: string;
        status: string;
    }[];
}
const InvoiceFormModal: React.FC<props> = ({
    visible,
    onOk,
    onCancel,
    initialValues,
    readOnly = false,
}) => {
    const userId = sessionStorage.getItem('userId') || '';
    // 新增与修改
    const [form] = Form.useForm();
    //查看
    const [viewData, setViewData] = useState<viewDataData>({});
    //纳税人option
    const [taxpayerType, setTaxpayerType] = useState<Dict[]>();

    useEffect(() => {
        if (visible) {
            if (initialValues) {
                invoiceView(initialValues.id).then((res) => {
                    const { code, data } = res;
                    if (code === 200) {
                        const fields = {
                            ...data,
                            id: data.id ? data.id : null,
                            attachment: data.qualificationCertificate
                                ? [{ uid: '-1', name: data.qualificationCertificate, url: data.qualificationCertificate, status: 'done', response: { url: data.qualificationCertificate } }]
                                : [],
                        };
                        console.log(fields, 'fields');

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

            getDictList('taxpayer_type').then((res) => {
                if (res.code == 200) {
                    setTaxpayerType(res.data)
                }
            })

        }
    }, [visible, initialValues]);

    // 提交
    const handleFinish = async () => {
        try {
            const values = await form.validateFields();
            const qualificationCertificate = values.attachment?.[0]?.response.url; // uploadFile 返回的 data
            const payload = {
                ...values,
                qualificationCertificate,
                supplierId: userId,
            };

            console.log(values, 'values');

            if (!values.id) {
                invoiceAdd(payload).then((res) => {
                    if (res.code == 200) {
                        message.success('新增成功');
                        onOk();
                    }
                })
            } else {
                invoiceEdit(payload).then((res) => {
                    if (res.code == 200) {
                        message.success('修改成功');
                        onOk();
                    }
                })
            }

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

    //上传接口
    const uploadProps: UploadProps = {
        name: 'file',
        showUploadList: true,
        beforeUpload: (file) => {
            if (file.size > 1048576) { // 1MB
                message.error('文件大小不能超过1MB');
                return Upload.LIST_IGNORE; // 阻止上传
            }
            return 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.taxpayerType}</Descriptions.Item>
                    <Descriptions.Item label="纳税人识别号">{viewData.taxpayerCode}</Descriptions.Item>
                    <Descriptions.Item label="开票电话">{viewData.phone}</Descriptions.Item>
                    <Descriptions.Item label="开户行账号">{viewData.account}</Descriptions.Item>
                    <Descriptions.Item label="开票抬头">{viewData.head}</Descriptions.Item>
                    <Descriptions.Item label="开票地址">{viewData.address}</Descriptions.Item>
                    <Descriptions.Item label="开票开户行">{viewData.bank}</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="taxpayerType" label="纳税人类型" rules={[{ required: true }]}>
                            <Select style={{ width: 150 }} placeholder="请选择纳税人类型" allowClear>
                                {taxpayerType?.map(item => (
                                    <Select.Option key={item.code} value={item.code}>{item.dicName}</Select.Option>
                                ))}
                            </Select>

                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item name="taxpayerCode" label="纳税人识别号" rules={[{ required: true }]}>
                            <Input placeholder='请输入纳税人识别号' />
                        </Form.Item>
                    </Col>

                    <Col span={24}>
                        <Form.Item name="phone" label="开票电话" rules={[{ required: true }]}>
                            <Input placeholder='请输入开票电话' />
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item name="account" label="开户行账号" rules={[{ required: true }]}>
                            <Input placeholder='请输入开户行账号' />
                        </Form.Item>
                    </Col>

                    <Col span={24}>
                        <Form.Item name="head" label="开票抬头" rules={[{ required: true }]}>
                            <Input placeholder='请输入开票抬头' />
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item name="address" label="开票地址" rules={[{ required: true }]}>
                            <Input placeholder='请输入开票地址' />
                        </Form.Item>
                    </Col>

                    <Col span={24}>
                        <Form.Item name="bank" label="开票开户行" rules={[{ required: true }]}>
                            <Input placeholder='请输入开票开户行' />
                        </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 InvoiceFormModal;
